kubernetes / client-go

Go client for Kubernetes.
Apache License 2.0
8.78k stars 2.9k forks source link

How can I get the namespace of the context I'm using? #1359

Closed davidmichaelkarr closed 2 weeks ago

davidmichaelkarr commented 3 weeks ago

I'm trying to use client-go v0.24.0 to talk to my v1.24.x Kubernetes cluster. I can hack the code in the "out-of-cluster-client-configuration" sample to hardcode the namespace, and that works, but I really need to use the namespace specified in the "namespace" property of the context from the ~/.kube/config . I've been looking through the "Config" type returned from "BuildConfigFromFlags", but I can't see any indication in that of the namespace for the context. I find it hard to believe that I'd have to get this info by separately parsing the config file. That is certainly doable, but I would think it should be available through a more direct interface.

ldemailly commented 3 weeks ago

This seems to work

    cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
        &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfigPath}, nil)

    rCfg, err := cfg.RawConfig()
    if err != nil {
        fmt.Printf("error getting raw config: %v\n", err)
        os.Exit(1)
    }
    namespace := rCfg.Contexts[rCfg.CurrentContext].Namespace
    kubeConfig, err := cfg.ClientConfig()

(ie opening up BuildConfigFromFlags and making it do return the internal config object instead of just the ClientConfig)

ldemailly commented 3 weeks ago

complete example: https://github.com/ldemailly/go-scratch/blob/kubectl/kubectl/kubectl.go

ldemailly commented 3 weeks ago

you can also even more simply call:

    namespace, nsOver, err := cfg.Namespace()

but that one won't be empty, it defaults to default (not sure when the override is true)

davidmichaelkarr commented 3 weeks ago

This all works fine, thanks. I also wonder what the override flag is for. I'll get to that at some point.