kubernetes / client-go

Go client for Kubernetes.
Apache License 2.0
9.13k stars 2.95k forks source link

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

Closed davidmichaelkarr closed 5 months ago

davidmichaelkarr commented 5 months 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 5 months 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 5 months ago

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

ldemailly commented 5 months 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 5 months ago

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