Wednesday, September 11, 2024

How to create task to add new variable in existing variablegroups in Azure Devops library

Step 1: Create a Personal Access Token (PAT)

To interact with Azure DevOps REST API, you'll need a Personal Access Token (PAT) with the necessary permissions. Follow these steps:

  1. Go to Azure DevOps portal.

  2. Navigate to User settings (top right corner) > Personal access tokens.

  3. Click on New Token and provide the required access (e.g., "Read and Write to Build").

  4. Save the token for use in the script.

Step 2: Use the Azure DevOps REST API to Update Variable Group

To update the Variable Group, use a PowerShell or cURL script in your pipeline that calls the Azure DevOps REST API.

API Endpoint to Update Variable Group:

PATCH <https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups/{groupId}?api-version=7.1-preview.1>

Request Body Example:

To add or update variables within the group, you can use the following structure:

{ "variables": { "newVariable": { "value": "newValue" }, "existingVariable": { "value": "updatedValue" } } }

Step 3: PowerShell Script for Azure DevOps Pipeline

Here’s how you can write a PowerShell script to update the Variable Group. Add this as an inline PowerShell task in your pipeline.

steps: - task: PowerShell@2 inputs: targetType: 'inline' script: | $token = "$(System.AccessToken)" $organization = "your-org" $project = "your-project" $groupId = "your-variable-group-id" $url = "<https://dev.azure.com/$organization/$project/_apis/distributedtask/variablegroups/$groupId?api-version=7.1-preview.1>" $headers = @{ Authorization = "Bearer $token" "Content-Type" = "application/json" } $body = @{ variables = @{ "newVariable" = @{ value = "newValue" } "existingVariable" = @{ value = "updatedValue" } } } | ConvertTo-Json -Depth 10 Invoke-RestMethod -Uri $url -Method Patch -Headers $headers -Body $body env: System.AccessToken: $(System.AccessToken) # Ensure "Allow scripts to access OAuth token" is enabled

Key Points:

  • Ensure the System.AccessToken is provided and enabled in the pipeline's Agent Job (under "Allow scripts to access the OAuth token").

  • Replace your-org, your-project, and your-variable-group-id with your actual Azure DevOps values.

  • Adjust the body of the request based on the variables you want to add/update.

Step 4: Add Task to Your Pipeline

Add the PowerShell task to your Azure DevOps pipeline YAML file. This script will invoke the Azure DevOps REST API to update the variable group by adding new variables.

Step 5: Run the Pipeline

Once the task is in place, run the pipeline, and it will update the variable group with the new variables.

This approach should allow you to automate the management of variable groups directly from within your Azure DevOps pipelines.

No comments :