More examples of using custom variables in Azure DevOps multi-stage YML
I have blogged in the past ( here , here and here) about the complexities and possible areas of confusion with different types of Azure DevOps pipeline variables.
Well here is another example of how to use variables and what can trip you up.
The key in this example is the scope of a variable, whether it is available outside a job and the syntax to access it
Variables local to the Job
So, if you create your variable as shown below
It is only available in the current job in the form $(standardvar)
Variable with a wider scope
If you want it to be available in another job, or stage you have to declare it thus, adding ;isOutput=true
But there is also a change in how you access it.
- You need to give the script that declares the variable a name so it can be referenced
- You need to add dependons associations between stages/jobs
- And the syntax used to access the variable changes depending on whether you are in the same job, same stage but a different job or a completely different stage.
Below is a fully worked example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pool: | |
vmImage: windows-latest | |
variables: | |
- name: system.debug | |
value: true | |
stages: | |
- stage: Stage1 | |
jobs: | |
- job: Job1 | |
steps: | |
- checkout: none | |
- pwsh: | | |
# declare the variable as standard job and stage variable | |
$MyPowerShellVar = "1.2.3.4" | |
write-host "Local var is $MyPowerShellVar" | |
write-host "##vso[task.setvariable variable=standardvar]$MyPowerShellVar" | |
write-host "##vso[task.setvariable variable=stagevar;isOutput=true]$MyPowerShellVar" | |
name: myscript | |
- pwsh: | | |
# accessing the two variable in the same job | |
Write-Host "Standard Var '$(standardvar)'" | |
Write-Host "Stage Var inside the same job '$(myscript.stagevar)'" | |
# to access the stage variable in a different job we need to create a local variable'alias' | |
# and this job must be set to depend on the first job | |
- job: Job2 | |
variables: | |
job2alias: $[dependencies.Job1.outputs['myscript.stagevar']] | |
dependsOn: Job1 | |
steps: | |
- checkout: none | |
- pwsh: | | |
Write-Host "Stage Var inside the same stage but a different job '$(job2alias)'" | |
# to access the stage variable in a different stage we need to create a local variable'alias' | |
# not the form is different to that used in job2 above | |
# and this job must be set to depend on the first stage | |
- stage: Stage2 | |
dependsOn: Stage1 | |
jobs: | |
- job: Job3 | |
variables: # add the alias | |
job3alias: $[stagedependencies.Stage1.Job1.outputs['myscript.stagevar']] | |
steps: | |
- checkout: none | |
- pwsh: | | |
Write-Host "Stage Var inside a different stage '$(job3alias)'" | |