在容器中通过环境变量获取Pod基础信息
客户如果需要在容器内获取POD的基础信息,可以通过kubernetes中的Downward API注入环境变量的方式实现。本操作实践展示如何在Deployment和POD的定义中增加环境变量配置,获取Pod的namespace、name、uid、IP、Region和AZ。
CCI创建Pod并分配节点的同时,Pod Annotations中新增所在节点的region和az信息。
此时Pod中Annotations格式为:
apiVersion: v1 kind: Pod metadata: annotations: topology.kubernetes.io/region: "{{region}}" topology.kubernetes.io/zone: "{{available-zone}}"
topology.kubernetes.io/region为所在节点的region信息。
topology.kubernetes.io/zone为所在节点的az信息。
Deployment配置示例
通过环境变量获取Pod基础信息,示例如下:
kind: Deployment apiVersion: apps/v1 metadata: name: cci-downwardapi-test namespace: cci-test # 填写具体的命名空间 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
负载运行起来后就可以通过环境变量在容器内查看到具体的Pod信息: