Azure DevOps pipelines: Cancel multiple pending jobs in queue - azure-devops

In Azure DevOps pipelines, How do I cancel all pending jobs for a job pool. I've got lots queued and couldn't see where I can cancel all the jobs I have waiting.

Azure devops doesnot yet have this feature to cancel all the pending jobs in batch from the UI partal.
You can write scripts to call rest api to cancel all the pending jobs as walkaround. Check out below steps:
First, use list build rest api to get all the pending jobs.
https://dev.azure.com/{organization}/{project}/_apis/build/builds?statusFilter=notStarted&api-version=5.1
Then, use update build api to cancel the pending jobs:
PATCH https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=5.1
See below powershell scripts for reference:
Check here to get a Personal access token that will be used in below scripts.
$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)}
}
You can also submit a new feature request(Click Suggest a feature and choose azure devops) to Microsoft development team for supporting cancelling pending jobs in batch. Hopefully they will consider adding this feature in the future sprint.

I find that using v6 of the api works, but instead of PATCH use DELETE.
(Reusing some of the code from #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
}

Related

From where I get all publish artifact of all stages of azure build pipeline instead of searching from all stages

I am publishing build artifact of each run over azure pipeline, whatever artifact I have published than can be accessible to that specific stage(run), But my query is in Azure is there any build artifacts repository where we can get all the build artifacts for all the builds of that pipeline ?
To get all the build artifacts for all pipeline runs, you need to combine the following two Rest APIs: Builds - List and Artifacts - List
Here is a PowerShell example:
$token = "PAT"
$url="https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
ForEach( $buildid in $response.value.id )
{
echo $buildid
$url1= "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$($buildid)/artifacts?api-version=4.1"
$response1 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
echo $response1 | ConvertTo-Json
}
This sample will traverse all pipeline runs and get relevant artifacts information.
Update:
When you use Classic Pipeline, you could add a PowerShell task and input the PowerShell Script. Please change the parameters in the script to make it suitable for your organization

Azure DevOps Server - pause/resume all pipelines during maintenance window

We have an Azure DevOps Server (on prem) and different build/release pipelines.
A build/release is depending to other systems. Now if we plan to do maintenance work on this other systems, no Azure build/release pipeline should be run during this time because of the dependency of this systems.
We can go to every pipeline and set the pipeline to "pause". This is working well for a small numbers of build/release pipelines, but if we have a lot of pipelines this would be time-consuming to enabled-disable all pipelines.
Is there any way to pause/resume all Azure Pipelines at the same time? (e.g. TeamCity has a simple flag to pause/resume the whole queue).
I checked the API, but there is also no way to disable the queue itself (change setting on the build/release pipeline). It this would be possible, we could loop through every pipeline definition and pause/resume the queue.
You can disable the agents to prevent the pipeline from running.
Go the Agent Pools under Pipelines in Project settings-->Select the agent pool -->Go to Agents tab-->Disable all the agents.
You can also use rest api to pause the build pipeline mentioned in the comments. See below example in powershell scripts: See here to get a personal access token.
$PAT="Personal Access Token"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
#list build definiations api
$url = "https://dev.azure.com/org/proj/_apis/build/definitions?api-version=6.1-preview.7"
#list all build definitions
$AllDefinitons = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = ("Bearer {0}" -f $base64AuthInfo)} -Method get
#get all the definition ids
$Ids = $AllDefinitons.value | select id
foreach($id in $Ids){
$definitionUrl="https://dev.azure.com/org/proj/_apis/build/definitions/$($id.id)?api-version=6.1-preview.7"
#get the definition of each build pipeline
$definiton = Invoke-RestMethod -Uri $definitionUrl-Headers #{Authorization = ("Bearer {0}" -f $base64AuthInfo)} -Method get
#set queueStatus to paused
$definiton.queueStatus= "paused"
#update the definition
Invoke-RestMethod -Uri $definitionUrl-Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method put -Body (ConvertTo-Json $definiton-Depth 100) -ContentType "application/json"
}

Execute Mutliple release pipeline

I have 50+ release pipelines for the production environment and each time doing production has to manually approve each of these pipelines for deployment.
Is there any way to automate and in a single click, all the pipeline gets approved and gets deployed?
The only way I am aware of accomplishing this would be to combine the 50+ pipelines into one master release and have those dependent on a separate stage who is deploying to a gated environment. Assign an approval on that environment. Thus once that stage in the "approval environment" is approved all subsequent stages will run.
In Azure DevOps, we can configure approvals, It checks all the resources used in that stage, such as source code and follow the target server deployed, this should let managers to check and agree this deploy, batch approval is meaningless.
If you insist on approving multiple release pipeline stages at the same time. we recommend that you can remove these approvals.
Or we can use API to list all Approvals and get the approval id, then update status of an approval.
In addition, if there are multiple approvals in the pipeline, it will only approve the current stage.
Steps:
Create a PAT token->create a build pipeline->click the tab variable and add the variable pat = {Token}, then set it to secret variable->add task powershell and enter the following script to approve.
$connectionToken="$(pat)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$PipelineUrl = "https://vsrm.dev.azure.com/{Org name}/{Project name}/_apis/release/approvals?api-version=5.1"
$Pipelines = (Invoke-RestMethod -Uri $PipelineUrl -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
$ ApprovalId = $Pipelines.value.id
Write-Host $ ApprovalId
# List all Approvals and get approval id
ForEach ($Id in $ ApprovalId)
{
$baseUrl = "https://vsrm.dev.azure.com/{Org name}/{Project name}/_apis/release/approvals/$($Id)?api-version=5.1"
$body ="{
`"status`": `"approved`"
}"
$response = Invoke-RestMethod -Uri $baseUrl -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PATCH
}

Capture commit count per pull request in Azure DevOps

I would like to get info on the number of commits per pull request. For now, semi-automated would be fine. Just looking for a simple approach, say, a PowerShell script. I'll likely need to create similar types of reports with different data in the future.
Does any approach lend itself to such a quick and dirty approach with Azure DevOps data?
There is a special Rest API for this: Pull Request Commits - Get Pull Request Commits:
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/commits?api-version=5.1
So, simple PowerShell script:
$pat = "YOUR-PERSONAL-ACCESS-TOKEN"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"$pat")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/commits?api-version=5.1"
$commitsCount = (Invoke-RestMethod -Method Get -Uri $url -Headers $headers -Body $jsonBody -ContentType 'application/json').count

How to get status of the release (success, failure) with powershell using Azure DevOps Rest API

I am using post method to create release in Azure DevOps:
$url = "https://vsrm.dev.azure.com/"+$organization+"/"+$project+"/_apis/release/releases?api-version=5.1"
$body = #{definitionId = 9} | ConvertTo-Json -Depth 4
Invoke-RestMethod -Uri $url -Method POST -Body $body -ContentType "application/json" -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
My pipeline is simple with single stage which executes automatically. Release creation and execution works fine.
But how to get status of my stage/s using powershell and REST API. I need to keep executing script while Release is in progress and initiate script failure if any of the stages fails.
Any ideas?
Using DefinitionID and EnvironmentIDs (you will get this from your initial POST response), you can query the last release and check for "deploymentStatus" value in intervals and exit when the status changes to "succeeded/failed/cancelled".
(collectionURL)/(teamproject)/_apis/Release/deployments?definitionId="+RELEASE_DEFINITIONID+"&definitionEnvironmentId="+RELEASE_DEFINITIONENVIRONMENTID?api-version=1.0