@@ -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,44 @@ func (o *LoginOptions) SaveConfig() (bool, error) {
593594 return created , nil
594595}
595596
597+ func (o * LoginOptions ) mergeConfig (additionalConfig kclientcmdapi.Config ) (* kclientcmdapi.Config , error ) {
598+ if o .Context == "" {
599+ return cliconfig .MergeConfig (* o .StartingKubeConfig , additionalConfig )
600+ }
601+
602+ // Unwrap additionalConfig. There is expected to be just a single context, cluster and authInfo.
603+ var (
604+ newContext kclientcmdapi.Context
605+ newCluster kclientcmdapi.Cluster
606+ newAuthInfo kclientcmdapi.AuthInfo
607+ )
608+ for _ , v := range additionalConfig .Contexts {
609+ newContext = * v
610+ }
611+ for _ , v := range additionalConfig .Clusters {
612+ newCluster = * v
613+ }
614+ for _ , v := range additionalConfig .AuthInfos {
615+ newAuthInfo = * v
616+ }
617+
618+ ret := * o .StartingKubeConfig
619+
620+ // If the selected context exists, replace the linked cluster and authInfo.
621+ // When there is no match, we use the new objects, but o.Context is still used as the new context name.
622+ existingContext , ok := ret .Contexts [o .Context ]
623+ if ok {
624+ newContext .Cluster = existingContext .Cluster
625+ newContext .AuthInfo = existingContext .AuthInfo
626+ }
627+
628+ ret .Clusters [newContext .Cluster ] = & newCluster
629+ ret .AuthInfos [newContext .AuthInfo ] = & newAuthInfo
630+ ret .Contexts [o .Context ] = & newContext
631+ ret .CurrentContext = o .Context
632+ return & ret , nil
633+ }
634+
596635func (o * LoginOptions ) whoAmI (clientConfig * restclient.Config ) (* userv1.User , error ) {
597636 if o .whoAmIFunc != nil {
598637 return o .whoAmIFunc (clientConfig )
0 commit comments