1. Several ways for Kubernetes Pods to refer to environment variables

1.1 Direct Key/Value

You can set the Value value directly, or you can use the current Pod’s information as the Value value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
apiVersion: v1
kind: Pod
metadata:
  name: envar-demo
  labels:
    purpose: demonstrate-envars
spec:
  containers:
  - name: envar-demo-container
    image: gcr.io/google-samples/node-hello:1.0
    env:
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"
    - name: MY_NODE_NAME
      valueFrom:
        fieldRef:
          fieldPath: spec.nodeName
    - name: MY_POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name

1.2 Referencing from Secret

There are two ways to refer to variables in the Secret

  • Referencing all variables in Secret via envFrom
  • Referring to the specified variable in the Secret via valueFrom
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
apiVersion: v1
kind: Pod
metadata:
  name: secret-env-pod
spec:
  containers:
  - name: mycontainer
    image: redis
    envFrom:
      - secretRef:
          name: secret-config
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: secret-config
            key: username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: secret-config
            key: password

1.3 Referencing from ConfigMap

There are two ways to reference variables in a ConfigMap.

  • Referencing all variables in ConfigMap via envFrom
  • Referring to the specified variable in ConfigMap via valueFrom
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      envFrom:
        - configMapRef:
            name: configmap-config
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: special.how
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: env-config
              key: log_level

2. Priority of Variable References

Initialize a Map to store the environment variables:

  1. Iterate through the Key/Value of the ConfigMap and Secret referenced by envFrom in order
  2. Iterate through the Key/Value of the settings in env in order
  3. Since the Pod has enabled EnableServiceLinks by default, you need to inject Service related variables at the end.

The priority is, Service variables > Env > EnvFrom.

3. Reference