Terraform配置:为首个Network Security Group添加专属安全规则
条件化配置NSG安全规则:仅为第一个NSG添加rule2
要实现仅给第一个NSG(索引0)添加rule2,你可以利用Terraform的**动态块(dynamic block)**结合count.index做条件判断——因为嵌套的security_rule块无法直接使用count参数。
修改后的完整代码
resource "azurerm_network_security_group" "terra_nsg" { count = length(local.nsg_names) name = element(local.nsg_names, count.index) location = var.azure_region resource_group_name = azurerm_resource_group.terra_rgo.name # 所有NSG均添加rule1 security_rule { name = "rule1" direction = "Inbound" access = "Allow" priority = 100 protocol = "Tcp" source_port_range = "*" destination_port_range = 3389 source_address_prefix = "1.2.3.4" destination_address_prefix = "*" } # 仅为索引0的NSG添加rule2 dynamic "security_rule" { if = count.index == 0 content { name = "rule2" priority = 110 direction = "Inbound" access = "Allow" protocol = "Tcp" source_port_range = "*" destination_port_range = "443" source_address_prefix = "*" destination_address_prefix = "*" } } }
核心逻辑说明
dynamic "security_rule"用于动态生成嵌套的安全规则块if = count.index == 0是关键条件判断:- 当当前NSG的索引为0(对应
nsg01)时,会渲染这个安全规则块 - 索引不为0时,跳过该规则的创建
- 当当前NSG的索引为0(对应
如果你使用的Terraform版本低于0.13,也可以用for_each写法替代if参数:
dynamic "security_rule" { for_each = count.index == 0 ? [1] : [] content { # rule2的配置内容同上 } }
内容的提问来源于stack exchange,提问作者Cookies
相关产品推荐
相关产品推荐

