Post

Conditional steps in Azure Pipeline Templates

Conditional steps in Azure Pipeline Templates

Ever encountered the following situation?

  • You have an Azure Pipeline which uses templates to encapsulate repeated tasks?
  • In this templates you have defined steps which should only be executed conditionally based on dynamic conditions?
  • For example, you build some artifacts and want them only published if the pipeline is triggered for your develop or master branch?

Conditional steps to the rescue

You can use the following pattern:

1
2
3
4
5
6
7
8
9
10
variables: 
  - name: shouldPublish 
  ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/develop') }}:
    value: true 
  ${{ if ne(variables['Build.SourceBranch'], 'refs/heads/develop') }}:
    value: false  
  
- template: template.yml     
  parameters:
    shouldPublish: ${{ variables.shouldPublish}}
1
2
3
4
5
6
7
parameters:
  shouldPublish:   

steps: 
  - script: echo 'i will run every time' 
  - script: echo 'i will only run on develop'   
    condition: ${{ parameters.shouldPublish }}

Have a nice day!

References

This post is licensed under CC BY 4.0 by the author.