John Erik Halse
John Erik Halse

Reputation: 143

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

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.

Upvotes: 14

Views: 21120

Answers (3)

ankon
ankon

Reputation: 4235

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

Upvotes: 46

Alex Robinson
Alex Robinson

Reputation: 13397

You can get the namespace of your pod automatically populated as an environment variable using the downward API.

Upvotes: 20

John Erik Halse
John Erik Halse

Reputation: 143

I found a solution by tracing what the web console does.

I am allowed to ask for the project list without having cluster-admin rigths on the following url:

https://openshift.default.svc.cluster.local/oapi/v1/projects

Only the projects which I have rights to are listed, and then it is possible to determine the current project which name is also the namespace.

Would love if there was an easier solution, but this works.

Upvotes: 0

Related Questions