如何在池需求中使用矩阵变量?

How to use matrix variable within pool demands?

对于 Azure Pipelines yaml 文件,我想 运行 对特定池中的每个代理执行一次一组任务。当我查看工作策略矩阵时,它看起来是一个很好的解决方案,但它目前无法获取我为此使用的变量。

管道 yaml 文件,与此问题相关的是这部分:

resources:
- repo: self

trigger: none

jobs:
- job: RunOnEveryAgent
  strategy:
    maxParallel: 3
    matrix:
      agent_1:
        agentName: Hosted Agent
      agent_2:
        agentName: Hosted VS2017 2
      agent_3:
        agentName: Hosted VS2017 3
  pool:
    name: Hosted VS2017
    demands:
    - msbuild
    - visualstudio
    - Agent.Name -equals $(agentName)

  steps:
  - (etc.)

使用此脚本,我尝试在池中的三个代理中的每一个上设置一个矩阵 运行。但是,当我尝试在需求列表中引用代理时,它不会接收到它。实际报错信息如下:

[Error 1] No agent found in pool Hosted VS2017 which satisfies the specified demands:

msbuild

visualstudio

Agent.Name -equals $(agentName)

Agent.Version -gtVersion 2.141.1

如果我对代理名称进行硬编码, 是否有效:

    demands:
    - msbuild
    - visualstudio
    - Agent.Name Hosted VS2017 3

是否支持在池需求中使用这些变量?或者我应该使用不同的变量或表达式?

由于变量展开的顺序,其中一些作业不支持变量。

但是,您可以为您的工作策略使用模板包含语法 (https://docs.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops),并将代理名称作为参数传入。

所以您在自己的 YAML 文件中的构建作业可能如下所示:

parameters:
  agentName1: ''
  agentName2: ''
  agentName3: ''

jobs:
- job: RunOnEveryAgent
  strategy:
    maxParallel: 3
    matrix:
      agent_1:
        agentName: ${{ parameters.agentName1 }}
      agent_2:
        agentName: ${{ parameters.agentName2 }}
      agent_3:
        agentName: ${{ parameters.agentName3 }}
  pool:
    name: Hosted VS2017
    demands:
    - msbuild
    - visualstudio
    - Agent.Name -equals ${{ parameters.agentName3 }}

  steps:

然后您的主要 azure-pipelines.yml 将变为如下所示:

resources:
- repo: self

trigger: none

jobs:
  - template: buildjob.yml
    parameters:
      agentName1: 'Hosted Agent'
      agentName2: 'Hosted VS2017 2'
      agentName3: 'Hosted VS2017 3'
parameters:
  - name: agentNames
    type: object
    default: []
jobs:
- job: RunOnEveryAgent
  strategy:
    matrix:
       ${{ each agentName in parameters.agentNames }}:
        ${{ agentName }}:
         agentName: ${{ agentName }}
  pool:
    name: Hosted VS2017
    demands:
    - msbuild
    - visualstudio
    - Agent.Name -equals $(agentName)

如果您想在将来添加更多代理,这将是一个更好的解决方案