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

无人久伴 提交于 2020-05-13 07:20:29

问题


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?


回答1:


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.

Yo 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.



来源:https://stackoverflow.com/questions/57004926/how-can-i-cancel-all-previous-build-when-a-new-one-is-queued

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!