Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current k8s context name using client-go

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.

like image 268
pkaramol Avatar asked Feb 01 '26 02:02

pkaramol


1 Answers

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
like image 55
Rafał Leszko Avatar answered Feb 03 '26 04:02

Rafał Leszko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!