无法使用 powershell 脚本中的 az cli 部署具有参数的 Azure ARM



尝试使用 PS 脚本中的参数进行简单部署:

$prefix = "xxx"
$location = "switzerlandnorth"
az deployment group create `
--name  $timestamp  `
--resource-group $resourceGroupName `
--mode incremental `
--verbose `
--template-file .srcopsscriptsarm.json `
--parameters "{ `"location`": { `"value`": `"$location`" },`"projectPrefix`": { `"value`": `"$prefix`" } }"

响应错误:

Unable to parse parameter: { location: { value: switzerlandnorth }, projectPrefix: { value: xxx } }

从 PS1 脚本运行

正如我们在错误中看到的那样,它无法解析参数。将参数传递给az deployment group create命令的正确方法是:

az deployment group create `
--name  $timestamp  `
--resource-group $resourceGroupName `
--mode "incremental" `
--verbose `
--template-file ".srcopsscriptsarm.json" `
--parameters '{ "location": { "value": "switzerlandnorth" },"projectPrefix": { "value": "xxx" } }' 

更新:

如果要在参数中传递PowerShell变量,可以执行以下操作 -

$location = "switzerlandnorth"
$projectPrefix = "xxx"
$params = '{ "location": { "value": " ' + $location + '" },"projectPrefix": { "value": "' + $projectprefix + '" } }' 
az deployment group create `
--name  $timestamp  `
--resource-group $resourceGroupName `
--mode "incremental" `
--verbose `
--template-file ".srcopsscriptsarm.json" `
--parameters $params

希望这有帮助!

您可以想到的另一种方法是在 PS 中使用对象/哈希表,然后转换为 JSON,例如

$param = @{
location = "switzerlandnorth"
prefix = "foo"
}
$paramJSON = ($param | ConvertTo-Json -Depth 30 -Compress).Replace('"', '"') # escape quotes in order to pass the command via pwsh.exe
az deployment group create -g $resourceGroupName--template-file "azuredeploy.json" -p $paramJson

这是一个类似的例子: https://gist.github.com/bmoore-msft/d578c815f319af7eb20d9d97df9bf657

我会在这里投入我的两分钱,因为以前的答案对我们在这里实际做的事情很渺茫。简而言之,az deployment group create命令希望--parameters参数是双序列化的 JSON 字符串 {scoff}。为了创建一个可以由az deployment group create处理的值,我们需要做这样的事情:

$stupidlyFormattedParam = @{
someAppSetting1 = @{ value = "setting 1" }
someAppSetting2 = @{ value = "setting 2" }
} | ConvertTo-Json -Compress -Depth 10 | ConvertTo-Json
az deployment group create --name someName--resource-group someGroup --parameters $stupidlyFormattedParam --template-file .someFile.json

最新更新