'Loop through variables in variable group in Azure Pipelines

In an azure-pipelines.yml file, how do I enumerate all variables defined in a "Variable Group" created in the UI?

Variable group

I'd like to do this so I can write these variables to a .env file in the pipeline build stage.



Solution 1:[1]

We could use REST API and power shell script to loop the variable group

Create PAT token, save it to pipeline variable and set it to secret, then add task power shell and enter below script

Power shell script:

$connectionToken="$(pat)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$URL = "https://dev.azure.com/{Org name}/{Project name}/_apis/distributedtask/variablegroups?groupIds={Variable group ID}&api-version=6.0-preview.2"
$Result = Invoke-RestMethod -Uri $URL -Headers @{authorization = "Basic $base64AuthInfo"} -Method Get 
 

$Variable = $Result.value.variables | ConvertTo-Json -Depth 100

Write-Host $Variable

Result:

enter image description here

Solution 2:[2]

You can use Variable Group Formatter extension. In outputFormat you can specify desired format like CLI or JSON

- task: VariableGroupFormatter@0
  name: variableGroup
  displayName: "Format variables"
  inputs:
    variableGroupID: '6'
    outputFormat: 'JSON'

- script: echo $(variableGroup.formattedVariables)

Result:

Example

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vito Liu
Solution 2 Javier Canizalez