Help Center/ Cloud Container Instance/ Best Practices/ Workload Management/ Exposing Basic Pod Information to Containers Through Environment Variables
Updated on 2023-08-23 GMT+08:00

Exposing Basic Pod Information to Containers Through Environment Variables

If you want a pod to expose its basic information to containers running in the pod, you can use the Kubernetes Downward API to inject environment variables. This section describes how to add environment variables to the definition of a Deployment or a pod to obtain the namespace, name, UID, IP address, region, and AZ of the pod.

When CCI creates a pod and allocates it to a node, the region and AZ information of the node is added to the pod's annotations.

In this case, the format of the pod's annotations is as follows:

apiVersion: v1
 kind: Pod
 metadata:
   annotations:
     topology.kubernetes.io/region: "{{region}}"  
     topology.kubernetes.io/zone: "{{available-zone}}"

topology.kubernetes.io/region indicates the region of the node.

topology.kubernetes.io/zone indicates the AZ of the node.

Deployment Configuration Example

The following example shows how to use environment variables to obtain basic pod information.

kind: Deployment
apiVersion: apps/v1
metadata:
  name: cci-downwardapi-test
  namespace: cci-test # Enter a specific namespace.
spec:
  replicas: 2
  selector:
    matchLabels:
      app: cci-downwardapi-test
  template:
    metadata:
      labels:
        app: cci-downwardapi-test
    spec:
      containers:
        - name: container-0
          image: 'library/euleros:latest'
          command:
            - /bin/bash
            - '-c'
            - while true; do echo hello; sleep 10; done
          env:
           - name: MY_POD_UID
             valueFrom:
               fieldRef:
                 fieldPath: metadata.uid
           - name: MY_POD_NAME
             valueFrom:
               fieldRef:
                 fieldPath: metadata.name
           - name: MY_POD_NAMESPACE
             valueFrom:
               fieldRef:
                 fieldPath: metadata.namespace
           - name: MY_POD_IP
             valueFrom:
               fieldRef:
                 fieldPath: status.podIP
           - name: REGION
             valueFrom:
               fieldRef:       
                 fieldPath: metadata.annotations['topology.kubernetes.io/region']
           - name: ZONE
             valueFrom:
               fieldRef:
                 fieldPath: metadata.annotations['topology.kubernetes.io/zone']
          resources:
            limits:
              cpu: 500m
              memory: 1Gi
            requests:
              cpu: 500m
              memory: 1Gi

When the Deployment starts, you can view the pod information exposed to the container through environment variables.

Figure 1 Basic pod Information