Kubernetes Tip: How to access Pod metadata in containers running inside the pod?


Today, I faced a requirement where a running container need to access Pod’s metadata. For my usecase, the running container need to know the namespace it belonged to. After spending time on Google, I learnt about Kubernetes Downward API that exposes Pod information to running container in the form of environment variables.

Let’s create a pod using following manifest file pod.yaml shown below.

apiVersion: v1
kind: Pod
metadata:
  name: myapp
spec:
  containers:
  - name: myapp
    image: busybox
    command: ["sleep","100000"]
    env:
    - name: MY_POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name
    - name: MY_POD_NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace

In the code snippet shown above, we defined two environment variables MY_POD_NAME and MY_POD_NAMESPACE. The values for the environment variables comes from the metadata fields. In the above pod definition, note that we are running sleep command to ensure that container does not exit.

You can create the pod by running the following command.

kubectl create -f pod.yaml

Once pod is created you can run the kubectl exec command to see all the environment variables available to the container.

kubectl exec myapp env|grep MY
MY_POD_NAME=myapp
MY_POD_NAMESPACE=default

Apart from Pod’s name and namespace, you can also access Pod’s IP address, node name, any many other as mentioned in the documentation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: