Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cancel all previous build when a new one is queued?

With Azure DevOps how can I cancel the current build when a new one is started?

I want to save my build time. On my master branch sometime I do a merge then another developer do one and another do one again. I don't need to do build by build. I can keep only the latest build. So when a new build is queued this one can cancel all previous build.

Is it possible to setup his build definition to do so?

like image 341
Bastien Vandamme Avatar asked Feb 04 '23 18:02

Bastien Vandamme


1 Answers

There is no such feature in Azure DevOps.

The closest thing it's to use "Batching CI builds" - when a build is running, the system wait until the build is completed, then queues another build of all changes that have not yet been built.

To enable it in yaml build add this in the trigger section:

batch: true

In the calssic editor, go to "Triggers" tab and mark the checkbox "Batch changes while a build is in progress".

Edit:

You can run a PowerShell script in the beginning of the build that cancel the running builds from the same definition:

$header = @{ Authorization = "Bearer $env:System_AccessToken" }
$buildsUrl = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/builds/builds"
$builds = Invoke-RestMethod -Uri $url -Method Get -Header $header
$buildsToStop = $builds.value.Where({ ($.status -eq 'inProgress') -and ($_.definition.name -eq $(Build.DefinitionName)) -and ($_.id -ne $(Build.BuildId)) })
ForEach($build in $buildsToStop)
{
   $build.status = "Cancelling"
   $body = $build | ConvertTo-Json -Depth 10
   $urlToCancel = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$(builds.id)"
   Invoke-RestMethod -Uri $urlToCancel -Method Patch -ContentType application/json -Body $body -Header $header
}

I used OAuth token for authorization (enable it on the job options) and in inline script ($(varName) and not $env:varName).

Now, if you have one build that running and someone else trigger another build that started to run, in this step the first build will be canceled.

like image 86
Shayki Abramczyk Avatar answered Apr 08 '23 03:04

Shayki Abramczyk