@@ -75,6 +75,7 @@ type LoginOptions struct {
7575 StartingKubeConfig * kclientcmdapi.Config
7676 DefaultNamespace string
7777 Config * restclient.Config
78+ Context string
7879
7980 // cert data to be used when authenticating
8081 CertFile string
@@ -570,7 +571,7 @@ func (o *LoginOptions) SaveConfig() (bool, error) {
570571 return false , err
571572 }
572573
573- configToWrite , err := cliconfig . MergeConfig ( * o . StartingKubeConfig , * newConfig )
574+ configToWrite , err := o . mergeConfig ( * newConfig )
574575 if err != nil {
575576 return false , err
576577 }
@@ -593,6 +594,39 @@ func (o *LoginOptions) SaveConfig() (bool, error) {
593594 return created , nil
594595}
595596
597+ // mergeConfig merges StartingKubeConfig with additionalConfig,
598+ // which must contain just a single context, cluster and authInfo.
599+ func (o * LoginOptions ) mergeConfig (additionalConfig kclientcmdapi.Config ) (* kclientcmdapi.Config , error ) {
600+ if o .Context == "" {
601+ return cliconfig .MergeConfig (* o .StartingKubeConfig , additionalConfig )
602+ }
603+
604+ // Set the custom context name in additionalConfig. This needs to happen in any case.
605+ for _ , v := range additionalConfig .Contexts {
606+ additionalConfig .Contexts = map [string ]* kclientcmdapi.Context {
607+ o .Context : v ,
608+ }
609+ }
610+
611+ // If there is a matching context, replace the linked cluster and authInfo.
612+ existingContext , ok := o .StartingKubeConfig .Contexts [o .Context ]
613+ if ok {
614+ for _ , v := range additionalConfig .Clusters {
615+ additionalConfig .Clusters = map [string ]* kclientcmdapi.Cluster {
616+ existingContext .Cluster : v ,
617+ }
618+ }
619+ for _ , v := range additionalConfig .AuthInfos {
620+ additionalConfig .AuthInfos = map [string ]* kclientcmdapi.AuthInfo {
621+ existingContext .AuthInfo : v ,
622+ }
623+ }
624+ }
625+
626+ additionalConfig .CurrentContext = o .Context
627+ return cliconfig .MergeConfig (* o .StartingKubeConfig , additionalConfig )
628+ }
629+
596630func (o * LoginOptions ) whoAmI (clientConfig * restclient.Config ) (* userv1.User , error ) {
597631 if o .whoAmIFunc != nil {
598632 return o .whoAmIFunc (clientConfig )
0 commit comments