If Statements are a fantastic feature in YAML pipelines that allows you to dynamically customize the behavior of your pipelines based on the parameters you pass. They use syntax found within the Microsoft Conditions Documentation. Let's dive in and talk about how you can add them to your pipelines.
Constraints: Where You Can Use If Statements
You cannot use if statements everywhere within your YAML. You'll want to use them only prior to Stages, Jobs, Tasks, and Variables.
Using an if statement within the parameters of a job will not work.
Examples: How to Use If Statements
Simple If Statement
parameters:
version: ""
jobs
- job: build
displayName: "Build .NET Application
pool:
vmImage: "ubuntu-latest"
steps:
- ${{ if ne(parameters.version, '1.0') }}:
- script: "echo 'success!'"
If/And Statement
parameters:
version: ""
jobs
- job: build
displayName: "Build .NET Application
pool:
vmImage: "ubuntu-latest"
steps:
- ${{ if and(
ne(parameters.version, '1.0'),
ne(parameters.version, '2.0')
) }}:
- script: "echo 'success!'"
If/And/Or Statment
parameters:
version: ""
jobs
- job: build
displayName: "Build .NET Application
pool:
vmImage: "ubuntu-latest"
steps:
- ${{ if or(
and(ne(parameters.version, '1.0'),
ne(parameters.version, '2.0')),
eq(parameters.version, '1.1')
) }}:
- script: "echo 'success!'"
Syntax: Available If Statment Expressions
Here is a selection of the most common expressions I use regularly. For the full list, check out Microsoft's Documentation on them.
and
and(
eq(parameters.version, '1.0'), eq(parameters.version, '2.0')
)
or or(
eq(parameters.version, '1.0'), eq(parameters.version, '2.0')
)
ne
ne(parameters.version, '1.0')
eq
eq(variables.version, '1.0')
contains
contains(variables.version, '1')
startsWith
startsWith(variables.version, '1')
endsWith
endsWith(variables.version, '.2')
ge (Greater Than or Equal To)
ge(variables.version, 1)
gt (Greater Than)
gt(variables.version, 1)
le (Less Than or Equal To)
le(variables.version, 2)
lt (Less Than)
lt(variables.version, 2)
Skip this post as it contains plenty of syntax errors and just go read the documentation.