Search code examples
gokubernetesclient-go

How to get current namespace of an out-cluster go Kubernetes client?


How can I get the current namespace of an out-of-cluster Go Kubernetes client using the client-go library?

I am using this code example: https://github.com/kubernetes/client-go/blob/master/examples/out-of-cluster-client-configuration/main.go for out-cluster client.

Here is an extract of my KUBECONFIG which might help in clarifying:

- context:
    cluster: kind-kind
    namespace: mynamespace
    user: kind-kind
  name: kind-kind
current-context: kind-kind

I'd like to find an easy way to retrieve mynamespace.


Solution

  • Thanks to @rick-rackow answer and comment, I was able to improve my understanding of the kubeconfig API, so here is a simple solution which works fine for me:

    package main
    
    import (
        "flag"
        "fmt"
        "path/filepath"
    
        "k8s.io/client-go/tools/clientcmd"
        "k8s.io/client-go/util/homedir"
    )
    
    func main() {
        var kubeconfig *string
        if home := homedir.HomeDir(); home != "" {
            kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
        } else {
            kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
        }
        flag.Parse()
    
        ns := getCurrentNamespace(*kubeconfig)
        fmt.Printf("NAMESPACE: %s", ns)
    }
    
    // Get the default namespace specified in the KUBECONFIG file current context
    func getCurrentNamespace(kubeconfig string) string {
    
        config, err := clientcmd.LoadFromFile(kubeconfig)
        if err != nil {
            panic(err.Error())
        }
        ns := config.Contexts[config.CurrentContext].Namespace
    
        if len(ns) == 0 {
            ns = "default"
        }
    
        return ns
    }