Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bryanknox/6e571e4c5fde9a9eb531a81d51b0ed3e to your computer and use it in GitHub Desktop.
Save bryanknox/6e571e4c5fde9a9eb531a81d51b0ed3e to your computer and use it in GitHub Desktop.
Pass variables between job steps in Azure DevOps YAML Pipelines.

Pass variables between job steps in Azure DevOps YAML Pipelines

Example YAML pipeline

The example (see sample-azure-pipeline.yml) uses the pwsh shortcut for the PowerShell task so it works across platforms.

In Step 1 the inline PowerShell script logic determines and sets the value of the IsFooBar variable. It uses "logging commands" to set the variable.

Write-Host "##vso[task.setvariable variable=IsFooBar]$IsFooEqualToBar"

See docs: Logging commands

Step 2 simply logs the value of the IsFooBar variable. Two techniques are used to access the value of the variable. The first uses the YAML $(IsFooBar) syntax. The second uses the PowerShell syntax for access environment variable $env:IsFooBar.

Step 3 also only logs the value of the IsFooBar variable, but we put a condition on this step, the step is only run if the value of the IsFooBar variable is true. The step's condition uses the YAML variables.IsFooBar syntax to access the variable's value.

Step 4 is similar to Step 3, but the step is only run if the IsFooBar variable is not true.

References and Links

Docs: Define variables

Docs: Logging commands

trigger: none
pool:
vmImage: 'ubuntu-latest'
steps:
- pwsh: |
Write-Host "Step 1"
$FOO = "some value"
$BAR = "some value"
$IsFooEqualToBar = ($FOO -eq $BAR)
Write-Host "FOO: $FOO"
Write-Host "BAR: $BAR"
Write-Host "IsFooBar: $IsFooBar"
Write-Host "##vso[task.setvariable variable=IsFooBar]$IsFooEqualToBar"
displayName: 'Step 1 - Set Variables'
- pwsh: |
Write-Host "Step 2"
Write-Host "IsFooBar from step variable: $(IsFooBar)"
Write-Host "IsFooBar from environment variable: $env:IsFooBar"
displayName: 'Step 2 - Log Variable Value'
- pwsh: |
Write-Host "Step 3"
Write-Host "IsFooBar from step variable: $(IsFooBar)"
displayName: 'Step 3 - Conditional (IsFooBar is true) log variable value'
condition: eq(variables.IsFooBar, true)
- pwsh: |
Write-Host "Step 4"
Write-Host "IsFooBar from variable: $(IsFooBar)"
displayName: 'Step 4 - Conditional (IsFooBar is NOT true) log variable value'
condition: ne(variables.IsFooBar, true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment