diff --git a/cmd/rook/rook/rook.go b/cmd/rook/rook/rook.go index 2444fe132..0e64135bc 100644 --- a/cmd/rook/rook/rook.go +++ b/cmd/rook/rook/rook.go @@ -38,6 +38,7 @@ import ( v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" ) const ( @@ -181,3 +182,34 @@ func GetOperatorBaseImageCephVersion(context *clusterd.Context) (string, error) return output, nil } + +// GetInternalOrExternalClient will get a Kubernetes client interface from the KUBECONFIG variable +// if it is set, or from the operator pod environment otherwise. +func GetInternalOrExternalClient() kubernetes.Interface { + kubeconfig := os.Getenv("KUBECONFIG") + + var ( + config *rest.Config + err error = fmt.Errorf("did not attempt to load a client") // just in case + ) + + if kubeconfig != "" { + for _, kConf := range strings.Split(kubeconfig, ":") { + config, err = clientcmd.BuildConfigFromFlags("", kConf) + if err == nil { + break + } + } + } else { + config, err = rest.InClusterConfig() + } + if err != nil { + TerminateOnError(err, "error creating client") + } + + client, err := kubernetes.NewForConfig(config) + if err != nil { + TerminateOnError(err, "could not get Kubernetes client interface") + } + return client +} diff --git a/cmd/rook/userfacing/multus/validation/validation.go b/cmd/rook/userfacing/multus/validation/validation.go index 11b123de9..834dc7d23 100644 --- a/cmd/rook/userfacing/multus/validation/validation.go +++ b/cmd/rook/userfacing/multus/validation/validation.go @@ -90,7 +90,7 @@ particularly noticeable with high I/O load or during OSD rebalancing ) func init() { - validationConfig.Clientset = rook.NewContext().Clientset + validationConfig.Clientset = rook.GetInternalOrExternalClient() Cmd.AddCommand(runCmd) Cmd.AddCommand(cleanupCmd)