9

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.

3 Answers3

30

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

ankon
  • 3,782
  • 24
  • 24
15

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

Alex Robinson
  • 10,892
  • 2
  • 31
  • 49
0

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.

  • 1
    Use the downward API to populate the environment variable... you can't assume you will have rights to read project lists from within a pod – Jordan Liggitt Jul 23 '15 at 01:25