Home > OS >  how to increment and save variable in azure devops pipeline
how to increment and save variable in azure devops pipeline

Time:07-27

Anyone know how can I increment the value of a variable under some conditions, (for example only if the pipeline succeeded) and save it for next build?

Example:
I set a variable: number=5.
If the pipeline succeeded and job number 2 ran, I want number=6 on the next build.

Is this possible?

CodePudding user response:

You can set the value of your variable by using following command:

-bash

echo "##vso[task.setvariable variable=number;]newValue"

-powershell

Write-Host "##vso[task.setvariable variable=number;]newValue"

so basically, your number will be set to the newValue after running this command.

CodePudding user response:

how to increment and save variable in azure devops pipeline

Since you could not use the counter, you could try to use the REST API Definitions - Update to update the variable:

PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0

The test scripts:

$url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0"

Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Headers @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"

$counter = [int]$pipeline.variables.Test.value

$counter  

$pipeline.variables.Test.value = $counter

####****************** update the modified object **************************
$json = @($pipeline) | ConvertTo-Json -Depth 99


$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}

write-host "==========================================================" 
Write-host "The value of Varialbe 'Test' is updated to" $updatedef.variables.Test.value

Note: We neeed to declare the variable type as int before we can use

$counter = [int]$pipeline.variables.Test.value

$counter  

If you met any premission issue, please refer this thead for some more details.

  • Related