powershelltfsmsbuildms-release-managementazure-devops-rest-api

Getting Unauthorised error while triggering TFS build from release definition


I need to trigger a build after successful deployment of a release. I have tried using below code in Powershell in the release definition.

After executing, I get this error - Access is denied due to invalid credentials

$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?
 api-version=2.0"

$body = "{ 'definition' : { 'id' : 1} }"

$type = "application/json"

$headers = @{
Authorization = "Basic d3JlblxzcsampleTIzNA=="
}

Write-Host "URL: $url"

$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -
Method Post -Headers $headers

Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"`

Solution

  • Based on my test, you can use -UseDefaultCredentials :

    $type = "application/json"
    
    $url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"
    
    $body = "{ 'definition' : { 'id' : 56} }"
    
    Write-Host "URL: $url"
    
    $definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -UseDefaultCredentials
    
    Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"
    

    Alternatively provide the specific Credential:

    $user = "username"
    $password = "password"
    
    # Base64-encodes the Personal Access Token (PAT) appropriately
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))
    $headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)}
    $type = "application/json"
    
    $url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"
    
    $body = "{ 'definition' : { 'id' : 56} }"
    
    Write-Host "URL: $url"
    
    $definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -Headers $headers
    
    Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"
    

    enter image description here