Expose Pod information using an environment variable

2 min read | by Jordi Prats

Some applications might need to retrieve (or at least know) some of the Pod's metadata, for example, it's namespace. We can push this information using fieldPath without having to grant access to the Kubernetes API or using any template engine (such as Helm) to set it's value (at the end of the day it would be hardcoding the value on the Pod's definition)

If we want to push, for example, the Pod's namespace as a environment variable we can define it using fieldPath and it's manifest path: metadata.namespace:

env:
- name: SYSTEM_NAMESPACE
  valueFrom:
    fieldRef:
      fieldPath: metadata.namespace

By setting this environment variable the processes running on it's containers can read this environment variable to get the Pod's namespace.

We can also use any other field that it is present on the manifest, such as the serviceAccountName:

env:
- name: POD_SERVICE_ACCOUNT
  valueFrom:
    fieldRef:
      fieldPath: spec.serviceAccountName

But not only on the spec section, we can also use the status section where we can find, for example, it's IP:

env:
- name: POD_IP
  valueFrom:
    fieldRef:
      fieldPath: status.podIP

We can use any field we can see when we get the using kubectl -o yaml

Some values from the Pod's metadata can also be pushed into a container as a Volume


Posted on 04/01/2022