azure-devopsazure-pipelinesazure-pipelines-yamlazure-yaml-pipelines

How to manage variable declarations according to parameters


In a yaml pipeline I have defined a string parameter with multiple values.
According to the selected value, I want to assign multiple variables.
The goal here is to write elegant and readable code. I want to avoid multiple ifs statements.

# I want to avoid this
parameters:
- name: virtualApp
  type: string
  default: 'value1'
  values:
  - 'value1'
  - 'value2'
  - 'value3'
  - 'value4'

variables:
- name: poolName
  value: 'pool'
- name: BuildConfiguration
  value: 'Release'
- ${{ if eq(${{ parameters.virtualApp }}, 'value1') }}:
  my variables for value 1
- ${{ if eq(${{ parameters.virtualApp }}, 'value2') }}:
  my variables for value 2

I tried the following code which is more elegant but I get an error: unexpected value 'condition'.

variables:
- name: poolName
  value: 'pool'
- name: BuildConfiguration
  value: 'Release'
- template: variables-value1.yml
  condition: eq( ${{ parameters.virtualApp }}, 'value1')
- template: variables-value2.yml
  condition: eq( ${{ parameters.virtualApp }}, 'value2')

Is there a way to manage this?


Solution

  • Conditions are not natively supported in templates.

    If you have variable templates such as variables-valueX.yml you can dynamically reference the template using the parameter value:

    parameters:
      - name: virtualApp
        type: string
        default: 'value1'
        values:
          - 'value1'
          - 'value2'
          - 'value3'
          - 'value4'
    
    variables:
      # other variables here
    
      - template: variables-${{ parameters.virtualApp }}.yml