Posted on Leave a comment

dynamically set dependsOn using variables – Azure devops

DependsOn is a condition on Azure devops with which you can define dependencies between jobs and stages.

An example can be found in the below picture where the stage2 depends from the production stage and will execute only when the production stage finishes. If the production stage fails, then the stage2 will not continue its execution.

The typical way to define a dependency would be by naming the stages and note on which stage you need your dependencies. For example in the stage2 we use dependsOn with the value stage1

stages:
- stage: stage1
  displayName: running stage1
  jobs:
  - job: job1
    displayName: running job1
    steps:
    - script: echo job1.task1
      displayName: running job1.task1  

- stage: stage2
  dependsOn: stage1
  displayName: running stage2
  jobs:
  - job: job2
    displayName: running job2
    steps:
    - script: echo job2.task1
      displayName: running job1.task1  

However you can also define dependsOn using a variable. This means that you can dynamically set under which stage another stage will depend and not by setting that as a static variable.

An example of this can be found below:

parameters:
  - name: myparam
    type: string
    values:
      - production
      - dev
      - qa

variables:
  ${{ if eq( parameters['myparam'], 'production' ) }}:
    myenv: production
  ${{ elseif eq( parameters['myparam'], 'dev' ) }}:
    myenv: dev
  ${{ elseif eq( parameters['myparam'], 'qa' ) }}:
    myenv: qa

trigger:
- none

pool:
  vmImage: ubuntu-latest

stages:
- stage: ${{ variables.myenv }}
  displayName: running ${{ variables.myenv }}
  jobs:
  - job: job1
    displayName: running job1
    steps:
    - script: echo job1.task1
      displayName: running job1.task1  

- stage: stage2
  dependsOn: ${{ variables.myenv }}
  displayName: running stage2
  jobs:
  - job: job2
    displayName: running job2
    steps:
    - script: echo job2.task1
      displayName: running job1.task1  

When we run the pipeline we will be asked for the environment as a parameter.

This parameter will be then passed into a variable and then this variable will be used for dependsOn condition.

You could also use the parameter itself as shown below.

- stage: stage2
  dependsOn: ${{ variables.myenv }}
  displayName: running stage2
  jobs:
  - job: job2
    displayName: running job2
    steps:
    - script: echo job2.task1
      displayName: running job1.task1  

Keep in mind that when you use variables, you should use the template syntax which is processed at compile time.

Youtube video:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.