Search code examples
powershellazure-devopstfsbuildazure-pipelinesazure-devops-rest-api

Delete VSTS builds using the OAuth Token


With the new possibility to get the OAuth token to access the VSTS API during a build, I tried to write a script which deletes certain builds.

Reading builds works fine like this:

$headers = @{  Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"  }
$baseUrl = "{0}{1}" -f $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, $env:SYSTEM_TEAMPROJECTID
$buildsUrl = [string]::Format("{0}/_apis/build/builds?api-version=2.0", $baseUrl)
$response = Invoke-WebRequest -Uri $buildsUrl -Headers $headers

But while trying to delete a build I get a 403 Forbidden error:

$deleteUrl = [string]::Format("{0}/_apis/build/builds/{1}?api-version=2.0", $baseUrl, $id)
$response = Invoke-WebRequest -Uri $url -Headers $headers -Method Delete

Is deleting just not possible with the OAuth token provided by VSTS to the build or do I need to call the delete request differently?


Solution

  • It looks like a security issue. The build service account does not have the permission to "Delete Builds" by default. Set the permission to "Allow" and then try again. enter image description here enter image description here