Azure Pipelines – How YAML Pipelines Work
This is a practical guide to Azure Pipelines. Using one small pipeline as the example, we go through its stages, jobs and steps, and then see how triggers, templates and variables help in running and reusing it.
Introduction
In this blog, we will look at how Azure Pipelines works, from the parts that every YAML pipeline is made of to the features that make a pipeline easy to control and to reuse. We start with how CI and CD are different, and why YAML is the better choice for a pipeline. Then we go through the stages, jobs and steps of a pipeline, taking one small pipeline for a .NET web project as the example.
After that, we will see how triggers decide when a pipeline runs, how templates and template expressions help in reusing the YAML, and how variables carry values through a pipeline, even from one job or stage to another.
What are CI, Continuous Delivery and Continuous Deployment?
These three terms come up a lot with pipelines, and an example makes the difference easier to see. Let’s say three developers are working on the web project, and each of them pushes a change to the main branch on the same morning.
With Continuous Integration (CI), each of these pushes is built and tested on its own, within a few minutes. So, if the second change breaks the build or a test, the team knows which change did it, while the developer still remembers what was changed. If the three changes were merged and tested together at the end of the week, finding the one that broke things would take much longer.
Continuous Delivery and Continuous Deployment (CD) are about what happens after the tests pass, i.e., getting the change to the users. With Continuous Delivery, every change that passes the tests is ready to be released, but someone has to approve the release before it goes to production. With Continuous Deployment, there is no approval step, so all three changes would reach production on the same morning, as soon as their tests pass.
Classic or YAML Pipelines?
When you create a new pipeline, Azure DevOps first asks where your code is, and then it sets up the pipeline as a YAML file. There is also a Classic editor, where a pipeline is put together by dragging and dropping tasks.
Classic is easier to start with, but a YAML pipeline lives in the repository next to the code, so every change to the pipeline is reviewed in a pull request, and you can always see who changed what and when. That’s why we would go with YAML for any new pipeline, and all the examples in this blog are in YAML.
What is Inside a YAML Pipeline?
A YAML pipeline is a file in the repository, which is usually called azure-pipelines.yml, and every YAML pipeline has the same shape. A pipeline has one or more stages, each stage has one or more jobs, and each job has one or more steps. Here’s a small pipeline for a .NET web project, which builds and tests the code on Linux and Windows at the same time, and then deploys it:
trigger:
- main
stages:
- stage: Build
jobs:
- job: BuildLinux
pool:
vmImage: 'ubuntu-latest'
steps:
- task: UseDotNet@2
inputs:
version: '8.x'
- script: dotnet build MyWebProject/MyWebProject.csproj
displayName: 'Build'
- script: dotnet test MyWebProject.Tests/MyWebProject.Tests.csproj
displayName: 'Test'
- job: BuildWindows
pool:
vmImage: 'windows-latest'
steps:
- task: UseDotNet@2
inputs:
version: '8.x'
- script: dotnet build MyWebProject/MyWebProject.csproj
displayName: 'Build'
- script: dotnet test MyWebProject.Tests/MyWebProject.Tests.csproj
displayName: 'Test'
- stage: Deploy
dependsOn: Build
jobs:
- job: DeployJob
pool:
vmImage: 'ubuntu-latest'
steps:
- script: echo "Deploying the app"
The Build stage has two jobs, one on a Linux machine and one on a Windows machine, and each of them runs the same three steps. The Deploy stage starts only after the Build stage has completed successfully. You may have noticed that the two jobs repeat the same steps, and we will see how to avoid that with templates later in this blog. For now, let’s look at each level of the pipeline, starting with the smallest one.
Steps
A step is the smallest building block of a pipeline. Each step is either a script or a task. A task is a pre-packaged script, written by Microsoft or by others, for common work like installing .NET or pushing a package. Here’s how the steps behave:
- Steps run one after another, in the order they are written, and all of them run on the same machine or container.
- A step runs only when all the steps before it have completed, and in general, only when they have succeeded.
- When a step fails, the steps after it are skipped, unless their condition says otherwise.
- When a step runs longer than its timeout, which is set with
timeoutInMinutes, it is stopped, and the steps after it are skipped. - The pipeline succeeds only when all its steps succeed.
At the end, each step has one of these results: Succeeded, SucceededWithIssues, Failed, Canceled or Skipped. You get SucceededWithIssues when a step fails but has continueOnError set to true, so the steps after it still run.
Every step has a condition, and if you don’t set one, the condition is succeeded(). You can set your own condition to decide when a step should run and when it should be skipped. Here are the status functions that can be used in a condition:
succeeded(): True when all the previous steps have completed successfully. A failed step that hascontinueOnErrorset to true doesn’t count as a failure here.failed(): True when at least one of the previous steps has failed.succeededOrFailed(): True when the previous steps have completed, whether they succeeded or failed. It is false only when the run is canceled.always(): Always true, even when the run is canceled.canceled(): True when the run has been canceled.
Conditions can also use variables and parameters, and they can be combined with functions like and() and or(). One thing to keep in mind is that your own condition replaces the default one. So, if a step has the condition eq(variables['Build.SourceBranch'], 'refs/heads/main'), it will run on the main branch even if an earlier step has failed. If you want it to run only when everything before it succeeded, write the condition as and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')).
Jobs
A job is a set of steps that run one after another as a unit, and it is the smallest unit of work that can be scheduled to run. In fact, every pipeline has at least one job, and when you write only steps, Azure Pipelines puts them in a job for you. Here’s how the jobs behave:
- Different jobs can run on different machines.
- Jobs are independent of each other by default, so they run in parallel, as long as there are enough agents and parallel jobs available.
- The
dependsOnproperty makes a job wait for other jobs to finish first. - A job runs when all the jobs it depends on have completed and its condition is true. Since the default condition is
succeeded(), a job runs when all its dependencies have succeeded, or when it has no dependencies at all. - If a job fails, the jobs that depend on it are skipped, unless their condition is changed, just like with steps.
An agent is the machine that runs a job, and the agents are grouped into agent pools. The agents are either Microsoft-hosted or self-hosted.
In case of Microsoft-hosted agents, Microsoft provides virtual machines with different images, like ubuntu-latest, windows-latest and macOS-latest. The job runs on an agent with the image that you ask for, and each job gets a fresh machine, so nothing is left over from the earlier runs.
In case of self-hosted agents, you set up and manage the machines yourself. The job asks for a pool by its name, and it can also list demands, i.e., the capabilities that the agent must have, like a particular operating system. Azure Pipelines then picks an agent from that pool which satisfies the demands, and if that agent is busy, the job waits until it is free. Since the same agent can pick up one job after another, you can use the workspace property to clean up whatever the earlier jobs left behind.
Stages
Stages are the next level up. A stage groups the jobs for one part of your delivery process, like building the app, running the tests or deploying it to a test environment, and each stage has one or more jobs. Here’s how the stages work:
- By default, the stages run one after another, in the order in which they are written.
- With
dependsOn, you can change this order, or let two stages run at the same time by settingdependsOnto an empty list. - A stage runs when all the stages it depends on have completed and its condition is true, the same way as jobs.
- Before a stage starts, Azure Pipelines checks access to all the resources that its jobs use, and runs any checks set on them, like a manual approval on an environment. So, a deployment stage can stay paused until someone approves it.
- If you write only jobs, Azure Pipelines puts them in a stage for you, just like it puts the steps in a job.
When Does a Pipeline Run?
A trigger tells a pipeline when to run. It can run on a schedule, or in response to an event, like a push to a branch or a new pull request. Since a trigger is about the pipeline as a whole, it can be defined only at the root level of the YAML file. Azure Pipelines supports these triggers:
- CI triggers: The pipeline runs when code is pushed to a branch.
- PR triggers: The pipeline runs when a pull request is created, or when new code is pushed to the source branch of an open pull request.
- Scheduled triggers: The pipeline runs at fixed times.
- Pipeline triggers: The pipeline runs when another pipeline completes.
CI Triggers
If you don’t write a trigger at all, the pipeline runs for a push to any branch. This default can also be switched off for a whole organization or a project, with the Disable implied YAML CI trigger setting. In the pipeline itself, you can turn CI off completely, give a list of branches, or use the full form, with branches, paths and tags:
trigger:
batch: true
branches:
include:
- features/*
exclude:
- features/experimental/*
paths:
exclude:
- README.md
In this example, the pipeline runs for pushes to any branch under features/, except the ones under features/experimental/, and a change that only touches README.md doesn’t start a run. Because of batch: true, if a run is already going on when new changes are pushed, Azure Pipelines waits for that run to complete, and then starts one run with all the changes that haven’t been built yet. Tags can be included or excluded in the same way as branches.
PR Triggers
PR triggers are written with the pr keyword. Like the CI trigger, it can take a list of branches, or the full form with branches and paths. The full form also has autoCancel, which cancels a running PR build when a new commit is pushed to the pull request, and drafts, which decides whether a draft pull request should start a run. To turn off the PR runs without affecting the CI runs, write pr: none.
However, there is one catch here. The pr keyword works for repositories on GitHub and Bitbucket, but it has no effect for Azure Repos Git. For Azure Repos, the PR runs have to be set up in Azure DevOps itself, as a Build validation policy on the target branch.
Scheduled Triggers
To run a pipeline at fixed times, like a nightly build, you can use schedules. Each schedule has a cron expression, and the time in it is always in UTC. Here’s an example with a daily build at midnight and a weekly build at noon on Sundays:
schedules:
- cron: '0 0 * * *'
displayName: Daily midnight build
branches:
include:
- main
- releases/*
exclude:
- releases/ancient/*
- cron: '0 12 * * 0'
displayName: Weekly Sunday build
branches:
include:
- releases/*
always: true
By default, a scheduled run starts only if the code or the pipeline has changed since the last successful scheduled run. With always: true, the pipeline runs on schedule every time, even when nothing has changed. There is also batch, which decides whether a scheduled run should start if the previous scheduled run is still going on. Both always and batch are false by default.
How Do Templates Help in Reusing YAML?
In real projects, many pipelines need the same steps. Instead of copying these steps everywhere, you can put them in a template. A template works like an include directive in many programming languages, which means its content is inserted into the pipeline, or into the other template, that refers to it.
A template can also have parameters, so the same content can be set up differently every time it is used. These parameters are declared the same way as the parameters of the pipeline itself. Also, each template is written for one kind of content, i.e., steps, jobs, stages or variables. For example, a variables template can be used only to define variables.
Here’s a job template that installs the npm packages and runs the tests, with the job’s name and the machine image as parameters:
parameters:
- name: name
default: ''
- name: vmImage
default: ''
jobs:
- job: ${{ parameters.name }}
pool:
vmImage: ${{ parameters.vmImage }}
steps:
- script: npm install
- script: npm test
And here’s a pipeline that uses this template three times, once for each operating system:
jobs:
- template: templates/npm-with-params.yml
parameters:
name: Linux
vmImage: 'ubuntu-latest'
- template: templates/npm-with-params.yml
parameters:
name: macOS
vmImage: 'macOS-latest'
- template: templates/npm-with-params.yml
parameters:
name: Windows
vmImage: 'windows-latest'
So, the same install and test steps run on Linux, macOS and Windows, and if these steps ever need a change, there’s only one file to update. There is another kind of template as well, called an extends template, where a pipeline is built on top of a template that fixes its overall structure. We won’t go into those in this blog.
What are Template Expressions?
Anything that is written as ${{ something }} is a template expression. These expressions are resolved first, before the pipeline runs, and then the pipeline runs using the YAML that comes out of this. During this resolution:
${{ parameters.paramName }}and${{ variables.variableName }}are replaced with the actual values of the parameter or the variable.- Every template is replaced with its content.
- Some elements, like steps, jobs, stages or variables, are included or left out, based on conditions.
Let’s see what these expressions make possible.
Including Elements Based on a Condition
With ${{ if }}, ${{ elseif }} and ${{ else }}, a variable, step, job or stage can be included only when a condition is true. In the example below, the value of apiUrl depends on the environment that is picked when the pipeline is run, and the extra checks run only for production:
parameters:
- name: environment
type: string
default: dev
values:
- dev
- test
- prod
variables:
${{ if eq(parameters.environment, 'prod') }}:
apiUrl: 'https://api.example.com'
${{ elseif eq(parameters.environment, 'test') }}:
apiUrl: 'https://test-api.example.com'
${{ else }}:
apiUrl: 'https://dev-api.example.com'
steps:
- script: echo "Deploying with $(apiUrl)"
- ${{ if eq(parameters.environment, 'prod') }}:
- script: echo "Running the extra production checks"
How Do Variables Work?
Variables are a convenient way to keep a value in one place and use it in different parts of the pipeline. Here are the main things to know about them:
- All variables are strings, and their values can change, from one run to another or from one job to another.
- There are two kinds of variables. System variables are set by Azure Pipelines, and they are read-only. User-defined variables are the ones that you set.
- User-defined variables can be set at the root, stage or job level. If the same name is set at more than one level, the job-level value wins.
- Variables can also be set in the pipeline’s settings in the UI. These are stored in Azure DevOps and not in the repository, so this is where secrets like passwords should go, as they should never be committed to the repository. Secrets can also be kept in variable groups.
- All variables, except the secrets, are available to tasks and scripts as environment variables. A secret has to be mapped to the step explicitly, with
env.
How Do You Refer to a Variable?
Azure Pipelines has three different ways to refer to a variable, and each one is processed at a different time:
| Syntax | Name | When it is processed | Where it is used |
|---|---|---|---|
$(var) | Macro | At runtime, just before a task runs | In the inputs of tasks and in scripts |
${{ variables.var }} | Template expression | At compile time, before the run starts | Anywhere in the YAML, even in keys |
$[variables.var] | Runtime expression | At runtime, when the condition or the variable is evaluated | In conditions and in variable values, as the whole value |
There’s one more difference, which shows up when the variable doesn’t exist. A macro like $(var) is then left as it is, so the text $(var) itself gets printed, while the other two give an empty string.
In practice, $(var) is the one you will use most of the time in steps. ${{ }} is for the things that must be known before the run starts, like template parameters and the conditions we saw above. And $[ ] is for conditions and for values that depend on the earlier jobs or stages, as we will see shortly.
How Do You Pass Values Between Jobs and Stages?
Logging commands are how tasks and scripts communicate with the Azure Pipelines agent. When a step writes a line in a special format to its standard output, the agent picks it up and does what it asks for, like setting a variable, reporting an error or marking the step as failed. The format is:
##vso[area.action property1=value;property2=value;...]message
The command that you will use most often is task.setvariable, which sets a variable for the later steps of the same job. If it is set with isOutput=true, the variable becomes an output variable, and the later jobs and stages can read it as well, as long as the step that sets it has a name.
To use the value in another job, it must be an output variable, and the other job must depend on the job that sets it. The value is then read from dependencies, with a runtime expression:
jobs:
- job: JobA
steps:
- script: echo "##vso[task.setvariable variable=myVar;isOutput=true]FromJobA"
name: StepA
- job: Job2
dependsOn: JobA
condition: and(succeeded(), eq(dependencies.JobA.outputs['StepA.myVar'], 'FromJobA'))
variables:
mappedVar: $[ dependencies.JobA.outputs['StepA.myVar'] ]
steps:
- script: echo "Job 2 ran, and mappedVar is $(mappedVar)"
Here, the value decides whether Job2 runs at all, and it is also mapped to a variable, so that the steps of Job2 can use it.
The syntax is different at each level, so here’s a short summary of where the value is read and how:
| Where the value is read | How it is referred to |
|---|---|
| A later step in the same job | $(StepA.myVar) |
| Another job in the same stage | dependencies. |
| A job in a later stage | stageDependencies. |
| The condition of a later stage | dependencies. |
The Bottom Line
Every YAML pipeline is made of stages, jobs and steps. The steps run in order on one machine, while the jobs decide where the steps run and which of them can run in parallel, and the stages group the jobs into the phases of your delivery process.
On top of these, triggers decide when a pipeline runs, templates and template expressions keep the YAML short, and variables carry the values through the pipeline, even from one job or stage to another. Together, these features cover most of what you need to write pipelines that can be maintained easily as the project grows.