From 1dafecf3661dac05ad537f147ce36df8c5918465 Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Thu, 28 Nov 2024 18:11:32 +0545 Subject: [PATCH] chore: refactor kubernetes client constructor --- context/context.go | 17 +++++------------ kubernetes/k8s.go | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/context/context.go b/context/context.go index 30a63317..440abf4e 100644 --- a/context/context.go +++ b/context/context.go @@ -346,25 +346,18 @@ func (k *Context) WithKubeconfig(input types.EnvVar) (*Context, error) { if k.GetNamespace() == "" { return nil, k.Oops().Errorf("namespace is required") } + val, err := k.GetEnvValueFromCache(input, k.GetNamespace()) if err != nil { return k, k.Oops().Wrap(err) } - var client kubernetes.Interface - var rest *rest.Config - - if strings.HasPrefix(val, "/") { - if client, rest, err = dutyKubernetes.NewClient(k.Logger, val); err != nil { - return k, k.Oops().Wrap(err) - } - } else { - if client, rest, err = dutyKubernetes.NewClientWithConfig(k.Logger, []byte(val)); err != nil { - return k, k.Oops().Wrap(err) - } + clientset, restConfig, err := dutyKubernetes.NewClientFromPathOrConfig(k.Logger, val) + if err != nil { + return k, k.Oops().Wrap(err) } - c := k.WithKubernetes(client, rest) + c := k.WithKubernetes(clientset, restConfig) return &c, nil diff --git a/kubernetes/k8s.go b/kubernetes/k8s.go index f245706e..7fc332d5 100644 --- a/kubernetes/k8s.go +++ b/kubernetes/k8s.go @@ -5,6 +5,7 @@ import ( "net/http" "os" "regexp" + "strings" "time" "github.com/flanksource/commons/console" @@ -100,6 +101,24 @@ func NewClientWithConfig(logger logger.Logger, kubeConfig []byte) (kubernetes.In } } +func NewClientFromPathOrConfig(logger logger.Logger, kubeconfigOrPath string) (kubernetes.Interface, *rest.Config, error) { + var client kubernetes.Interface + var rest *rest.Config + var err error + + if strings.HasPrefix(kubeconfigOrPath, "/") { + if client, rest, err = NewClient(logger, kubeconfigOrPath); err != nil { + return nil, nil, err + } + } else { + if client, rest, err = NewClientWithConfig(logger, []byte(kubeconfigOrPath)); err != nil { + return nil, nil, err + } + } + + return client, rest, err +} + func trace(clogger logger.Logger, config *rest.Config) *rest.Config { if clogger.IsLevelEnabled(7) { clogger.Infof("tracing kubernetes API calls")