If you’re working with Azure DevOps Pipelines, you should be aware of all your options when it comes to using variables. They make it possible to “Build Once, Deploy Anywhere”, prevent code-reuse, and build scale-able CI/CD pipelines.
User-Defined Vs. System variables
First, I want to start off with the distinction between user-defined variables and system variables. User-defined variables are variables that are defined by you, the end-user (duh!); these are set for things like build tasks, scripts, when queuing a build, creating a release, etc. System variables are automatically set by the system and the values cannot be changed by you, the end-user (read-only). System variables can be also referred to as “predefined variables”, these are the system variables defined by Azure DevOps. In the context of build or release runtime, the variables are available as “Environment Variables”. You can find the list of system variables that are available for builds here and for releases here.
Setting Pipeline variables
User-defined variables that are specific to the pipeline can be set on the variables tab of the build or release definitions. After adding variables, you can use the variable as an input to a task or inside the scripts in your pipeline. To reference these variables in tasks, wrap is using $(), such as $(exampleVariableName).
1. Set variable
2. Reference variable in task
To reference the variables in scripts, you can refer to the Microsoft doc here.
Notice that variables are also made available to scripts through environment variables. The syntax for using these environment variables depends on the scripting language. Name is upper-cased,
_, and automatically inserted into the process environment. Here are some examples:
Variable groups are groups of variables that you can share across multiple pipelines. Rather than setting the same variable across definitions, you can add it to a group so it can be managed in one place. I often see variable groups setup for each environment a set of applications flows through (e.g. DEV, TEST, PROD). This is a great spot to store things like connection strings. I’d recommend storing secrets in Azure Key Vault, then linking the Azure Key Vault to the variable group.
Expressions can be used to access and define variables. The following logging command can be run in a PowerShell task to set a variable:
Write-Host "##vso[task.setvariable variable=testvar;]testvalue"
I like to version my builds using a counter expression. To do this I set the following variables:
Then change the build number format to reference them:
You can find the list of functions available for expressions in the docs here.
What creative ways have you used variables in an Azure DevOps pipeline? Feel free to share in the comments below.