ARM 模板:有条件地添加到数组

问题描述 投票:0回答:4

对于我的 Azure ARM 模板,我想有条件地添加额外的 NSG 规则。如果参数为 true,则将额外的规则附加到“securityRules”数组中。我如何有效地解决这个问题?我无法对嵌套对象使用“条件”属性。创建两个资源似乎很笨拙。

azure azure-resource-manager azure-rm-template
4个回答
8
投票

根据条件,您希望向现有 json 数组添加附加(字符串)值。这可以通过 concat 函数来完成。为了连接数组和字符串值,字符串值也需要转换为数组。当条件为真时,可以连接两个数组。当条件为 false 时,您可以将现有字符串与空数组连接起来。

"[concat( parameters('existingArray'), if( parameters('condition'), array('Cc'), variables('emptyArray')) )]"

假设原始数组为:["Aa", "Bb"]

  • 当条件为真时,将得到:["Aa", "Bb", "Cc"]
  • 当条件为假时,将导致:["Aa", "Bb"]

0
投票

想太多了。允许将变量定义为数组。定义两个变量,每个变量具有不同的规则集。根据参数“allowInternetAccess”将“if”函数应用于 securityRules。


0
投票

我的解决方案:

在我的参数文件(JSON)中操作定义如下(这不是完整的参数文件)

"Operation1": {
    "name": "operation-1",
    ...
},
"Operation2": {}

二头肌操作处理:

var allOperations = [
    apiManagement.api.operations.Operation1
    apiManagement.api.operations.Operation2
]

var usedOperations = [
    apiManagement.api.operations.Operation1
    empty(apiManagement.api.operations.Operation2) ? null : apiManagement.api.operations.Operation2
]

var operations = intersection(allOperations, usedOperations)

module api_operation './shared/api-operation.bicep' = [for operation in operations: {
  name: '${apiManagement.api.name}-${operation.name}'
  params: {
    apiManagement: apiManagement
    operation: operation
  } 
}]

0
投票

假设您有两组 NSG 规则变量

defaultNSGRules
additionalNSGRules
,它们都是规则数组。

为了能够添加附加规则,您可以检查条件,如果满足,则连接附加规则,否则为空数组。为此,您需要做两件事:

  1. 一个条件。这可以是您检查特定值的变量或参数。为了简单起见,我们假设它是一个
    bool
    ,名称为
    shuoldUseAdditionalNSGRules
    。但您可以检查字符串值等。
  2. 一个空数组变量定义如下:
    "emptyArray": []
    。这是必要的,因为 ARM 模板不喜欢在 concat 调用的 if 语句中使用
    []

然后当 bool 设置为 true 时,您可以使用它来附加附加规则:

"securityRules": "[concat(variables('defaultNSGRules'), if (parameters('shuoldUseAdditionalNSGRules'), variables('additionalNSGRules'), variables('emptyArray')))]"
© www.soinside.com 2019 - 2024. All rights reserved.