Add support for running out-of-cluster with KUBERNETES_CONFIG
Allows testing the operator without dockerizing it and deploying it to a cluster.
@@ -27,6 +27,7 @@ import (
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
+ "k8s.io/client-go/tools/clientcmd"
)
var (
@@ -84,8 +85,15 @@ func apiResource(gvk schema.GroupVersionKind, restMapper *discovery.DeferredDisc
}
// mustNewKubeClientAndConfig returns the in-cluster config and kubernetes client
+// or if KUBERNETES_CONFIG is given an out of cluster config and client
func mustNewKubeClientAndConfig() (kubernetes.Interface, *rest.Config) {
- cfg, err := inClusterConfig()
+ var cfg *rest.Config
+ var err error
+ if os.Getenv("KUBERNETES_CONFIG") != "" {
+ cfg, err = outOfClusterConfig()
+ } else {
+ cfg, err = inClusterConfig()
+ }
if err != nil {
panic(err)
}
@@ -99,7 +107,7 @@ func inClusterConfig() (*rest.Config, error) {
if len(os.Getenv("KUBERNETES_SERVICE_HOST")) == 0 {
addrs, err := net.LookupHost("kubernetes.default.svc")
if err != nil {
- panic(err)
+ return nil, err
}
os.Setenv("KUBERNETES_SERVICE_HOST", addrs[0])
}
@@ -108,3 +116,9 @@ func inClusterConfig() (*rest.Config, error) {
}
return rest.InClusterConfig()
}
+
+func outOfClusterConfig() (*rest.Config, error) {
+ kubeconfig := os.Getenv("KUBERNETES_CONFIG")
+ config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
+ return config, err
+}
