我已经有一个现有的脚本,用于在 Azure DevOps 中创建发布管道。我希望对其进行改进以创建可在发布时设置的管道变量。
我尝试将以下内容添加到我现有的脚本中:
#Params section
$pipelineVariables =@{
"Variable1" = "Value1"
"Variable2" = "Value2"
}
#Body section
$body = @{
"name" = $releaseName
"variableGroups" = @($variableGroupID)
"variables" = @(
foreach ($varName in $pipelineVariables.Keys) {
@{
"name" = $varName
"value" = $pipelineVariables[$varName]
"isSecret" = $false
}
}
)
}
此脚本已成功执行,但我在“管道变量”部分中没有看到变量,而且我还需要找出一种方法来选中“运行时可设置”选项。
我们可以调用release Definitions - Update REST API先获取响应体,然后将变量块添加到json体中以创建变量。
例如,如果发布管道中已经存在一个现有变量,那么您可以引用以下 PowerShell 脚本来创建/添加新的
Settable at runtime
发布变量。
Param(
[string]$orgurl = "https://vsrm.dev.azure.com/{org}",
[string]$project = "0508-t",
[string]$releaseDefid = "18",
[string]$user = "",
[string]$token = "PAT-Here"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$baseUri = "$orgurl/$project/_apis/Release/definitions/$($releaseDefid)?api-version=7.0"
$releasedef = Invoke-RestMethod -Method Get -Uri $baseUri -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
#Add a block to a json body
$variablename = "Variable3"
$variablevalue ='{"value": "20", "allowOverride": true}'
$releasedef.variables | Add-Member -Type NoteProperty -Name $variablename -Value (Convertfrom-Json $variablevalue) -Force
#****************** update the modified object **************************
$json = @($releasedef) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $baseUri -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
write-host "=========================================================="
Write-host "The Variable $variablename is created."
write-host "=========================================================="
如果没有现有变量,那么您必须添加一个新的完整
variables
块,其中包含要在其中创建的所有变量。您可以根据您的需求调整和优化脚本。