azure-devopsazure-pipelinesazure-pipelines-yaml

ADO Template Expression condition for Pools using variable groups


I am trying to assign agent pool demand (dev or stage) to the job based on what value is being set in variable group for branch name variable. Below is the extract from the yaml file:

template.yml

parameters:
- name: branch
  type: string
jobs:
- job:
  pool:   
    ${{ if eq(parameters.branch, 'development') }}:
      demands: Agent.Name -equals "DEVAGENT"
    ${{ if eq(parameters.branch, 'master') }}:
      demands: Agent.Name -equals "STGAGENT"
  steps:        
  - script: |
      echo Branch name from Variable Group.
      echo branch_param =  ${{ parameters.branch }}
    displayName: 'Run test Pipeline'

main.yml

variables:
  - group: BranchVariableGroup
stages:
- stage: Test
  displayName: 'Test'
  jobs:
  - template: template.yml
    parameters:
      branch: $(branchName)

The above code compiles correct however the template file condition for pool demands is not evaluated and MS hosted default agent is assigned to the job. I am trying to understand how can I use the self hosted agents "DEVAGENT" or "STGAGENT" based on the value being passed in the parameter?


Solution

  • Fixing the agent pool

    however the template file condition for pool demands is not evaluated and MS hosted default agent is assigned to the job.

    You need to set the name property of the pool resource in order to use a self-hosted agent pool:

    pool:
      name: MyAgentPool # <---------------------- set agent pool name
      demands: Agent.Name -equals xxxxxx
    

    Setting the agent pool demand

    As already mentioned by Daniel, variable groups are resolved at runtime.

    Consider adding a new variable to the variable group containing the agent name:

    Variable group

    main.yaml

    variables:
      - group: BranchVariableGroup
    
    stages:
    - stage: Test
      displayName: 'Test'
      jobs:
      - template: template.yml
        parameters:
          branch: $(branchName)
          agentName: $(agentName) # <----------------- new variable/parameter
    

    template.yml

    parameters:
      - name: branch
        type: string
    
      - name: agentName
        type: string
    
    jobs:
      - job:
        pool:
          name: MyAgentPool # <---------------------- set agent pool name
          demands: Agent.Name -equals ${{ parameters.agentName }}
        steps:
          - script: |
              echo Branch name from Variable Group.
              echo branch_param =  ${{ parameters.branch }}
            displayName: 'Run test Pipeline'