How to remove runs with Legacy retention Model

Viewed 168

I have runs which are retained due to Legacy retention model as below:

enter image description here

I'm not sure where it coming from. And I want to remove them but not going through each run and removing lease. Is there a way to do that?

1 Answers

I didn't found an settings on Azure DevOps to turn it off so I wrote powershell script which goes through each pipeline definition and then builds and remove Legacy Retention Mode lease and build with this lease.

$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":your-pat-here")) }

$organization = "org-name"
$project = "project-name"

$definitionsUrl = "https://dev.azure.com/${organization}/${project}/_apis/build/definitions?api-version=6.0"

$definitions = Invoke-RestMethod -Uri $definitionsUrl -Method Get -Headers $AzureDevOpsAuthenicationHeader

foreach ($definition in $definitions.value)
{
  Write-Host $definition.name -ForegroundColor Green
  
  $pipelineUrl = "https://dev.azure.com/${organization}/${project}/_apis/pipelines/$($definition.id)/runs?api-version=6.0-preview.1"

  # Invoke the REST call
  $result = Invoke-RestMethod -Uri $pipelineUrl -Method Get -Headers $AzureDevOpsAuthenicationHeader

  foreach ($run in $result.value) {
    $leasesUrl = "https://dev.azure.com/${organization}/${project}/_apis/build/builds/$($run.id)/leases?api-version=6.1-preview.1"

    $leasesResult = Invoke-RestMethod -Uri $leasesUrl -Method Get -Headers $AzureDevOpsAuthenicationHeader

    $ownerId = "Legacy Retention Model"
    foreach ($lease in $leasesResult.value) {
      if($lease.ownerId -Match $ownerId){

        $deleteLeaseUrl = "https://dev.azure.com/${organization}/${project}/_apis/build/retention/leases?ids=$($lease.leaseId)&api-version=6.0-preview.1"

        Write-Host "Removing ${ownerId} from run $($run.id) (created date $($run.createdDate))" -ForegroundColor Blue

        $leasesResult = Invoke-RestMethod -Uri $deleteLeaseUrl -Method Delete -Headers $AzureDevOpsAuthenicationHeader
        Write-Host "Removed lease"

        $deleteBuildUrl = "https://dev.azure.com/${organization}/${project}/_apis/build/builds/$($run.id)?api-version=6.0"

        $leasesResult = Invoke-RestMethod -Uri $deleteBuildUrl -Method Delete -Headers $AzureDevOpsAuthenicationHeader
        Write-Host "Removed build"
      }
    }
  }
}

Related