Posted on 1 Comment

Update variable group using Azure DevOps rest API – pipeline example

Following my previous article about how to update a variable group using POSTMAN, I will now document how to implement the same behavior through a pipeline.

First things first you will need a PAT. I have included this PAT in a different variable group than the one that I will update. this is because when you update the variable group, all the variables that are inside will get lost. If you need to retain them, you should have to get them first and then add them again on the variable group.

For this reason I have created a variable group named token-group which holds my PAT. I also made this variable a secret.

The variable group that I will update has the name of var-group and the id of 5.

The pipeline includes two tasks. The first task will loop through the variables on the group and print them out. The second task will update the variable group based on the JSON that you provided. You should change your ORG and project URLs.

trigger:
– none
pr: none
pool:
vmImage: ubuntu-latest
variables:
– group: token-group
steps:
– task: PowerShell@2
displayName: Get variables from variable-group
inputs:
targetType: 'inline'
script: |
$connectionToken="$(PAT)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$URL = "https://dev.azure.com/geralexgr/test-project/_apis/distributedtask/variablegroups?groupIds=5&api-version=7.1-preview.1"
$Result = Invoke-RestMethod -Uri $URL -Headers @{authorization = "Basic $base64AuthInfo"} -Method Get
$Variable = $Result.value.variables | ConvertTo-Json -Depth 100
Write-Host $Variable
– task: PowerShell@2
displayName: add variables on variable-group
inputs:
targetType: 'inline'
script: |
$connectionToken="$(PAT)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$URL = "https://dev.azure.com/GeralexGR/test-project/_apis/distributedtask/variablegroups/5?api-version=5.1-preview.1"
$body = '{"id":5,"type":"Vsts","name":"var-group","variables":{"rest-var1":{"isSecret":false,"value":"rest-var-value-1"},"rest-var2":{"isSecret":false,"value":"rest-var-value-2"},"rest-var3":{"isSecret":false,"value":"rest-var-value-3"}}}'
$Result = Invoke-RestMethod -Uri $URL -Headers @{authorization = "Basic $base64AuthInfo"} -Method Put -Body $body -ContentType "application/json"
$Variable = $Result.value.variables | ConvertTo-Json -Depth 100
Write-Host $Variable

After running the pipeline you will notice a null output on the update of the variable group. This is the requested result and as task has not failed your var group will get updated.

Variables inside json

1 thought on “Update variable group using Azure DevOps rest API – pipeline example

  1. PAT : Personal Access Token

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.