SHIFT

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

User Tools

Site Tools


Sidebar

Recently Changed Pages:

View All Pages


View All Tags


LinkedIn




WIKI Disclaimer: As with most other things on the Internet, the content on this wiki is not supported. It was contributed by me and is published “as is”. It has worked for me, and might work for you.
Also note that any view or statement expressed anywhere on this site are strictly mine and not the opinions or views of my employer.


Pages with comments

View All Comments

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

You could leave a comment if you were logged in.
scriptazuredevopsremoveleases.txt · Last modified: 2022/04/22 06:58 by sjoerd