How to get current k8s context name using client-go

Issue

I am trying to get / print the name of my current kubernetes context as it is configured in ~/.kube/config using client-go

I hava managed to authenticate and get the *rest.Config object

    config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
        &clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig},
        &clientcmd.ConfigOverrides{
            CurrentContext: "",
        }).ClientConfig()

but I don’t see any relevant fields in the config struct.

Note that despite the fact I am passing an empty string ("") in the ConfigOverrides the config object returned provides me a kubernetes.Clientset that is based on my current kubectl context.

Solution

The function ClientConfig() returns the Kubernetes API client config, so it has no information about your config file.

To get the current context, you need to call RawConfig(), then there is a field called CurrentContext.

The following code should work.

    config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
        &clientcmd.ClientConfigLoadingRules{ExplicitPath: pathToKubeConfig},
        &clientcmd.ConfigOverrides{
            CurrentContext: "",
        }).RawConfig()
    currentContext := config.CurrentContext

Answered By – RafaƂ Leszko

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.