How To Get a PAT (Personal Access Token) for Azure DevOps from the az cli

Another long title for a relatively short article.

In case you aren’t aware, the az cli has a great extension for Azure DevOps and supports automatically logging you in to the devops extension when you use az login. Very helpful and simple, no need to manually issue a PAT through the Azure DevOps portal.

Now, what about the scenario when you need a PAT to make a rest call to Azure DevOps? There are some scenarios that the devops az cli extension does not cover (such as queuing a yaml pipeline with parameters).

Here is a quick and easy PowerShell script to get you a PAT:

az login
$azureDevopsResourceId = "499b84ac-1321-427f-aa17-267ca6975798"
$token = az account get-access-token –resource $azureDevopsResourceId | ConvertFrom-Json
$authValue = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":" + $token.accessToken))
$headers = @{
Authorization = "Basic $authValue";
'X-VSS-ForceMsaPassThrough' = $true
}
$organization = "myorg"
$pipelineRunUrl = "https://dev.azure.com/$organization/_apis/projects"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-RestMethod -Uri $pipelineRunUrl -Method GET -Headers $headers -ContentType 'application/json' -Verbose

Note that there is not much documentation on using this mechanism with the az cli. I was able to work this out due to my previous experience obtaining an Azure Databricks token using the same command.

This is about as close as I can find to anything official: https://github.com/microsoft/azure-devops-auth-samples/blob/master/PersonalAccessTokenAPIAppSample/app_config.py

3 Replies to “How To Get a PAT (Personal Access Token) for Azure DevOps from the az cli”

Leave a Reply

Your email address will not be published. Required fields are marked *