Azure Pipelines覆盖管道变量

时间:2020-01-25 23:47:12

标签: azure-devops azure-pipelines

如何覆盖管道变量或如何从作业创建管道变量?

我正在运行一个prepare作业,我将当前的git标记提取到后续作业中需要的变量中,因此我决定创建管道变量并在第一个作业中覆盖其值:

variables:
  GIT_TAG: v0.0.1

jobs:
- job: job1
  pool:
    vmImage: 'ubuntu-16.04'
  steps:
    - powershell: |
        Write-Host "##vso[task.setvariable variable=GIT_TAG]$(git describe --tags --always)"

但是,在下一个作业中,GIT_TAG的初始值为v0.0.1

1 个答案:

答案 0 :(得分:3)

默认情况下,如果覆盖变量,则该值仅对他的作业可用,而对序列作业不可用。

在同一阶段的作业之间传递变量要复杂一些,因为它需要使用输出变量。

类似于上面的示例,传递FOO变量:

  1. 确保为工作命名,例如job: firstjob
  2. 同样,请确保也为该步骤命名,例如:name: mystep
  3. 使用与以前相同的命令设置变量,但添加;isOutput=true,例如:echo "##vso[task.setvariable variable=FOO;isOutput=true]some value"
  4. 在第二个作业中,在作业级别定义一个变量,为其赋予值$[ dependencies.firstjob.outputs['mystep.FOO'] ](请记住,对表达式使用单引号)

完整示例:

jobs:

  - job: firstjob
    pool:
      vmImage: 'Ubuntu-16.04'
    steps:

      # Sets FOO to "some value", then mark it as output variable
      - bash: |
          FOO="some value"
          echo "##vso[task.setvariable variable=FOO;isOutput=true]$FOO"
        name: mystep

      # Show output variable in the same job
      - bash: |
          echo "$(mystep.FOO)"

  - job: secondjob
    # Need to explicitly mark the dependency
    dependsOn: firstjob
    variables:
      # Define the variable FOO from the previous job
      # Note the use of single quotes!
      FOO: $[ dependencies.firstjob.outputs['mystep.FOO'] ]
    pool:
      vmImage: 'Ubuntu-16.04'
    steps:

      # The variable is now available for expansion within the job
      - bash: |
          echo "$(FOO)"

      # To send the variable to the script as environmental variable, it needs to be set in the env dictionary
      - bash: |
          echo "$FOO"
        env:
          FOO: $(FOO)

更多信息,您可以找到here