Trigger Azure DevOps Pipeline with a Python Script

We can use Azure DevOps API to trigger an ADO pipeline. In this quick start demo , we will go through how to trigger an Azure DevOps pipeline with a Python script.

I have already created an ADO pipeline called demo-pipeline. we are going to trigger this pipeline by using below Python script.

Following parameters are required to trigger a pipeline using API endpoint.

  • ADO Organization name
  • ADO Project name or Id
  • ADO Pipeline Id
azure devops console

Organization and project names can be found on Azure DevOps console. In my case, organization name is devops-counsel and project name is demo.

azure devops pipeline from console

To know the pipeline id go to pipelines, click on pipeline, then in URL you can see definitionId, that is pipeline id. here in my case it is 1.

Or we can also get pipeline id By running below azure cli command.

az pipelines show --organization https://dev.azure.com/devops-counsel --project demo --name demo-pipeline | jq '.id'

With above details we can construct the API endpoint URL, that is

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

We also need a PAT for authentication, to create a PAT go to User Settings -> personal access tokens -> new token to create a personal access token.

Azure DevOps  personal access token

Now we need to export below environment variables to trigger a pipeline.

Note: replace ADO_PAT variable value with your PAT

export PIPELINE_URL="https://dev.azure.com/devops-counsel/demo/_apis/pipelines/1/runs?api-version=7.1-preview.1"
export ADO_PAT="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Copy following Python code to a file and run it after exporting above variables.

import os
import requests
import base64

url = os.environ['PIPELINE_URL']
token = os.environ['ADO_PAT']
base64_token = str(base64.b64encode(bytes(':'+token, 'ascii')), 'ascii')
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Basic {base64_token}"
}
uri_data = {
    "resources": {},
    "templateParameters": {},
    "variables": {}
}
response = requests.post(url, json=uri_data, headers=headers)

def trigger_pipeline():
        try:
            response = requests.post(url, json=uri_data, headers=headers)
            response.raise_for_status()
            if response.json()['name']:
                    print("Pipeline has been triggered, it's id is " + response.json()["name"])
            else:
                    print("Pipeline triggger has failed. here is the error: " + response.json())
        except (ValueError) as e:
                raise e


if __name__ == "__main__":
    trigger_pipeline()

When you run the scipt it will trigger the ADO pipeline and prints pipeline name on screen.

ado pipeline trigger script output

in the below screen shot you can see a pipeline run with 20231011.17 name

ado pipeline runs

This is how we can trigger an Azure DevOps pipeline with a python script. You can find more information about this API call here.

Leave a Reply

%d