From 53054337fab65daf49fb8efa9407f82b04451936 Mon Sep 17 00:00:00 2001 From: Paolo Dettori Date: Wed, 1 May 2024 10:09:32 -0500 Subject: [PATCH] exit with non-zero error when context already exists Signed-off-by: Paolo Dettori --- .gitignore | 2 ++ cmd/kflex/create/create.go | 2 +- pkg/kubeconfig/kubeconfig.go | 15 ++++++++------- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 0f6655b..8a465cd 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,5 @@ bin dist/ *.tgz .DS_Store + +.vscode/ \ No newline at end of file diff --git a/cmd/kflex/create/create.go b/cmd/kflex/create/create.go index 0efb4da..a7c6d1f 100644 --- a/cmd/kflex/create/create.go +++ b/cmd/kflex/create/create.go @@ -98,7 +98,7 @@ func (c *CPCreate) Create(controlPlaneType, backendType, hook string, hookVars [ done <- true if err := kubeconfig.LoadAndMerge(c.Ctx, clientset, c.Name, controlPlaneType); err != nil { - fmt.Fprintf(os.Stderr, "Error loading and merging kubeconfig: %s\n", controlPlaneType) + fmt.Fprintf(os.Stderr, "Error loading and merging kubeconfig: %s\n", err) os.Exit(1) } diff --git a/pkg/kubeconfig/kubeconfig.go b/pkg/kubeconfig/kubeconfig.go index ef2437a..e6900f8 100644 --- a/pkg/kubeconfig/kubeconfig.go +++ b/pkg/kubeconfig/kubeconfig.go @@ -19,7 +19,6 @@ package kubeconfig import ( "context" "fmt" - "os" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -52,7 +51,10 @@ func LoadAndMerge(ctx context.Context, client kubernetes.Clientset, name, contro return err } } else { - copyHostContextAndSetItToDefault(konfig, name) + err = copyHostContextAndSetItToDefault(konfig, name) + if err != nil { + return err + } } return WriteKubeconfig(ctx, konfig) @@ -177,10 +179,9 @@ func renameKey(m interface{}, oldKey string, newKey string) interface{} { return m } -func copyHostContextAndSetItToDefault(config *clientcmdapi.Config, name string) { +func copyHostContextAndSetItToDefault(config *clientcmdapi.Config, name string) error { if _, ok := config.Contexts[name]; ok { - fmt.Fprintf(os.Stderr, "there is already a context with name %s\n", name) - return + return fmt.Errorf("there is already a context with name %s", name) } // current context must be pointing at the hosting cluster @@ -188,8 +189,7 @@ func copyHostContextAndSetItToDefault(config *clientcmdapi.Config, name string) hostContext, ok := config.Contexts[cContext] if !ok { - fmt.Fprintf(os.Stderr, "current context with name %s not found\n", cContext) - return + return fmt.Errorf("current context with name %s not found", cContext) } config.Contexts[name] = &clientcmdapi.Context{ @@ -198,4 +198,5 @@ func copyHostContextAndSetItToDefault(config *clientcmdapi.Config, name string) } config.CurrentContext = name + return nil }