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

Terraform创建Azure NSG动态规则时遭遇DuplicateResourceName错误

解决Azure NSG动态安全规则的重复资源错误

问题根源

你遇到的错误是因为动态生成的两条安全规则使用了完全相同的名称("01-tf-SG"),而Azure网络安全组(NSG)要求所有子资源(安全规则)的名称必须唯一。另外代码里还有个隐藏问题:两条规则的priority都设为100,NSG规则的优先级也必须唯一,后续执行同样会触发错误。

修正后的代码

把安全规则的名称和优先级都改成动态关联的,确保每个规则唯一:

resource "azurerm_network_security_group" "linux_vm_nsg" {
  depends_on = [azurerm_resource_group.main]
  name                = "01-tf-SG"
  location            = azurerm_resource_group.main.location
  resource_group_name = azurerm_resource_group.main.name

  dynamic "security_rule" {
    for_each = toset(["Icmp", "Tcp"])
    content {
      # 规则名称结合协议名,确保唯一
      name                       = "Allow-${security_rule.value}-Between-VMs"
      # 优先级按协议索引动态分配,避免重复
      priority                   = 100 + index(toset(["Icmp", "Tcp"]), security_rule.value)
      direction                  = "Inbound"
      access                     = "Allow"
      protocol                   = security_rule.value
      source_port_range          = "*"
      destination_port_range     = "*"
      source_address_prefix      = "172.16.25.10/32"
      destination_address_prefix = "10.0.1.10/32"
    }
  }
}

关键修改点

  • 规则名称:使用Allow-${security_rule.value}-Between-VMs,生成的规则名会是Allow-Icmp-Between-VMs和Allow-Tcp-Between-VMs,确保唯一。
  • 优先级:通过index函数给每个规则分配递增的优先级(100和101),避免优先级冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:15:59