在矩阵作业中访问输出变量

时间:2020-03-03 09:00:55

标签: azure-devops azure-pipelines azure-devops-server-2019

我正在矩阵作业A中生成输出变量:

  - job: A
    strategy:
      matrix:
        nonprod:
          environment: test
        prod:
          environment: prod
    steps:
      - pwsh: Write-Host "##vso[task.setvariable variable=Hostname;isOutput=true]'StuffFrom$(environment)'"
        name: OutputVariable

现在,我需要在相应工作的后续矩阵策略中访问它们:

  - job: B
    dependsOn: A
    strategy:
      matrix:
        nonprod:
          environment: test
        prod:
          environment: prod
    steps:
      - pwsh: Write-Host How can I use output variables from job A in here?

3 个答案:

答案 0 :(得分:1)

您需要映射输出变量,然后才能使用它们。您可以通过以下方式做到这一点:

  jobs:
  - job: A
    strategy:
     matrix:
      nonprod:
        environment: test
      prod:
        environment: prod
    steps:
      - pwsh: Write-Host "##vso[task.setvariable variable=Hostname;isOutput=true]'StuffFrom$(environment)'"
        name: OutputVariable
  - job: B
    dependsOn: A
    variables:
        varFromAprod: $[ dependencies.A.outputs['prod.OutputVariable.Hostname'] ]
        varFromAnonprod: $[ dependencies.A.outputs['nonprod.OutputVariable.Hostname'] ]
    strategy:
     matrix:
      nonprod:
        environment: test
      prod:
        environment: prod
    steps:
      - pwsh: Write-Host "$(varFromAprod)"
        name: PrintVariableProd
      - pwsh: Write-Host "$(varFromAnonprod)"
        name: PrintVariableNonprod

更多信息,您可以找到here

答案 1 :(得分:1)

matrix还接受包含字符串化JSON对象的运行时表达式。例如:

    jobs:
    - job: generator
      steps:
      - bash: echo "##vso[task.setVariable variable=legs;isOutput=true]{'a':{'myvar':'A'}, 'b':{'myvar':'B'}}"
        name: mtrx
      # This expands to the matrix
      #   a:
      #     myvar: A
      #   b:
      #     myvar: B
    - job: runner
      dependsOn: generator
      strategy:
        matrix: $[ dependencies.generator.outputs['mtrx.legs'] ]
      steps:
      - script: echo $(myvar) # echos A or B depending on which leg is running

在这里检查:

https://docs.microsoft.com/en-us/azure/devops/pipelines/process/phases?tab=yaml&view=azure-devops&tabs=yaml#multi-job-configuration

答案 2 :(得分:0)

基于@Shayki Abramczyk的答案,我最终使用了这种方法:

  jobs:
  - job: A
    strategy:
     matrix:
      nonprod:
        environment: test
      prod:
        environment: prod
    steps:
      - pwsh: Write-Host "##vso[task.setvariable variable=Hostname;isOutput=true]'StuffFrom$(environment)'"
        name: OutputVariable
  - job: B
    dependsOn: A
    variables:
        varFromAprod: $[ dependencies.A.outputs['prod.OutputVariable.Hostname'] ]
        varFromAnonprod: $[ dependencies.A.outputs['nonprod.OutputVariable.Hostname'] ]
    strategy:
     matrix:
      nonprod:
        environment: test
        hostname: $(varFromAnonprod)
      prod:
        environment: prod
        hostname: $(varFromAprod)
    steps:
      - pwsh: |
          Write-Host Hostname for this job is $Hostname