Search code examples
powershellazure-devopsazure-pipelinesbitbucket-cloud

In an Azure Devops pipeline, how can I detect and cancel other build jobs from the same Git branch?


How do I write an Azure Pipeline script that detects whether any other CI build jobs are running using the same Git branch, and cancels those other jobs?

  • I want to cancel only CI build jobs. Any PR build jobs and manually triggered jobs from the same Git branch should be ignored, and allowed to continue running.

  • Any build jobs from other Git branches should also be ignored.

The Azure DevOps VM is a self-hosted Windows VM, so the task must be a PowerShell or Windows script, not bash. The source is in Bitbucket Cloud -- this is important, because ADO handles Bitbucket Cloud repositories differently from other repositories.

If a canned task is available, I can use it as well.

The following questions are related, but they do not directly address this use case.


Solution

  • The answer from @Shamrai-Alexsandr cancels the current build, but what I want to do was cancel all other builds (that is, CI builds on the current branch) still in progress.

    The answer from @bright-ran-msft gave me enough clues to combine @bright's solution with @shamrai's solution, replacing the exit 1 with code that cancels the other builds:

            if ($buildId -gt $bid) 
            {
                $build.status = "Cancelling"
                $cancelRequest = $build | ConvertTo-Json -Depth 10
                $uriCancel = "$orgUrl$teamProject/_apis/build/builds/$($build.id)?api-version=6.0"
                $resultOfCancel = Invoke-RestMethod -Uri $uriCancel -Method Patch -ContentType "application/json" -body $cancelRequest -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
                Write-Host "Result of Cancel request: " $resultOfCancel.status
            }