如何从发布任务修改 Azure DevOps 发布定义变量?

How to modify Azure DevOps release definition variable from a release task?

从 AzureDevOps 发布任务中获取密钥轮换以用于 Azure 存储帐户的最简单方法是什么?目前的计划是在发布后重新生成旧密钥使其失效,并有一个新的密钥可以在下一次部署时使用。但是为了让它工作,我似乎至少需要存储要在发布变量中使用的密钥的名称。

我查看了他的日志记录任务 (https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md),但这只会更改当前版本中的值,不会修改版本定义。

您可以使用 REST API (Definitions - Update) 从发布任务更新发布定义变量的值。

  1. 转到 Agent Phase 和 select Allow Scripts to Access OAuth Token。参见 Use the OAuth token to access the REST API
  2. 授予 Project Collection Build Service (xxx) 帐户编辑​​权限 释放管道权限。 (Select 发布管道 --> ... --> Security --> Edit release definition 设置为 Allow)
  3. 在发布管道中添加 PowerShell 任务
  4. 运行 内联脚本:(在下面的示例中更新变量 v1030 的值)

    $url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
    Write-Host "URL: $url"
    $pipeline = Invoke-RestMethod -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
    
    # Update an existing variable named v1030 to its new value 1035
    $pipeline.variables.v1030.value = "1035"
    
    ####****************** 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 'v1030' is updated to" $updatedef.variables.v1030.value
    write-host "=========================================================="
    

这是一个更简洁、更好的解决方案,它还允许同时触发多个构建。 https://tsuyoshiushio.medium.com/how-to-pass-variables-with-pipeline-trigger-in-azure-pipeline-5771c5f18f91

本质上,您的触发构建会生成工件,您的触发构建会读取这些工件并将其转化为变量。

仍然不是很好,但总比没有好,比 REST 调用设置静态全局变量组要好。