在Terraform中使用条件表达式实现NSG规则差异化配置
Terraform中实现NSG规则的条件配置方案
Terraform本身没有原生的if/else语句,但可以通过**条件表达式(三元运算符)**结合for_each迭代实现分支逻辑,满足你针对特定NSG调整端口的需求。
核心实现思路
通过判断当前NSG的名称是否为目标特定值,动态选择对应的端口配置:
- 普通NSG使用默认端口(RDP:3389、SSH:22)
nsg-restricted-jdmsg-chn使用自定义端口(RDP:33091、SSH:26)
修改后的代码示例
假设local.nsgrules的键对应NSG的完整名称(即"nsg-restricted-${var.cfg.name}"),直接在资源中添加条件判断:
resource "azurerm_network_security_rule" "testrules" { for_each = local.nsgrules resource_group_name = var.jdgrp.rg.name location = var.jdgrp.rg.location name = each.key security_rule { name = "rdp" direction = "Inbound" access = "Allow" priority = "100" protocol = "Tcp" source_port_range = "*" destination_port_range = each.key == "nsg-restricted-jdmsg-chn" ? 33091 : 3389 source_address_prefix = "VirtualNetwork" destination_address_prefix = "192.168.2.0/24" } security_rule { name = "ssh" direction = "Inbound" access = "Allow" priority = "101" protocol = "Tcp" source_port_range = "*" destination_port_range = each.key == "nsg-restricted-jdmsg-chn" ? "26" : "22" source_address_prefix = "VirtualNetwork" destination_address_prefix = "192.168.2.0/24" } }
适配模块配置的优化方案
如果NSG名称是通过var.cfg.name拼接而来,可以直接判断var.cfg.name的值,避免字符串拼接冗余:
resource "azurerm_network_security_rule" "testrules" { for_each = local.nsgrules resource_group_name = var.jdgrp.rg.name location = var.jdgrp.rg.location name = "nsg-restricted-${var.cfg.name}" security_rule { name = "rdp" direction = "Inbound" access = "Allow" priority = "100" protocol = "Tcp" source_port_range = "*" destination_port_range = var.cfg.name == "jdmsg-chn" ? 33091 : 3389 source_address_prefix = "VirtualNetwork" destination_address_prefix = "192.168.2.0/24" } security_rule { name = "ssh" direction = "Inbound" access = "Allow" priority = "101" protocol = "Tcp" source_port_range = "*" destination_port_range = var.cfg.name == "jdmsg-chn" ? "26" : "22" source_address_prefix = "VirtualNetwork" destination_address_prefix = "192.168.2.0/24" } }
逻辑说明
Terraform条件表达式语法为条件 ? 满足条件时的值 : 不满足条件时的值,可直接嵌入资源属性中实现分支逻辑。结合for_each对每个NSG实例迭代,既能批量配置规则,又能对特定实例做差异化调整。
内容的提问来源于stack exchange,提问作者Maryo David
相关产品推荐
相关产品推荐

