How to get the namespace from inside a pod in OpenShift?

John Erik Halse picture John Erik Halse · Jul 22, 2015 · Viewed 9.1k times · Source

I would like to access to OpenShift and Kubernetes API from inside a pod to query and modify objects in the application the pod belongs to.

In the documentation (https://docs.openshift.org/latest/dev_guide/service_accounts.html) I found this description on how to access the api:

$ TOKEN="$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"

$ curl --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
"https://openshift.default.svc.cluster.local/oapi/v1/users/~" \
-H "Authorization: Bearer $TOKEN"

The problem is when I for example want to access a pod, I need to know the namespace I'm in:

https://openshift.default.svc.cluster.local/oapi/v1/namespaces/${namespace}/pods

The only way I found so far is to submit the namespace as an environment variable, but I would like to not requiring the user to enter that information.

Answer

ankon picture ankon · Feb 24, 2017

At least in kubernetes 1.5.3 I can also see the namespace in /var/run/secrets/kubernetes.io/serviceaccount/namespace.