使用 Rest API 更新 Azure Devops 构建管道变量

Update Azure Devops Build Pipeline Variable with Rest API

我有一个基于 Azure Devops YAML 的构建(而非发布)管道。我定义了一个名为 Department 的变量。我的要求是在构建结束时使用其余 API 更新此变量。我正在使用此代码。

API 调用正常。但我不确定这是否是正确的 API 调用。该部门将针对每个构建进行更改。根据输出 HTTP 方法 put is not supported.

注意:Department我实际上定义了5个变量,Department是最后一个。当调用 API 时,它只输出前 3 个变量。


$Department = getDepartment.ps1

$url = "https://dev.azure.com/xxx/xxx/_apis/pipelines/$(System.DefinitionId)/runs?api-version=6.0-preview.1"

$pipeline = Invoke-RestMethod -Uri $url -Headers @{
          Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
      }
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"


$pipeline.variables.Department.value = $Department
      

$json = @($pipeline) | ConvertTo-Json -Depth 99


$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}

Write-host "==========================================================" 
Write-host "The value of Variable 'Department' is updated to $( $updatedef.variables.Department.value)"
write-host "=========================================================="

The Department will change for each build. According to the output HTTP method put is not supported.

根据文档Pipelines

它不提供使用 PUT 更新管道的方法。

要解决这个问题,您仍然需要使用 REST API Build Definitions - Update:

PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0

代码示例:

$url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0"

Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Headers @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"

$pipeline.variables.Test.value = "$Department"

####****************** 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"}

write-host "==========================================================" 
Write-host "The value of Varialbe 'Test' is updated to" $updatedef.variables.Test.value

测试结果: