The Kubernetes Downward API allows a pod to get access to metadata about itself and the cluster without creating a tight coupling to the Kubernetes API. For example, information such as pod name, labels, annotations, IP address, node, and cpu/memory limits can be made available inside the pod.
In this article, I’ll show how to expose pod and container metadata through either environment properties or volume mounts.
Pod fields and Container fields
There are two types of metadata that can be exposed with the Downward API: pod metadata and container metadata.
Pod metadata includes name, namespace, node, IP address, labels, annotations. While container metadata will contain items such as cpu and memory limits for the container.
Exposed as environment variables
To expose this pod/container metadata as an environment variable from inside the pod, create definitions like below in the deployment manifest.
# at yaml path '.spec.template.spec.containers[].env' env: # pulling pod fields - name: MY_NODE_NAME valueFrom: fieldRef: fieldPath: spec.nodeName # pulling container fields from containers[].name - name: "mem_limit" valueFrom: resourceFieldRef: containerName: golang-hello-world-web resource: limits.memory divisor: 1Mi
See my downward-golang-web.yaml for examples of more env vars that can be pulled.
Exposed as Volume mounted file
The other way to expose this metadata is as a volume mounted file.
# pull metadata # at yaml path '.spec.template.spec.volumes' volumes: - name: podinfo downwardAPI: items: # pulling pod fields - path: "nodeName" fieldRef: fieldPath: metadata.nodeName # pulling container fields from containers[].name - path: "mem_limit" resourceFieldRef: containerName: golang-hello-world-web resource: limits.memory divisor: 1Mi # mount for files # at yaml path '.spec.template.spec.containers[].volumeMounts # mount for Downward files volumeMounts: - name: podinfo mountPath: /etc/podinfo
See my downward-golang-web.yaml for examples of more variables that can be pulled.
Accessing from inside pod
Now these OS level environment variables and files found in the directory “/etc/podinfo” can be read just like any other env or file.
If you are in an interactive shell for any Linux based container, type “env” to view the environment variables. And “ls -l /etc/podinfo” to view the files.
If you are using a GoLang application, you can see examples of reading env vars and files in my main.go. Here is the detailed blog article.
If you are using a Python application, you can see examples of reading env vars and files in my app.py. Here is the detailed blog article.
REFERENCES
kubernetes.io, expose pod info to containers through env vars