覆盖容器规范中定义的 env 值 [英] Override env values defined in container spec

查看:14
本文介绍了覆盖容器规范中定义的 env 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a configmap where I have defined the following key-value mapping in the data section:

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

然后在我的容器的定义中(在部署/状态集清单中)我有以下内容:

then in the definition of my container (in the deployment / statefulset manifest) I have the following:

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

这样做时,我期望来自 configmap 的值 (TEST="CONFIGMAP_VALUE") 将覆盖容器规范中指定的(默认)值(TEST="ANOTHER_VALUE"),但情况并非如此(TEST始终从容器规范中获取值).我找不到关于此的任何相关文档 - 是否可以实现这种 env 变量值覆盖?

When doing this I was expecting that the value from the configmap (TEST="CONFIGMAP_VALUE") will override the (default) value specified in the container spec (TEST="ANOTHER_VALUE"), but this is not the case (TEST always gets the value from the container spec). I couldn't find any relevant documentation about this - is it possible to achieve such env variable value overriding?

推荐答案

来自 Kubernetes API 参考:

envFrom :在容器中填充环境变量的源列表.源中定义的键必须是 C_IDENTIFIER.当容器启动时,所有无效的键都会被报告为一个事件.当一个键存在于多个源中时,与最后一个源关联的值将优先.由具有重复键的 Env 定义的值将优先.无法更新.

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.

So above clearly states the env will take precedence than envFrom.

当一个键存在于多个源中时,与最后一个源关联的值优先.

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

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

So, for overriding, don't use envFrom, but define the value twice within env, see below:

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

这篇关于覆盖容器规范中定义的 env 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆