azure-devopsyamlazure-pipelines-yaml

In Azure yaml, how to use local variables, conditional variables and template variables together?


Consider the following scenario, on where a job (or stage), needs to use some local, conditional and template variables:

# (1) Local for the yaml file
variables:
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

# (2) Conditional, depending on parameters
variables:
  - ${{ if eq(parameters.environment, 'dev') }}:
    - environment: 'development'
  - ${{ if eq(parameters.environment, 'test') }}:
    - environment: 'test'
  - ${{ if eq(parameters.environment, 'prod') }}:
    - environment: 'production'

# (3) Specific, defined on a template file
variables:
  - template: environment-variables-$(environment).yml

How can I combine these 3?

I need variables that are not environment dependant (1), but some others are environment specific (3), so, I read a different template (2) depending on a "parameter.environment" value.

Obviously, when I try to use "variables tag" more than once, Azure-Devops complains because "variables" is already defined. How could I do it?


Solution

  • How can I combine these 3?

    In Pipeline YAML, variables can only be defined once at a stage or root level.

    To meet your requirements, you need to define three type of variables in the same variables field.

    Here is an example:

    parameters:
    - name: environment
      displayName: Test
      type: string
      values:
      - dev
      - test
      - prod
    
    variables:
    - name: buildPlatform
      value: 'Any CPU'
    - name: buildConfiguration
      value: 'Release'
    - template: variables.yml
    
    
    - ${{ if eq(parameters.environment, 'dev') }}:
      - name: environment
        value: development
    - ${{ if eq(parameters.environment, 'test') }}:
      - name: environment
        value: test
    - ${{ if eq(parameters.environment, 'prod') }}:
      - name: environment
        value: prod