Skip to content

Instantly share code, notes, and snippets.

@rfennell
Last active January 29, 2021 09:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rfennell/13b014fc816822cc9007ae26cc2cb43f to your computer and use it in GitHub Desktop.
Save rfennell/13b014fc816822cc9007ae26cc2cb43f to your computer and use it in GitHub Desktop.
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