pkaramol
pkaramol

Reputation: 19312

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.

Upvotes: 2

Views: 3933

Answers (2)

SaravAK
SaravAK

Reputation: 1

You can Get your current context like this too easily using the GetConfigFromFileOrDie method

Once the Config is loaded - you can get the current context with config.CurrentContext

kubeconfig := filepath.Join(os.Getenv("HOME"), ".kube", "config")


if config := clientcmd.GetConfigFromFileOrDie(kubeconfig); conf != nil{
    fmt.Println("Current Context is",config.CurrentContext)
}

Further reference on this method is here

Upvotes: 0

Rafał Leszko
Rafał Leszko

Reputation: 5521

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

Upvotes: 10

Related Questions