首页 > 解决方案 > Azure Pipelines 中的变量如何直接在 Container 的 NodeJS 代码中使用?

问题描述

我尝试在 Azure Pipelines 的 Release 中设置变量,可以使用 Release 中的 Command Task 将变量的值替换为 Docker Kubernetes 的 .yaml 文件。

它对我来说很好,但我需要准备几个命令任务来一一替换变量。

例如,我在 Pipelines 的 Release 中设置了变量 TESTING1_(value:Test1)、TESTING2_(value:Test2) 和 TESTING3_(value:Test3)。然后我只使用命令任务将 Docker Kubernetes 的 .yaml 文件中的 TESTING1_ 替换为 $(TESTING1_) 。以下是 .yaml 文件中的原始环境设置:

spec:
  containers:
  - name: devops
      env:
      - name: TESTING1
        value: TESTING1_
      - name: TESTING2
        value: $(TESTING2_)

运行 Pipelines 的 Release 后,NodeJS 中的打印结果为:

console.log(process.env.TESTING1); --> 测试1

console.log(process.env.TESTING2); --> $(TESTING2_)

console.log(process.env.TESTING3); --> 未定义

标签: dockerkubernetesenvironment-variablesazure-pipelinesazure-pipelines-release-pipeline

解决方案


我认为您应该为此使用配置映射(也许更新配置映射中的值)。您不应该直接更新容器。这为您提供了灵活性和管理。例子:

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: special.how

然后,如果某些值发生更改,您将更新配置映射,并且所有引用此配置映射的 pod 都会获得新值。

https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#define-container-environment-variables-using-configmap-data


推荐阅读