gkgkgkgk
gkgkgkgk

Reputation: 717

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

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.

Upvotes: 14

Views: 17406

Answers (3)

bappr
bappr

Reputation: 315

Add this environment variable in your deployment config.

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

This is using the kubernetes downward api

Upvotes: 7

Jesse Glick
Jesse Glick

Reputation: 25451

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.

Upvotes: 14

Prafull Ladha
Prafull Ladha

Reputation: 13443

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

Upvotes: 2

Related Questions