如何将环境变量添加到 Azure Devops 管道中

Mar*_*vin 2 azure node.js azure-web-app-service azure-devops azure-pipelines

我正在为 Node 应用程序设置 Azure 管道,使用 Jest 来测试 API 和集成。源代码位于 Azure DevOps 中,代码部署在 Azure 门户中。当我运行测试时,它在管道中失败,因为 .env 从未在远程存储库中检查过。通过配置,环境变量在运行时位于 Azure 门户中,因此管道无法真正访问它。

为了让我的测试运行虚拟机,有哪些方法可以访问环境变量或为环境变量创建新位置?

我当前的解决方案(我不知道它是否正确)是创建一个变量组并重新定义我的所有环境变量,以便管道可以读取此处描述的变量:https : //damienaicheh.github.io/azure/devops /2019/09/04/how-to-use-variables-inside-your-azure-devops-builds-en.html

我的问题是:

  1. 这样对吗?此处存储的任何变量都与构建无关,它们也不是运行命令的输入,而是源代码中需要我的所有环境变量,以便我可以在虚拟机中进行测试(例如:base_url、apiKeys 等)。
  2. 如果这是正确的,我怎样才能避免重写和重新分配管道中的所有值?我可以获取整个变量组并且源代码可以解释吗?我想避免这样
- env
  - API_KEY: $(apiKey)
  - MAPS_KEY: $(mapsKey)  
  - CLIENT_KEY: $(clientKey)  
  - CLIENT_SECRET: $(clientSecret)
  - 
  -
  - and so on... 


// looking for something like this
   -env: myVariableGroup
Run Code Online (Sandbox Code Playgroud)
  1. 任何导致帖子,文章的更好解决方案?我正在考虑使用密钥保管库,但我认为它与我必须逐一导入基本相同。

Krz*_*tof 5

管道变量会自动映射到 env 变量,因此无需额外工作。只有一个例外——秘密。您必须明确映射它们

steps:
- script: echo $MYSECRET
  env:
    MYSECRET: $(Foo)
Run Code Online (Sandbox Code Playgroud)

所以来自声明、组或模板的所有值都映射到环境变量

变量文件

variables:
  variableFromTemplate: 'valueFromTemplate'
Run Code Online (Sandbox Code Playgroud)

构建.yaml

variables:
  - group: PROD
  - name: variableFromDeclaration
    value: 'valueFromDeclaration'
  - template: vars.yaml  

pool:
  vmImage: 'ubuntu-latest'

steps:
- script: env | sort
- script: | 
    echo $VARIABLEFROMDECLARATION
    echo $VARIABLEFROMGROUP
    echo $VARIABLEFROMTEMPLATE
- pwsh: |
    
    $url = "https://dev.azure.com/thecodemanual/$(System.TeamProject)/_apis/build/builds/$(Build.BuildId)?api-version=5.1"
    $build = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Bearer $env:MY_SECRET"}
    Write-Host "Pipeline = $($build | ConvertTo-Json -Depth 100)"

    $status = $build.status
    Write-Host $status
  name: initial
  env: 
    MY_SECRET: $(System.AccessToken)

Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在此处输入图片说明

因此,对于每一步,您都需要在env部分中定义秘密。作为一种解决方法,我尝试使用容器作业并在容器级别定义 env 映射。

resources:
  containers:
  - container: string  # identifier (A-Z, a-z, 0-9, and underscore)
    image: string  # container image name
    options: string  # arguments to pass to container at startup
    endpoint: string  # reference to a service connection for the private registry
    env: { string: string }  # list of environment variables to add
    ports: [ string ] # ports to expose on the container
    volumes: [ string ] # volumes to mount on the container
    mapDockerSocket: bool # whether to map in the Docker daemon socket; defaults to true
    mountReadOnly:  # volumes to mount read-only - all default to false
      externals: boolean  # components required to talk to the agent
      tasks: boolean  # tasks required by the job
      tools: boolean  # installable tools like Python and Ruby
      work: boolean # the work directory
Run Code Online (Sandbox Code Playgroud)