问题
I have an Azure DevOps Build Pipeline which contains two Agent Jobs, which I'll call Job A and Job B. I want these jobs to run simultaneously, but if Job A fails, then I don't need Job B to run to completion.
Is there any way to add a task to Job A which will cancel Job B (or, alternately, terminate the entire pipeline with a "Failed" status) if any of Job A's tasks failed?
回答1:
Add a PowerShell task that cancel the pipeline when a task failed:
steps:
- powershell: |
Write-Host "Cancel all jobs..."
$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds/$($env:BUILD_BUILDID)?api-version=2.0"
$header = @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
$body = @{ 'status'='Cancelling' } | ConvertTo-Json
Invoke-RestMethod -Uri $url -Method Patch -Body $body -Headers $header -ContentType application/json
displayName: Cancel the pipeline
condition: failed()
env:
System_AccessToken: $(System.AccessToken)
Result:
回答2:
The bash equivalent for @shayki-abramczyk 's script (thanks btw!)
- bash: |
echo "Cancel all jobs..."
url="${SYSTEM_TEAMFOUNDATIONCOLLECTIONURI}${SYSTEM_TEAMPROJECTID}/_apis/build/builds/${BUILD_BUILDID}?api-version=2.0"
curl -X "PATCH" "$url" \
-H "Authorization: Bearer ${SYSTEM_ACCESSTOKEN}" \
-H 'Content-Type: application/json' \
-d $'{"status":"Cancelling"}'
displayName: Cancel the pipeline
condition: failed()
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
You will have to also go into your project settings in azure devops, Permissions, Groups, edit the Build Administrators group and then add the Project Collection Build Service (yourcompanyhere) user to it.
Also a quick note on Failed over Cancelled. According to the docs there is a "result" field which has a failed option, but the "status" field does not. I have tried many permutations of just updating one and not the other, but the status=cancelling one is the only reliable one and in no cases could I get it to show the build as "failed" :(
Docs for the build api update method are here: https://docs.microsoft.com/en-us/rest/api/azure/devops/build/builds/update%20build?view=azure-devops-rest-6.0
来源:https://stackoverflow.com/questions/57466218/is-an-azure-devops-build-pipeline-is-there-a-way-to-cancel-one-pipeline-job-fro