From 2673c466d20e2cf4df130b6eb56fe457bb72a1a0 Mon Sep 17 00:00:00 2001 From: Blaine Gardner Date: Thu, 4 May 2023 15:22:45 -0600 Subject: [PATCH] operator: use KUBECONFIG context for cli if present Use contents of KUBECONFIG var for creating Kubernetes client interface if its present. This allows running rook CLI commands locally for quicker development iteration. Signed-off-by: Blaine Gardner (cherry picked from commit b72761c1a1974fd1fe00e3ac4522b3b464192ad1) --- cmd/rook/rook/rook.go | 32 +++++++++++++++++++ .../multus/validation/validation.go | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) 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)