How to get current namespace from running pod usin client api

9/5/2019

I am using kubernetes java client libraries in order to communicate with my kubernetes server.

My question is there any way programmatically get namespace of running pod from inside of which sent call to kubernetes?

I heard that there is file located here - /var/run/secrets/kubernetes.io/serviceaccount/namespace

However I wanted to know is there any way ro get it using java client without reading this file.

I have searched in documentation, however found nothing related to this.

-- liotur
deployment
docker
kubectl
kubernetes

2 Answers

9/5/2019

If you set the below environment variable on the pod definition file, the namespace of the pod will be stored on the environment variables. Then it can be retrieved by the client API.

 env
  - name: MYPOD_NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
-- Subramanian Manickam
Source: StackOverflow

9/5/2019

A quick search of the Go, Python, and Java clients seems to indicate that this isn't supported for in-cluster clients unfortunately.

This makes sense, as the namespace which the in-cluster client is running in won't necessarily be related to the namespace which the credentials of the client are scoped to, i.e. a role, role binding, and service account.

So I can see why such a method/endpoint doesn't exist within the various clients, as it could be quite confusing. Thus your best and only option seems to be /var/run/secrets/kubernetes.io/serviceaccount/namespace

-- cewood
Source: StackOverflow