azureazure-devopsyamlazure-pipelines

Azure DevOps build pipeline logid for a specific task - dynamically


In Azure DevOps, I have a multistage build pipeline. In that pipeline, I have a task named - Terraform_init. I need the log ID of this task, dynamically. How do I find out the log ID dynamically, if I know the displayname of the task?

Current situation:

Right now I have figured out the Log ID for that task. But later, in my build pipeline, I will add more tasks before the Terraform_init task. So, the log Id will be changed for that task.

Why I need:

After Terraform init task, I have another task called Get_logs. This task gets the logs of the Terraform_init task and saves it in a blob. For that, I have to use the following line -

$logs_url = ('https://dev.azure.com/bmw-ai-big-data-platform/{0}/_apis/build/builds/{1}/logs/27?api-version=6.0' -f $($env:SYSTEM_TEAMPROJECTID), $($env:BUILD_BUILDID) )

I will have more tasks before the Terrafrom_init task, so ../logs/27.. - this part will need to update every time. I want to avoid this.


Solution

  • Use this code to get the logids:

    import requests
    import json
    
    url = "https://dev.azure.com/<orgname>/<project name>/_apis/build/builds/<build id>/timeline?api-version=6.0"
    
    payload={}
    headers = {
      'Authorization': 'Basic <base64encoded PAT>'
    }
    
    response = requests.request("GET", url, headers=headers, data=payload)
    
    reponse_json = response.json()
    records = reponse_json['records']
    for record in records:
        if record['name'] == 'Initialize job':
            print(record['log']['id'])
    

    After that, using logging command to output the data as variable, and then you can be able to use it in other following tasks(Only for runtime, compile time is unable to achieve.).