Azure Pipelines: If Statements


This is about Azure YAML Pipelines, not Azure Classic Pipelines. The docs explain the differences.

Everything I show here is in the docs but the pieces are scattered and it took some work to find everything. This article collects what I found.

Pipelines support two kinds of conditions. The first isn’t an if statement, but it acts like one by letting you use expressions to choose when jobs, steps, or stages run. Like this example from the doc:

- job: Foo
  - script: echo Hello!
    condition: always()

There are a bunch of different functions you can use.

These conditions are handy but haven’t been enough on their own. It’s not enough to turn jobs on and off, I need to automate decisions about what config to pass them. Fortunately, you can also conditionally set variables and parameters using if statements. The expressions doc calls it “conditional insertion” and gives examples like this:

  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    stageName: prod

And this:

- task: PublishPipelineArtifact@1
    targetPath: '$(Pipeline.Workspace)'
    ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
      artifact: 'prod'

You can also use these in pipeline templates. The templates doc has its own section on conditional insertion that gives examples of lists of tasks:

- ${{ if eq(parameters.toolset, 'msbuild') }}:
  - task: msbuild@1
  - task: vstest@2

Last, Microsoft has a repo of example pipeline YAML and its each expressions also happen to show if statements. I’m linking the latest commit (at the time I wrote this) because it’s technically not a doc about if statements and future versions might not use the same examples. You may also want to check out the latest version.

DevOps is all about managing config and conditional variables and parameters are essential to doing that well. Most of the pipelines I build rely on this second kind of condition, the if statement. Hopefully it helps with yours.

Happy automating!


Need more than just this article? I’m available to consult.

You might also want to check out these related articles: