Instantly share code, notes, and snippets.

Embed
What would you like to do?
A bit of PowerShell to add capabilities to a Azure DevOps Pipeline Agent programmatically
##-----------------------------------------------------------------------
## <copyright file="Add-CapabilityToAgent.ps1">(c) Tichard Fennell </copyright>
##-----------------------------------------------------------------------
# Adds capacility tags a Azure DevOps Pipeline agent
# Run in the agent folder
Param
(
[parameter(Mandatory=$true,HelpMessage="Personal Access Token with rights to manage agents")]
$patToken,
[parameter(Mandatory=$false,HelpMessage="The tags to added as a block of JSON ")]
$tags = "{SONAR_SCANNER:'true',UxTest:'true'}",
[parameter(Mandatory=$true,HelpMessage="The Azure DevOps instance target name")]
$organisation
)
function Get-WebClient
{
param
(
[string]$username,
[string]$password,
[string]$contentType = "application/json"
)
$wc = New-Object System.Net.WebClient
$wc.Headers["Content-Type"] = $contentType
if ([System.String]::IsNullOrEmpty($password))
{
$wc.UseDefaultCredentials = $true
} else
{
# This is the form for basic creds so either basic cred (in TFS/IIS) or alternate creds (in VSTS) are required"
$pair = "${username}:${password}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$wc.Headers.Add("Authorization","Basic $base64");
}
$wc
}
Write-Host "Getting the agent details"
$agent = (Get-Content '.agent' | Out-String | ConvertFrom-Json)
Write-host "Adding tags"
$wc = Get-WebClient -password $patToken
$uri = "https://$organisation.visualstudio.com/_apis/distributedtask/pools/$($agent.poolId)/agents/$($agent.agentId)/usercapabilities?api-version=5.0-preview.1"
$response = $wc.UploadString($uri,"PUT", $tags )| ConvertFrom-Json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment