Saturday 10 August 2024

Copy Environment Across Team Projects in Azure DevOps

 We have dicussed how to "Copy Variable Groups Across Team Projects in Azure DevOps" in a previous post. In similar way we can use a scrip with Azure DevOps REST API to copy environment defined in Azure DevOps across team projects.

We need to define a personal access token (PAT) with permission to read and manage environments.


Then we can use the script below to copy over the environment from one team project to another. However, note that this script will not copy the approvals etc in the environment.

param
(
    [Switch] $apply
)

$PAT = "yourPAT";
$sourceEnvironmentId = 41
$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 environment
$urlSource = -join("https://dev.azure.com/chamindac/", $sourceTeamProject, "/_apis/pipelines/environments//", $sourceEnvironmentId);

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

# Change project reference to target
$environment.project.id = "";
$environment.project.name = $targetTeamProject;

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

if ($apply)
{
    $urlDestination = -join("https://dev.azure.com/chamindac/", $targetTeamProject, "/_apis/pipelines/environments?api-version=7.2-preview.1");
    $createedEnvironment = Invoke-RestMethod -Uri $urlDestination -Headers $header -Method Post -Body $environmentJson -ContentType "application/json"; 

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

No comments:

Popular Posts