Azure DevOps 管道:取消队列中的多个挂起作业

5
在Azure DevOps管道中,我如何取消作业池的所有挂起作业。我有很多排队等待的作业,但找不到可以取消所有等待作业的位置。
2个回答

6
Azure DevOps目前还没有批量取消所有挂起作业的功能,需要编写脚本调用REST API来实现。请按照以下步骤操作:首先使用list build rest api获取所有挂起的作业。

https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=5.1

然后,使用update build api取消挂起的作业: PATCH https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=5.1 参考以下 PowerShell 脚本:
单击此处获取将在下面脚本中使用的个人访问令牌
$url= "https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=5.1"

$pat="Personal Access Token"

$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))

$pendingJobs=Invoke-RestMethod -Uri $url-Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method get -ContentType "application/json" 

$jobsToCancel = $pendingJobs.value

#Pending jobs donot consume the job agents in the agent pool. To filter the definition name to cancel pending jobs for a particular pipeline, you can use below filter criteria. 
#$jobsToCancel = $pendingJobs.value | where {$_.definition.Name -eq "{Name of your pipeline }"}

#call update api to cancel each job.
ForEach($build in $jobsToCancel)
{
   $build.status = "Cancelling"
   $body = $build | ConvertTo-Json -Depth 10
   $urlToCancel = "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$($build.id)?api-version=5.1"
   Invoke-RestMethod -Uri $urlToCancel -Method Patch -ContentType application/json -Body $body -Header @{Authorization = ("Basic {0}" -f $base64AuthInfo)}
}

你也可以提交新的功能请求(点击建议一个特性并选择Azure DevOps),向微软开发团队提供支持批量取消挂起作业的请求。希望他们会考虑在未来的迭代中添加此功能。

1
我已经使用了您的脚本来解决完全相同的问题,但是在Invoke-RestMethod``VERBOSE: PATCH <server-url>_apis/build/builds/12495&api-version=5.0 with -1-byte payload中出现了异常- 我已经检查了$body,它已经完全填充并且是json格式。 - fduff
添加 &definitions=<ur-build-definitionid> 可以缩小取消操作的范围到一个构建管道。 - Dinesh Balasubramanian

0

我发现使用API的v6版本可以工作,但是不要使用PATCH而是使用DELETE。

(重用@Levi Lu-MSFT的一些代码)

$url= "https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=6.0-preview"

$pendingJobs=Invoke-RestMethod -Method GET -UseDefaultCredentials -Uri $url -ContentType "application/json" 

$jobsToCancel = $pendingJobs.value

#$jobsToCancel = $pendingJobs.value | Where {$_.definition.Name -eq "{Name of your pipeline }"}

ForEach($build in $jobsToCancel)
{
   $urlToCancel = "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$($build.id)?api-version=6.0-preview"
   Invoke-RestMethod -Uri $urlToCancel -Method DELETE -UseDefaultCredentials -ContentType application/json -Body $body
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接