Ashish Kumar
Ashish Kumar

Reputation: 83

Get the failure message of a task in another task in Azure yaml pipelines

I am writing a YAML pipeline and want to report issues in a particular task to application insights. I am trying to do something like this:

- task: Task1
  displayName: doSomething1

- task: Task2
  displayName: doSomething2

- task: Task3
  displayName: log failures in task1 and task2

Basically, Task1 and Task2 do some stuff, and if either of those tasks fails, I want task3 to start executing. Task3 will send the data to application insights. Is there any way to know which task failed and get the failure log of that task inside task 3 so that it can be sent to application insights?

Is there any better alternative way to achieve this?

Upvotes: 1

Views: 1193

Answers (1)

Kevin Lu-MSFT
Kevin Lu-MSFT

Reputation: 35514

Is there any better alternative way to achieve this?

You can use task to run Rest API: Timeline - Get to get the error message and the failed task.

Here is PowerShell example:

$token = "PAT"

$url="https://dev.azure.com/{ORG}/{project}/_apis/build/builds/$(build.buildid)/timeline?api-version=6.0"

$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))



$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json

$errors = $response.records.Where({ $_.result -eq "failed“ })



$errors.ForEach({
   
   $_.name

   $_.issues.ForEach({ $_.message })
})

Result:

enter image description here

At the same time, you need to set the condition for the tasks.

For example:

- task: Task1
  displayName: doSomething1

- task: Task2
  displayName: doSomething2

- task: Task3
  displayName: log failures in task1 and task2
  condition: failed()

Here is a doc about Condition.

Upvotes: 3

Related Questions