You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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时,跳过该规则的创建

如果你使用的Terraform版本低于0.13,也可以用for_each写法替代if参数:

dynamic "security_rule" {
  for_each = count.index == 0 ? [1] : []
  content {
    # rule2的配置内容同上
  }
}

内容的提问来源于stack exchange,提问作者Cookies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:10:20