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

Viewed 11073

How do I get the current namespace of a deployment/service using the kubernetes client-go API? It doesn't seem to be in the client object or in the config.

3 Answers

Using

ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")

works but is ugly, when the desired implementation is present in the Namespace() method of inClusterClientConfig. But how would you get that object starting from rest.InClusterConfig()? It is only instantiable from outside the package via NewNonInteractiveDeferredLoadingClientConfig.

I see kubernetes #63707 which looks related but was abandoned.

You can always set the context for each namespace and then read from kubeconfig on which context you are currently on:

Use the following code to find out on which namespace you are on:

namespace, _, err := kubeconfig.Namespace()
    if err != nil {
            panic(err)
    }

This will return the namespace in which you're.

For more information refer :

https://github.com/kubernetes/client-go/blob/master/tools/clientcmd/client_config.go

Add this environment variable in your deployment config.

 - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace

This is using the kubernetes downward api

Related