Philosophene
Philosophene

Reputation: 190

How to conditionally insert variables in Azure DevOps YAML Stages

I would like to have a iterate over a list of environments that I would use in various places rather than copying and pasting the same code for each environment.

I get the following error:

Encountered error(s) while parsing pipeline YAML: file.yml (Line: 14, Col: 7): Unexpected symbol: 'env'. Located at position 8 within expression: eq(${{ env. For more help, refer to

I see several examples of something like this such as here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops#conditional-insertion

How can I get this to work?

parameters:
- name: environments
  type: object
  default: ['dev'] # e.g. for multiple envs: ['dev','stage','prd','etc']

stages:
- ${{ each env in parameters.environments }}:
  - stage: Deploy_${{ env }}
    dependsOn:
    - 'Build'
    pool:
      vmImage: 'windows-latest'
    variables:
      ${{ if eq(${{ env }}, 'prd') }}:
        environment: 'ADO Environment'
      ${{ else }}:
        environment: 'ADO Environment - Dev'
      azureServiceConnection: 'ServiceConnection - ${{ env }}'
    jobs:
    - deployment: 'Deploy_${{ env }}'
      environment: ${{ variables.environment }}
      strategy:
        runOnce:
          deploy:
            steps:
            - template: deploy.yml
              parameters:
                azureServiceConnection: '${{ variables.azureServiceConnection }}'
                environment: ${{ variables.environment }}

Upvotes: 0

Views: 1170

Answers (1)

Ging Yuan-MSFT
Ging Yuan-MSFT

Reputation: 747

According to your YAML file, I can reproduce your problem. Parameters are expanded just before the pipeline runs so that values surrounded by ${{ }} are replaced with parameter values

Because the ${{}} is a runtime expression, I tried to use the env in the "if" condition and it works as expected.

YAML like:

variables:
  ${{ if eq(env, 'prd') }}:
    environment: 'ADO Environment'
  ${{ else }}
    environment: 'ADO Environment - Dev'  

Upvotes: 2

Related Questions