SHIFT-WIKI

--- Sjoerd Hooft's InFormation Technology ---

User Tools

Site Tools


scriptazuredevopsremoveleases

Script: Azure DevOps API: Remove Leases

Goal of the script is to remove all the leases that are set on all of the builds that are created with a specific pipeline:

  • Retrieve the builddefinition id for the specified pipeline
  • Lists all leases for the builddefinition
  • Removes all the leases for the build definition id

If the leases kept you from deleting the build pipeline, you can delete the pipeline afterwards.

The Script

Note that you need to change the first four variables.

# Define organization base url, PAT and API version variables
$orgUrl = "https://dev.azure.com/ORGNAME"
$project = "projectname"
$builddefinition = "buildpipelinename"
$pat = "XXXX"
$apiversion = "api-version=6.1-preview"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = @{authorization = "Basic $token"}
 
#Get build definition ID for $buildefinition
$buildurl = "$orgurl/$project/_apis/build/definitions?$apiversion"
Write-Output "Build url = $buildurl"
$builddefinitionid = ((Invoke-RestMethod -Uri $buildurl -Method GET -ContentType "application/json" -Headers $header).Value | select-object id,name | where-object {$_.name -eq $builddefinition}).id
Write-Output "Build definition $builddefinition has the id $builddefinitionid"
 
# Function to delete all retention leases for a build definition
function DeleteLease($defid) {
 
    #Get all leases for the build definition
    $leaseurl = "$orgurl/$project/_apis/build/retention/leases?$apiversion&definitionId=$defId"
    Write-Output "Lease url = $leaseurl"
    $leases = (Invoke-RestMethod -Method GET -Uri $leaseurl -ContentType "application/json" -Headers $header )
    Write-Output "The Build definition $builddefinition has $($leases.count) leases"
 
    #Loop through all leases and delete them. 
    foreach ($lease in $leases.value) {
        $leaseId = $lease.leaseId
        $leaseurl = "$orgurl/$project/_apis/build/retention/leases?ids=$($leaseId)&$apiversion"
        Write-Output $leaseurl
        Invoke-RestMethod -Method DELETE -Uri $leaseurl -ContentType "application/json" -Headers $header
    }
}
 
DeleteLease $builddefinitionid

Resources

scriptazuredevopsremoveleases.txt · Last modified: 2022/04/22 08:58 by sjoerd