Friday 2 August 2024

Copy Variable Groups Across Team Projects in Azure DevOps

 You can easily clone a variabe group in Azure DevOps within a given team project. However, There is no straight forward way to copy a variable group from a team project to another team project. We can write a scrpt using Azure DevOps REST API to achive the requirement.

As the first step we need a personal access token (PAT) with permision to read, create and manage variable groups.


Then we can use the below script to copy variable group from a team project to another. You can further paramterize the script below to make it more dynamic. Note that same as cloning variable group within team project, you will have to add the cecret values again to the copied variable group, via the below script, as secret values will be empty values when copied.


param
(
    [Switch] $apply
)

$PAT = "yourpat";
$sourceVarGroupId = 29
$sourceTeamProject = "aks_blue_green";
$targetTeamProject = "aks_blue_green_nginx";

# Use PAT to create auth header
$Base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"));
$header = @{Authorization = "Basic {0}" -f $Base64AuthInfo};

# Generate url for the variable group
$urlSource = -join("https://dev.azure.com/chamindac/", $sourceTeamProject, "/_apis/distributedtask/variablegroups/", $sourceVarGroupId);

# Get variable group
$variableGroup = Invoke-RestMethod -Uri $urlSource -Headers $header -Method get -ContentType "application/json"; 

# Change project reference to target
$variableGroup.variableGroupProjectReferences[0].projectReference.id = ""
$variableGroup.variableGroupProjectReferences[0].projectReference.name = $targetTeamProject

# Print variables as json
$variables = $variableGroup | ConvertTo-Json -Depth 100;
Write-Host "------------------------------------------";
Write-Host (-join($variableGroup.name, " - to be copied"));
Write-Host "------------------------------------------"
Write-Host $variables;
Write-Host "------------------------------------------";

if ($apply)
{
    $urlDestination = -join("https://dev.azure.com/chamindac/", $targetTeamProject, "/_apis/distributedtask/variablegroups?api-version=7.2-preview.2");
    $createVariableGroup = Invoke-RestMethod -Uri $urlDestination -Headers $header -Method Post -Body $variables -ContentType "application/json"; 

    # Print variables as json
    $createdVariables = $createVariableGroup | ConvertTo-Json -Depth 100;
    Write-Host "------------------------------------------";
    Write-Host (-join($createVariableGroup.name, " - copied to target."));
    Write-Host "------------------------------------------"
    Write-Host $createdVariables;
    Write-Host "------------------------------------------";
}

No comments:

Popular Posts