Skip to content

Commit

Permalink
exit with non-zero error when context already exists
Browse files Browse the repository at this point in the history
Signed-off-by: Paolo Dettori <[email protected]>
  • Loading branch information
pdettori committed May 1, 2024
1 parent fc24980 commit 5305433
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ bin
dist/
*.tgz
.DS_Store

.vscode/
2 changes: 1 addition & 1 deletion cmd/kflex/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
15 changes: 8 additions & 7 deletions pkg/kubeconfig/kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package kubeconfig
import (
"context"
"fmt"
"os"

v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -177,19 +179,17 @@ 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
cContext := config.CurrentContext

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{
Expand All @@ -198,4 +198,5 @@ func copyHostContextAndSetItToDefault(config *clientcmdapi.Config, name string)
}

config.CurrentContext = name
return nil
}

0 comments on commit 5305433

Please sign in to comment.