Execute Azure Devops job on a pool based on conditional parameter

Viewed 3424

I am trying to execute an Azure Devops Job on a specific pool based on a condition. The goal is to switch between self-hosted agent and microsoft agent. Here is the configuration:

parameters:
  custom_agent: true

jobs:
  - job: Test
    displayName: Test job
  - ${{ if eq(parameters.custom_agent, true) }}:
    - pool:
      name: mypool
      demands:
        - agent.os -equals Linux
  - ${{ if eq(parameters.custom_agent, false) }}:
    - pool:
        vmImage: 'ubuntu-latest'
    steps:
      - task: npmAuthenticate@0

enter image description here

Any ideas ?

4 Answers

Another apporach to conditionally select pools if you use non-vm pools:

variables:
- ${{ if eq(parameters.custom_agent, true) }}:
  - name: testJobPool
    value: mypool
- ${{ if eq(parameters.custom_agent, false) }}:
  - name: testJobPool
    value: mypool_second

jobs:
- job: Test
  displayName: Test job
  pool:
    name: $(testJobPool)
  steps:
    - task: npmAuthenticate@0

This has proved working.

The below example solved my requirement

parameters:
  - name: 'vmImage'
    type: string
    default: 'ubuntu-latest'
  - name: 'agentPool'
    type: string
    default: ''

jobs:
  - job: 'Example'
    pool:
      ${{ if ne(parameters.agentPool, '') }}:
        name: ${{ parameters.agentPool }}
      ${{ if eq(parameters.agentPool, '') }}:
        vmImage: ${{ parameters.vmImage }}
    steps:
      - script: example

We can specify conditions under which a step, job, or stage will run. We can configure the jobs in the pipeline with different condition entries, and set demands based on those conditions.

A skeleton version looks like this:

parameters:
- name: custom_agent
  displayName: Pool Image
  type: boolean
  default: True

jobs:
  - job: selfhostedagent
    condition: eq(${{ parameters.custom_agent }}, True)
    displayName: 'self_hosted agent'
    pool:
      name: Default
      demands:
        - Agent.Name -equals WS-VITOL-01
    steps:
      - script: echo self_hosted agent

  - job: hostedagent
    condition: eq(${{ parameters.custom_agent }}, False)
    displayName: 'hosted agent'
    pool:
      vmImage: 'ubuntu-latest'
      
    steps:
      - script: echo hosted agent

Update1

In addition, we can configure task template, then use the template in the steps.

Result:

enter image description here

It looks like pool is not a valid property of a job type

Try switching your job to a deployment type:

jobs:

  - deployment: Test
  - ${{ if eq(parameters.custom_agent, true) }}:
     pool:
      name: mypool
      demands:
        agent.os -equals Linux
    strategy:
        runOnce:    
          deploy:
            steps:
Related