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

时间:2020-09-23 03:13:54

标签: node.js azure azure-devops azure-web-app-service azure-pipelines

我正在为Node应用程序设置Azure管道,并使用Jest测试API和集成。源代码位于Azure DevOps上,并将代码部署在Azure Portal中。 当我运行测试时,它在管道中失败了,因为从未在远程存储库中检查过.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
  1. 有人引出文章,文章引出更好的解决方案吗?我当时在考虑使用密钥保管库,但我认为它必须与导入一个文件的库基本相同。

1 个答案:

答案 0 :(得分:2)

管道变量会自动映射到env变量,因此不需要额外的工作。只有一个例外-机密。您必须明确地映射它们

steps:
- script: echo $MYSECRET
  env:
    MYSECRET: $(Foo)

因此声明,组或模板中的所有值都映射到环境变量

vars.yaml

variables:
  variableFromTemplate: 'valueFromTemplate'

build.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)

enter image description here

enter image description here

因此,对于每个步骤,您都需要在env部分中定义机密。作为解决方法,您可以尝试使用container jobs并在container level上定义环境映射。

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
相关问题