Run Pipeline via Azure Function by Rest API

Abhijit M 25 Reputation points
2024-09-20T09:56:02.2233333+00:00

I want to run an azure build pipeline and as per the documentation given here https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run-pipeline?view=azure-devops-rest-7.1&source=docs i could utlise Rest API to run a pipeline. I tried creating an azure function which serves the purpose and it's able to do so I pass a PAT token in header for authentication
I want to know how i can perform the same without utlising PAT token but some other sort of authenication

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,029 questions
0 comments No comments
{count} votes

Accepted answer
  1. Vinodh247 21,881 Reputation points
    2024-09-22T11:46:47.68+00:00

    Hi Abhijit M,

    Thanks for reaching out to Microsoft Q&A.

    To run an Azure DevOps pipeline via an Azure Function using a different authentication method instead of a PAT, you can leverage Azure AD auth through service principals or managed identities. Here's how you can achieve this:

    Service Principal Authentication (Client Credentials)

    Instead of using a PAT token, you can authenticate with Azure DevOps using a service principal. This method involves creating an Azure AD app registration, granting the necessary permissions, and then using the app’s client ID and client secret to obtain an OAuth token.

    Steps to try:

    Create an App Registration in Azure AD:

    Register a new application in Azure AD (Azure Active Directory > App Registrations > New Registration). Make note of the client ID, tenant ID, and create a client secret.

    Assign Permissions to the Service Principal in Azure DevOps:

    • In your Azure DevOps organization, navigate to Project Settings > Permissions.
    • Add the service principal as a member to the relevant project or group, and assign the necessary permissions (ex., Contributor or Build Pipeline permissions).

    Grant API Access to Azure DevOps: In Azure AD, under the API permissions tab of the app registration, add permissions to allow the service principal to call the Azure DevOps APIs. You will need to request user_impersonation permission for the Azure DevOps API.

    Obtain an OAuth Token: In your Azure Function, use the following code to get an OAuth token using client credentials:

    import requests
    def get_access_token(tenant_id, client_id, client_secret):
        url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
        payload = {
            "grant_type": "client_credentials",
            "client_id": client_id,
            "client_secret": client_secret,
            "scope": "499b84ac-1321-427f-aa17-267ca6975798/.default"  # Azure DevOps scope
        }
        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
        response = requests.post(url, data=payload, headers=headers)
        token = response.json().get("access_token")
        return token
    
    

    Run the Pipeline with the OAuth Token: After obtaining the token, pass it in the 'Authorization' header in your Azure Function when making the API request to run the pipeline.

    def run_pipeline(organization, project, pipeline_id, token):
        url = f"https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipeline_id}/runs?api-version=7.1-preview.1"
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }
        payload = {
            # Add your pipeline run details here
        }
        response = requests.post(url, json=payload, headers=headers)
        return response.json()
    
    

    MI Auth (if using Azure Function with MI):

    If your Azure Function has a MI enabled, you can use it to authenticate with Azure DevOps. This is a more secure approach as it eliminates the need for secrets or credentials.

    Steps:

    1. Enable Managed Identity for Azure Function: In the Azure portal, go to your Azure Function > Identity and turn on the managed identity.
    2. Grant Access to Azure DevOps: Add the managed identity to the Azure DevOps project or team with the necessary permissions (Contributor or Build permissions).
    3. Use Managed Identity to Obtain an Access Token: You can obtain an access token for Azure DevOps using the managed identity as follows:
    import requests
    import os
    def get_msi_token():
        url = "http://169.254.169.254/metadata/identity/oauth2/token"
        params = {
            "api-version": "2018-02-01",
            "resource": "499b84ac-1321-427f-aa17-267ca6975798"  # Azure DevOps resource ID
        }
        headers = {"Metadata": "true"}
        response = requests.get(url, params=params, headers=headers)
        token = response.json().get("access_token")
        return token
    
    
    1. Run the Pipeline with the Managed Identity Token: Once you get the token, pass it in the 'Authorization' header to run the Azure DevOps pipeline as shown earlier.

    Note: The code provided above is as is and only a demo, you have to edit and modify according to your env.

    Please 'Upvote'(Thumbs-up) and 'Accept' as an answer if the reply was helpful. This will benefit other community members who face the same issue.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.