How to trigger an Azure DevOps Pipeline via API
Azure DevOps pipelines can be triggered very easily using their API.
In practice, most build pipelines would be triggered via code changes or similar actions directly in Azure repos, so an external trigger would not be required. However, triggering via API can be very useful for a few different scenarios.
Some examples could be:
- Triggering a pipeline from a Slack message/bot.
- Triggering a pipeline to begin when a deployment ends on another service.
- Triggering a pipeline to begin if a critical error message is logged.
In my case, I was looking to run a set of automated tests via a webhook coming from an external CI/CD tool. This simple webhook would begin the automated test suite (webdriverio) when a deployment was complete.
Running the Pipeline
All that is required is a standard POST request.
fetch(AZURE_PIPELINE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic ' + AZURE_PERSONAL_ACCESS_TOKEN,
},
body: JSON.stringify({
resources: {
repositories: {
self: {
refName: 'refs/heads/master',
},
},
},
}),
})
The endpoint follows the pattern: https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=6.1-preview.1
You will also need a Personal Access Token from your Azure account:
- Go to your Azure Portal → https://dev.azure.com/
- In the upper right hand corner, click the User Setting icon and then Personal Access Tokens
- Click New Token and enter your details. For Scopes, select Read & Execute under Build.
- Save your new token and copy the token ID to use in your application.
There are lots of other things you can do with the Azure DevOps API.
Check out the full docs here.