如何从Azure DevOps管道中的另一个作业访问InvokeRestAPI任务的响应?

时间:2020-08-22 07:37:47

标签: azure-devops azure-pipelines azure-devops-pipelines

我正在尝试通过在Azure DevOps管道中调用REST API来自动在Elastic cloud中部署Elasticsearch资源。

使用InvokeRestAPI任务调用API可以正常工作,但是现在我想使用在对此API调用的响应中发送的信息。 here文档说此任务可用于调用HTTP API并解析响应,但未提供有关如何执行此操作的信息。

到目前为止,我已经尝试根据依赖关系将变量添加到我的下一个作业中,但这是行不通的:

- 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

我可能可以用“常规” Powershell脚本替换InvokeRestAPI,但是InvokeRestAPI任务似乎更容易设置。

所以问题是:如何访问API响应中的JSON对象并将其部分传递给管道中的下一个作业?

1 个答案:

答案 0 :(得分:1)

说明the task的最后一部分:

使用此任务来调用HTTP API并解析响应

而是指successCriteria选项,该选项使您可以使用响应来指示成功或失败:

定义何时传递任务的标准。没有条件表示响应内容不会影响结果。示例:-对于响应{“ status”:“ successful”},表达式可以是eq(root ['status'],'successful')。 More information

因此,如果您需要在下一个任务中使用响应,则需要使用powershell,bash或任何其他shell任务。例如,这里有一个powershell脚本,我在其中使用API​​来获取和修改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"}
相关问题