I have searched everywhere and cannot figure out how to switch context in a configuration with multiple clusters.
Is there some way in code to be able to set the context that you want to use?
Try this
func buildConfigFromFlags(context, kubeconfigPath string) (*rest.Config, error) {
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},
&clientcmd.ConfigOverrides{
CurrentContext: context,
}).ClientConfig()
}
I came across this problem recently, I have multiple kubeconfig file, but I don't want to reload the files every time I change context. So I look in the client-go code and I do it this way.
config := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{Precedence: kubeconfigFiles},
&clientcmd.ConfigOverrides{})
clientapiConfig, err = config.RawConfig() // save the result
// every time I need to change context do this
override := &clientcmd.ConfigOverrides{CurrentContext: contextName}
clientConfig := clientcmd.NewNonInteractiveClientConfig(clientapiConfig, override.CurrentContext,
override, &clientcmd.ClientConfigLoadingRules{})
It work for me, but not sure it's the right way.
Issues go stale after 90d of inactivity.
Mark the issue as fresh with /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.
If this issue is safe to close now please do so with /close.
Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle stale
Stale issues rot after 30d of inactivity.
Mark the issue as fresh with /remove-lifecycle rotten.
Rotten issues close after an additional 30d of inactivity.
If this issue is safe to close now please do so with /close.
Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle rotten
/remove-lifecycle stale
Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.
Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close
the correct way goes through cmdclient.ModifyConfig, which takes care of config file locking etc...
here is my code:
func (k *K8s) SwitchContext(ctx string) (err error) {
if k.RawConfig.Contexts[ctx] == nil {
return fmt.Errorf("context %s doesn't exists", ctx)
}
k.RawConfig.CurrentContext = ctx
err = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), k.RawConfig, true)
return
}
@kuritka
I鈥檓 wondering could you plz show me more about the "k *k8s"
Most helpful comment
Try this