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

11/13/2018

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.

-- gkgkgkgk
go
kubernetes

3 Answers

5/1/2020

Add this environment variable in your deployment config.

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

This is using the kubernetes downward api

-- bappr
Source: StackOverflow

1/26/2019

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.

-- Jesse Glick
Source: StackOverflow

11/13/2018

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

-- Prafull Ladha
Source: StackOverflow