Redline1111
Redline1111

Reputation: 131

Using Rest API to trigger a specific stage within a yaml pipeline

Is there a way to execute a specific stage within a running yaml pipeline which uses an environment with approvals?

I have an on-prem deploy and an on-prem destroy stage both have manual approvals.

What I would like to do is run on-prem destroy stage in the past builds using rest api.

What I achieved so far is get 10 recent builds in descending order for a specific source branch lets call it feature/on-prem-enterprise. Then I do some parsing and find past builds that had a successful deployment but failed, cancelled, or skipped destroy stage, using these results from timeline endpoint, I want to use rest api to run/re-run a destroy stage in those builds.

We get into a situation where we have several deployments but nobody is manually running the destroy stage and because this pipeline is shared amongst all developers for dev builds, its very difficult to find those older builds manually.

If it cannot be achieved, then other solution may be to compile this list of builds and send an email out, but would prefer to have less manual intervention here.

Upvotes: 0

Views: 1842

Answers (2)

Nick Graham
Nick Graham

Reputation: 1469

You can use the Stages - Update REST API method. This is part of the Build resource methods but works fine for YAML Pipelines as well.

PATCH https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/stages/{stageRefName}?api-version=7.1-preview.1

It sounds like you're already getting the buildId programmatically. The stageRefName is the name of the stage as defined in your YAML. Your URI will look something like:

https://dev.azure.com/myorg/myproject/_apis/build/builds/1234/stages/DestroyStageName?api-version=7.1-preview.1

In the request body you'll need:

{
    forceRetryAllJobs = $false
    state = 1 # state 1 is retry
}

forceRetryAllJobs may be unnecessary. There's an example implementation in PowerShell here.

If you're struggling to identify the appropriate API method to replicate something you do in the Azure DevOps GUI opening your browser's debugger tools and inspecting the requests in the network tab can often help you identify the call that's being used.

Upvotes: 0

Leo Liu
Leo Liu

Reputation: 76660

Is there a way to execute a specific stage within a running yaml pipeline which uses an environment with approvals?

The answer is yes.

You could use the REST API Runs - Run Pipeline with below request body to skip other stages to trigger stage which you wanted:

POST https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=6.0-preview.1

Request Body:

{
    "stagesToSkip":["Dev","Test"]
}

Postman test result:

enter image description here

And the test result for the pipeline runs:

enter image description here

Upvotes: 3

Related Questions