Search code examples
azure-devopsazure-pipelinesazure-devops-pipelines

How to access the response of the InvokeRestAPI task from another job in an Azure DevOps pipeline?


I'm trying to automate the deployment of an Elasticsearch resource in the Elastic cloud, by invoking their REST API from within an Azure DevOps pipeline.

Invoking the API works fine using the InvokeRestAPI task, but now I want to use the information that is sent in the response to this API call. The documentation here says that this task can be used to invoke an HTTP API and parse the response but it doesn't give information about how to do that.

So far, I've tried to add a variable to my next job, based on a dependency, but that doesn't work:

- job: DeployES
  dependsOn: GenerateTipTenantId
  pool: server
  variables:
    tenantid: $[ dependencies.GenerateTipTenantId.outputs['GenerateGuid.faketenantid'] ]
  steps:
    - task: InvokeRESTAPI@1
      name: EsRest
      inputs:
        <InvokeRESTAPI task inputs generated by the assistant>

- job: processDeployment
  dependsOn: DeployES
  pool:
    vmImage: 'ubuntu-latest'
  variables:
    depid: $[ dependencies.DeployES.outputs['EsRest.Response.id'] ]
  steps:
    - script: echo $(depid)
      name: echoid

I could probably replace the InvokeRestAPI by a 'regular' Powershell script, but the InvokeRestAPI task seemed easier to set up.

So the question is: how can I access the JSON object in the API's response and pass on part of it to the next job in my pipeline?


Solution

  • The last part of the description the task:

    Use this task to invoke an HTTP API and parse the response.

    refers rather to successCriteria option which let you use response to indicate success or failure:

    Criteria which defines when to pass the task. No criteria means response content does not influence the result. Example:- For response {"status" : "successful"}, the expression can be eq(root['status'], 'successful'). More information

    So if you need to use response in your next task you need to use powershell, bash or any other shell task. For instance, here you have powershell script where I use API to get and modify ReleaseVersion:

    $url = "https://vsrm.dev.azure.com/thecodemanual/$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0"
    
    $pipeline = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
    Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
    
    $buildNumber = $env:BUILD_BUILDNUMBER
    $pipeline.variables.ReleaseVersion.value = $buildNumber
    
    ####****************** update the modified object **************************
    $json = @($pipeline) | ConvertTo-Json -Depth 99
    
    $updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}