如何使用REST API更新Azure DevOps Server 2019中的当前阶段发布变量?

问题描述

我想在阶段运行时更新发行版(而不是发行版定义)范围变量的值,但每次尝试时都会收到以下错误消息。

我该怎么做?

##[error]Invoke-RestMethod : {"$id":"1","innerException":null,"message":"VS402898: Stage 'dev' cannot be modified as it is 
in-progress or completed. Changes were detected in the following properties: 
'Variables'","typeName":"Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException,Mic
rosoft.VisualStudio.Services.ReleaseManagement2.Data","typeKey":"InvalidRequestException","errorCode":0,"eventId":3000}
At line:263 char:5

+     Invoke-RestMethod -Uri $url -Method Put -ContentType "application ...

+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],WebExc 

   eption

    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
2020-11-03T06:45:48.2096034Z ##[error]PowerShell exited with code '1'.

示例脚本:

$url = "{0}{1}/_apis/Release/releases/{2}?api-version=5.0" -f $env:SYstem_TEAMFOUNDATIONCOLLECTIONURI,$env:SYstem_TEAMPROJECTID,$env:RELEASE_RELEASEID

$pipeline = Invoke-RestMethod -Uri $url -Method Get -Headers @{
    Authorization = "Bearer $env:SYstem_ACCEsstOKEN"
}

# Update an existing scoped variable named Testvar
# Just for StackOverflow we assume that the currently running stage in Azure DevOps Server
# matches this environment[0] below
$pipeline.environments[0].variables.Testvar.value = "NewValue"

$body = $pipeline | ConvertTo-Json -Depth 99

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

以防万一,还有另一种解决方案...我要实现的目标是稍后将PowerShell脚本的变量输出用于单独的“替换文件” JSON转换步骤,以在其中填充值Web应用程序的appsettings.json文件。问题在于该变量是在一个作业中创建的,并且“替换文件”步骤未使用该变量,因为我认为它需要是一个发布变量,而不仅仅是任务变量。

解决方法

根据错误消息VS402898: Stage 'dev' cannot be modified as it is in-progress or completed和文档说明,您似乎正在使用this REST API。我们只能使用它来更新完整版本

作为一种解决方法,我们可以在创建发行版时更改变量值。

我的测试步骤:创建一个发布变量->将其命名为测试并将值设置为55->启用选项可在发布时设置->添加任务power shell以打印变量{ {1}}值

然后调用rest API创建发布并更新运行时发布变量。

注意:它不会更改发行版定义变量。

API:

test

请求正文:

POST https://{instance}/{collection}/{project}/_apis/release/releases?api-version=5.0

结果:

enter image description here

更新1

似乎您想在代理作业之间传递变量,我们无法在经典模式下执行此操作,我们可以在YAML模式下使用输出变量,请参考此docblog更多细节。

示例代码。

{
  "definitionId": {Release definition ID},"artifacts": [
  ],"variables": {
    "test": {
      "value": "99"
    }
  }
}