diff --git a/pkg/kubeconfig/write.go b/pkg/kubeconfig/write.go index 9a3e70c..f6f953b 100644 --- a/pkg/kubeconfig/write.go +++ b/pkg/kubeconfig/write.go @@ -53,10 +53,16 @@ func (k *KConf) Merge(config *clientcmdapi.Config, name string) { if renamed, ok := renamedUsers[ctx.AuthInfo]; ok { ctx.AuthInfo = renamed } - if name == "" { - name = ctxName + // the context name is chosen based on the following priority: + // 1. provided via --context-name + // 2. specified in the provided config file + // 3. generated from the cluster and user name (-) + if name != "" { + ctxName = name + } else if ctxName == "" && name == "" { + ctxName = fmt.Sprintf("%s-%s", ctx.Cluster, ctx.AuthInfo) } - added := k.AddContext(name, ctx) + added := k.AddContext(ctxName, ctx) if added != "" { // this context was newly added if added != ctxName { Out.Log().Msgf("renamed context '%s' to '%s'", ctxName, added) diff --git a/pkg/kubeconfig/write_test.go b/pkg/kubeconfig/write_test.go index 1bd7a65..77bea59 100644 --- a/pkg/kubeconfig/write_test.go +++ b/pkg/kubeconfig/write_test.go @@ -180,6 +180,22 @@ func TestMerge(t *testing.T) { AssertContext(t, k, "test") AssertContext(t, k, "test-1") // renamed context }, + "merge multiple unique contexts": func(t *testing.T) { + k := MockConfig(1) + k2 := MockConfig(3) + + // we need k and k2 to be two unique configs, so delete the first config in k2 + err := k2.Remove("test") + if err != nil { + t.Fatal(err) + } + + k.Merge(&k2.Config, "") + + AssertContext(t, k, "test") + AssertContext(t, k, "test-1") + AssertContext(t, k, "test-2") + }, "rename cluster if it already exists": func(t *testing.T) { k := MockConfig(1) k2 := MockConfig(2)