azure-devopsazure-active-directoryazure-managed-identityazure-releases

Authenticate to Azure DevOps without user's DevOps PAT


Currently we use an approach to reach DevOps and trigger "release pipelines" from a specific VM1 by utilizing user's DevOps PAT. We run PowerShell commands below at VM1:

$userPatToken = "xxxdfdgklfdgofkglfg4565gfhgfhgfh4gf54h54545fhfghfdffg"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $userPatToken)))

$url = "https://vsrm.dev.azure.com/MyOrg/MyProject/_apis/release/releases?definitionId=7&$top=100&api-version=6.0"
Invoke-RestMethod -Method Get -Uri $url -ContentType "application/json" -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo) }

The user is AAD one, is there a way to use it's let say AAD credentials and authenticate to DevOps and do the same? Or may there is a way to use VMs system managed (or any user managed) identity to authenticate into DevOps and trigger release pipelines? We do not want to be dependent of the user's PAT. It should be written in PowerShell.


Solution

  • If you don't want to use the PAT, you can install Az powershell module, login with a user account which has the permission in your devops org via Connect-AzAccount.

    Then, you can get the token via below command. Please note don't change the 499b84ac-1321-427f-aa17-267ca6975798 in the script, it is the well-known resource id of the DevOps REST API.

    $token = (Get-AzAccessToken -ResourceUrl "499b84ac-1321-427f-aa17-267ca6975798").Token
    

    Then, you can pass the token to your powershell script. You can find more details/sample script here.

    Edit:

    Add username&Password automation script sample:

    Install-Module -Name Az -Confirm:$False -Force -AllowClobber
    Import-Module Az
    $username = "useremail"
    $password = "password"
    $SecurePassword = ConvertTo-SecureString "$password" -AsPlainText -Force
    $credentials = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
    Connect-AzAccount -Credential $credentials -TenantId yourTenantID
    
    $token = (Get-AzAccessToken -ResourceUrl "499b84ac-1321-427f-aa17-267ca6975798").Token
    
    $URL = 'https://dev.azure.com/{orgname}/{Projectname}/_apis/pipelines/{pipelineID}/runs?api-version=6.0-preview.1'
    $header = @{
        'Authorization' = 'Bearer ' + $token
        'Content-Type' = 'application/json'
    }
    $body = @"
      {
        "resources": {
            "repositories": {
                "self": {
                    "refName": "refs/heads/master"
                }
            }
        }
      }
    "@
    
    Invoke-RestMethod -Method Post -Uri $URL -Headers $header -Body $body