Search code examples
yamlazure-pipelinesazure-pipelines-yaml

Azure pipeline yaml: use each command and compare string


I migrate my classic legacy TaskGroup to Yaml and I struggle with string comparison.
I have 3 stages: dev, test and prod. My stage dev and test must immediately in parallel and prod must depends on test.

I try to optimize using for each command that i read in multiple articles.

trigger:
  - main

parameters:
  - name: environment
    type: object
    default:
    - 'dev'
    - 'test'
    - 'prod'

pool:
  name: local

stages:
  - ${{ each env in parameters.environment }}:
    - stage: ${{env}}
      ${{ if eq( '${{ env }}', 'prod') }}:
        dependsOn: test
      ${{ else }}:
        dependsOn: []

As you can see parameter dependsOn is empty when dev or test environement are detected. And when environment prod is detected then it must dependsOn test.

What i get is that else is already triggered whatever environment detected. Did I miss something ? Do I apply correct algorithm ?

Thx for your feedback
Paul


Solution

  • The condition is wrong. Change ${{ if eq( '${{ env }}', 'prod') }} to ${{ if eq(env, 'prod') }}, remembering that the eq is already inside a ${{ ... }} block which applies to everything inside it, including the env (so you don't need to add it again.

    Full working solution for me:

    trigger:
    - main
    
    pool:
      vmImage: ubuntu-latest
    
    parameters:
      - name: environment
        type: object
        default:
        - 'dev'
        - 'test'
        - 'prod'
    
    stages:
    - ${{ each env in parameters.environment }}:
      - stage: ${{env}}
        ${{ if eq(env, 'prod') }}:
          dependsOn: test
        ${{ else }}:
          dependsOn: []
        jobs:
          - job: SomeJob
            steps:
            - script: echo ${{env}}
    

    Azure Pipelines screenshot