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

Accessing output variables in matrix job

我正在矩阵作业 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?

您需要映射输出变量,然后才能使用它们。你可以这样做:

  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

基于@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

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