How to update an azure pipeline variable from a powershell task?

190 Views Asked by At

How do I update a pipeline variable in an azure task? enter image description here

I'm currently thinking og using the Azure cli to do this:

  1. Login to az
  2. use az pipelines variable update --name=AppVersion --value=7.13.1 command to update

I also tried updating the variable without the AZ CLI but could not get the $AppVersion to update properly. Is it possible to update the $AppVersion in a task without the AZ CLI? I tried a powershell script:

Write-Host $(AppVersion) # 18.13.0
$AppVersion = "9.0.0"
##vso[task.setvariable variable=AppVersion;isOutput=true]9.0.0
$env:AppVersion = '9.0.0'
Write-Host $(AppVersion)  # Still 18.13.0
1

There are 1 best solutions below

2
Scott Richards On

To use powershell to create/update an Azure DevOps variable, the syntax will look as follows:

Write-Host "##vso[task.setvariable variable=AppVersion]9.0.0"

or

echo "##vso[task.setvariable variable=AppVersion]9.0.0"

Two things to note when updating a variable in this way:

  • The variable will only be updated on subsequent tasks, not the current task that has defined it.
  • updating in this way will only update the AppVersion variable for the current job. Subsequent jobs will not be aware of the variable update. This can be achieved by using ;IsOutput=true, and redefining the variable within that job or stage.

Taking the above notes into account, here is the values of AppVersion in an example yaml:

jobs:
- job: Job1
  steps:
  - powershell: | 
      Write-Host "AppVersion is: $(AppVersion)"                       # Appversion = 7.13.0
      Write-Host "##vso[task.setvariable variable=AppVersion]9.0.0"
      Write-Host "AppVersion is: $(AppVersion)"                       # Appversion = 7.13.0

  - powershell: |    
      Write-Host $(AppVersion)                                        # Appversion = 9.0.0
      
- job: Job2
  steps:
  - powershell: | 
      Write-Host "AppVersion is: $(AppVersion)"                       # Appversion = 7.13.0

Depending on how you determine if AppVersion should be updated or not, you can achieve a global update of AppVersion by updating it underneath variables: in your yaml file:

variables:
  ${{ if eq(variables['Build.Reason'], 'Manual') }}:    
    AppVersion: 9.0.0 # will default to pipeline value of 7.13.0 if build reason is not equal to Manual.