The Drum playing Computer Scientist

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:

# File: azure-pipeline.yml
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}}Code language: PHP (php)
# File: template.yml
parameters:
    shouldPublish: 

steps:
- script: echo 'i will run every time'
- script: echo 'i will only run on develop'
  condition: ${{ parameters.shouldPublish }}
Code language: PHP (php)

Have a nice day!

References