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

10,823

Solution 1

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

Solution 2

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

Share:
10,823
John Erik Halse
Author by

John Erik Halse

Updated on June 30, 2022

Comments

  • John Erik Halse
    John Erik Halse almost 2 years

    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.

  • Tiger93
    Tiger93 almost 9 years
    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
  • yzorg
    yzorg almost 3 years
    I believe the accepted answer is stale. @ankon's answer is universal, and should be recommended. Use downward API only if you need an envvar, or need to control how it is read. This answer was best answer in 2015, but I think the namespace file is better for programmatic access going forward.