azureazure-functionsazure-pipelinesazure-yaml-pipelines

Get a custom message from callback of task AzureFunction@1 in pipeline


I'm using the task AzureFunction@1 in an Azure yaml pipeline. According to the documentation, you can use a callback to indicate the task if it should pass or fail. This itself works as expected.

What I want to know is if there's a way to display some custom message in the pipeline with some summary of what happened? For example, if the task is supposed to fail, to also display in the pipeline a message like "Failed because of reasons X,Y,Z"? If not possible, is it maybe at least possible to poll the callback url somehow by C# code from another listening process, and get the message that way?


Solution

  • The AzureFunction@1 task can also be used as a check task in the release pipeline deployment gate: deployment gate.

    So, we can refer the document Send status updates to Azure DevOps from checks which also introduce more usage about Invoke Azure Function task. It mentions:

    You can provide status updates to Azure Pipelines users from within your checks using Azure Pipelines REST APIs.

    The steps to send status updates are:

    1. Create a task log
    2. Append to the task log
    3. Update timeline record

    Based the above information, I tested the Append to the task log API to add more logs to the task.

    First, here is the header in JSON format to be attached to the request sent to the function: Headers

    We will use the values from the header in the next steps, including the "HubName", "PlanId", "ProjectId","TaskInstanceId" and "AuthToken".

    Here is my test PowerShell script

    $AuthToken =""
    $organization = ""
    $projectId = ""
    
    $hubName = "build"
    $planId = ""
    $logId = 4
    $logURI = "https://dev.azure.com/$organization/$projectId/_apis/distributedtask/hubs/$hubName/plans/$planId/logs/${logId}?api-version=7.1"
    
    
    $headers = @{
        'Authorization' = "bearer " + "$AuthToken"
        'Content-Type' = 'application/octet-stream'
    }
    
    $logBody = @(
        '##[error]==================================='
        '##[error]Failed because of reasons X,Y,Z'
        '##[error]==================================='
    )
    
    foreach ($line in $logBody) {
        Invoke-RestMethod -Uri $logURI -Headers $headers -Method POST -Body $line
    }
    

    The $logId is found from the API https://dev.azure.com/$organization/$projectId/_apis/distributedtask/hubs/$hubName/plans/$planId/logs?api-version=7.1" based on the TaskInstanceId.

    logid

    Test result:

    result

    C# code sample to send the request to Append to the task log API:

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            var authToken = "your_auth_token";
            var organization = "your_organization";
            var projectId = "your_projectId";
            var hubName = "build";
            var planId = "your_planId";
            var logId = 4;
            
            var logURI = $"https://dev.azure.com/{organization}/{projectId}/_apis/distributedtask/hubs/{hubName}/plans/{planId}/logs/{logId}?api-version=7.1";
    
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
    
            var logBody = new[]
            {
                "##[error]===================================",
                "##[error]Failed because of reasons X,Y,Z",
                "##[error]==================================="
            };
    
            foreach (var line in logBody)
            {
                var content = new StringContent(line, Encoding.UTF8, "application/octet-stream");
                var response = await client.PostAsync(logURI, content);
    
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Log entry posted successfully.");
                }
                else
                {
                    Console.WriteLine($"Failed to post log entry: {response.StatusCode}");
                    var responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
        }
    }