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.