How to use variables in the Azure DevOps pipeline
The article talks about how to use the variables in the Azure DevOps pipeline. The pipeline variablization helps you in the following ways.
- You can separate configuration values from the code and inject them during the deployment
- You can scope the values to environment specific. Sometimes the values of a configuration parameter may change based on environment type. i.e. Dev, QA etc.
Now, let us see how to variablize an Azure DevOps release pipeline for executing a PowerShell script for each environment i.e. Dev, QA.
The below is the script for the PowerShell task:
Write-output "Welcome to Azure DevOps. I am in Dev environment"
With the above script, I need to change the text for write-output for each other environment. If I variablize it, then I no need to hard code the environment value in the script. When comes to Azure DevOps, we need to define the variable at the variable section of the pipeline as below.
Few points to observe:
- The Add button allows to define the variable and the name should not be duplicated unless its scope is different
- Define the value and you can lock it if the value is sensitive and securing it from other users.
- The scope defines the visibility scope of the value. If you multiple stages such as Dev, QA, then you can define the same variable with two values scoping to Dev and QA respectively. Its value will only be visible to the tasks in that stage. During the stage execution, the corresponding value will be visible.
Note: If any variable defined wit Release scope, then it’s value is visible to all the tasks in all stage of the pipeline.
Now, refer to the variable in the pipeline using the syntax $() in the case of the PowerShell script. To understand the syntax, refer to the variablization in Azure DevOps.
The whole pipeline looks like:
and the variables:
The PowerShell script task would be same in both the stages as below:
The pipeline output will be:
As in the above screenshot, though the script is the same, its value got interpolated with the pipeline variables. Similarly, we can create variable groups for each stage. The advantage of the variable groups over the pipeline variables is that you can group all the stage level parameters as groups and attach them to a stage in the pipeline. The pipeline variables are useful when you deal with single-stage pipelines.
To create the variables groups, navigate to Azure DevOps pipeline library and create the variable group as below.
This you can manage the stage level parameters as a group using variable groups in stead of making the changes to pipeline variables when you have multiple stages.
Hope you find the article useful.