How do I pass the region information as environment variable to a container running in Kubernetes?

4/12/2018

I have a use case where I publish messages from containers deployed in various regions and I would like to tag those messages from the region they originated from. Also, I want to do this in a container engine agnostic way so specifically want to access the region info as an environment variable.

-- Hajmola
kubernetes

1 Answer

4/13/2018

You can expose pod information as an environment variable using the Downward API

However, this isn't supported for node labels, as per these github issues.

What you can do is follow this example and labels your pods/deployments (and also maybe pin those pods/deployments using a NodeSelector) and then expose that info. An example:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars-fieldref
  labels:
    zone: us-west-2
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c", $(ZONE)]
      env:
        - name: ZONE
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels.zone
  restartPolicy: Never

Please note, I haven't tested this so YMMV

-- jaxxstorm
Source: StackOverflow