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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With