Friday 11 November 2022

Create Deployment Groups Dynamically in Azure DevOps Release Pipeline

 Deployment groups are used in Azure DevOps classic release pipelines to define groups of targets an application should be deployed. We may sometime need to create these deployment groups dyamically based on the stage we are running in release pipeline. Let's look at the sample PowerShell code to use for creating depployment group dynamically, using Azure DevOps REST API, and how to use it in a pipeline.

The PowerShell script below is capable of creating a deployment group if a deployment group is not existing with the same name.

$token = 'yourPAT'
$User=""

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User,$token)));
$header = @{Authorization=("Basic {0}" -f $base64AuthInfo)};

$Uri = -join ('https://dev.azure.com/OrgName/TeamProjectName/_apis/distributedtask/deploymentgroups?name=', 'DeploymentGroupName', '&api-version=7.1-preview.1')

$deploymentGroup = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri -Headers $header

if ($deploymentGroup.count -eq 0)
{

    $Uri = 'https://dev.azure.com/OrgName/TeamProjectName/_apis/distributedtask/deploymentgroups?api-version=7.1-preview.1'
$deploymentGroupMetadata = ' { "name": "DeploymentGroupName"
} '; $deploymentGroup = Invoke-RestMethod -Method Post -ContentType application/json -Uri $Uri -Body $deploymentGroupMetadata -Headers $header } $deploymentGroup


We need to use a Personal Access Token (PAT) with Deployment Groups read and manage for the above script if we are running it locally.



To use the script in a pipeline you can use a PowerShell task.

In a pipeline you can use SYSTEM_ACCESSTOKEN instead of a personal access token. For the sytem access token to use to create deployment groups in deployment groups security, you need to add Administrator role to the project build service user.




No comments:

Popular Posts