Paul O'Leary
Paul O'Leary

Reputation: 60

How can I set a variable based on which agent is running an Azure DevOps build pipeline?

We have multiple self-hosted build agents. One step of one of our build pipelines is to copy some artifacts to a network drive. We do this via a PowerShell script, which takes the destination as a parameter. We would like this destination to vary based on which agent (or agent pool) runs the pipeline.

I wondered about adding a user-defined capability to the agent that specifies this path, but you cannot then use this in the pipeline as a variable.

I also tried this:

parameters:
- name: PoolName
  displayName: Pool Name
  type: string
  default: Pool A
  values:
  - Pool A
  - Pool B

pool:
  name: ${{ parameters.PoolName }}

variables:
  ${{ if eq(parameters.PoolName, 'Pool A') }}:
      BuildArchiveLocation:  'foo'
  ${{ if eq(parameters.PoolName, 'Pool B') }}:
      BuildArchiveLocation:  'bar'

But received A template expression is not allowed in this context on the name: ${{ parameters.PoolName }} line.

Is there a nice way this can be done?

Upvotes: 1

Views: 3459

Answers (2)

MPavlak
MPavlak

Reputation: 2221

I had a similar need to parameterize the pool, but I needed to also switch between hosted and private build agents. You have to conditional the entire pool node as below. You cannot conditional the parameter to the pool node.

parameters:
  - name: BuildAgent
    type: string
    default: private
    values:
      - private
      - hosted

jobs:
- job: BuildJob
  displayName: Build
  ${{ if eq(parameters.BuildAgent, 'private') }}:
    pool: default #whatever your private agent pool name is
  ${{ if eq(parameters.BuildAgent, 'hosted') }}:
    pool:
      vmImage: windows-latest

Upvotes: 2

Krzysztof Madej
Krzysztof Madej

Reputation: 40939

This is strange that you can't use runtime parameters at this level. However if you put pool at job level you should be able to run your pipeline. So please try:

parameters:
- name: PoolName
  displayName: Pool Name
  type: string
  default: Pool A
  values:
  - Pool A
  - Pool B

variables:
  ${{ if eq(parameters.PoolName, 'Pool A') }}:
      BuildArchiveLocation:  'foo'
  ${{ if eq(parameters.PoolName, 'Pool B') }}:
      BuildArchiveLocation:  'bar'

jobs:
- job: build
  displayName: Build and Test
  pool: 
    name: ${{ parameters.PoolName }}
  steps:
  - script: echo building $(Build.BuildNumber)

The script passed validation:

enter image description here

Upvotes: 2

Related Questions