覆盖容器规范中定义的 env 值

Override env values defined in container spec

我有一个 configmap,我在 data 部分定义了以下键值映射:

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: test
  name: test-config
data:
  TEST: "CONFIGMAP_VALUE"

然后在我的容器定义中(在 deployment/statefulset 清单中)我有以下内容:

        env:
        - name: TEST
          value: "ANOTHER_VALUE"
        envFrom:
        - configMapRef:
            name: test-config

执行此操作时,我期望来自 configmap (TEST="CONFIGMAP_VALUE") 的值将覆盖容器规范 (TEST="ANOTHER_VALUE") 中指定的(默认)值,但这情况并非如此(TEST 总是从容器规范中获取值)。我找不到任何关于此的相关文档 - 是否有可能实现这样的环境变量值覆盖?

来自Kubernetes API reference

envFrom : List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.

所以上面明确指出 env 将优先于 envFrom.

When a key exists in multiple sources, the value associated with the last source will take precedence.

因此,为了覆盖,不要使用 envFrom,而是在 env 中定义两次值,见下文:

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: default
  name: test-config
data:
  TEST: "CONFIGMAP_VALUE"
---
apiVersion: v1
kind: Pod
metadata:
  name: busy
  namespace: default
spec:
  containers:
  - name: busybox
    image: busybox
    env:
    - name: TEST
      value: "DEFAULT_VAULT"
    - name: TEST
      valueFrom:
        configMapKeyRef:
          name: test-config
          key: TEST
    command:
    - "sh"
    - "-c"
    - >
      while true; do
        echo "$(TEST)";
        sleep 3600;
      done

检查:

kubectl logs busy -n default
CONFIGMAP_VALUE