Search code examples
azure-devopsazure-language-understanding

How do I Invoke a REST API from Azure DevOps using Bearer Token


I'm trying to use an Azure DevOps task to programatically assign a LUIS predict resource to a LUIS app, as documented here. In short, this involves

I am able to execute these steps manually, but how to I do this from Azure DevOps? I have tried to use a 'Invoke REST API' task from an agentless job, but don't see how I can retrieve and use the Bearer token. Note the Bearer token expires.

Thanks for your advice.


Solution

  • You can add a powershell task in your pipeline to do this from azure devops.

    Get an Azure Resource Manager token: You can refer to below powershell scripts to get the token. Check here for more information about where to get client id and client secret. Please be noted that the resource here is "https://management.core.windows.net/"

    $client_id = "{client id}"
    $client_secret = "{client secret}"
    $uri= "https://login.microsoftonline.com/{tenant id}/oauth2/token"
    
    $Body = @{
            'resource'= "https://management.core.windows.net/"
            'client_id' = $client_id
            'grant_type' = 'client_credentials'
            'client_secret' = $client_secret
    }
    
    $params = @{
        ContentType = 'application/x-www-form-urlencoded'
        Headers = @{'accept'='application/json'}
        Body = $Body
        Method = 'Post'
        URI = $uri
    }
    
    $response = Invoke-RestMethod @params
    $token = $response.access_token
    

    After the you got the token you can pass it to the LUIS rest api. Below script is just for example.

    $LuisBody = @{
            "azureSubscriptionId"= "{subscription_id}"
            "resourceGroup"= "{resource_group_name}"
            "accountName"= "{account_name}"
    }
    
    $Luisparams = @{
        Headers = @{ 
            Authorization = ("Bearer {0}" -f $token) # pass the token which got from above script
            "Ocp-Apim-Subscription-Key" = "{subscription key}"
            ContentType = "application/json"
            }
    
        Body = $LuisBody
        Method = 'Post'
        URI = "https://{endpoint}/luis/api/v2.0/apps/{appId}/azureaccounts"
    }
    
     Invoke-RestMethod @Luisparams
    

    There is another blog you might find helpful.

    Update: GetAzure Resource Manager token with Azure CLI with below script:

    az account get-access-token --resource=https://management.core.windows.net/ | jq -r .accessToken

    Check official documents here, and here for an example.