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

Azure中使用Terraform创建多协议网络安全规则遇类型错误该如何解决?

如何在Terraform的Azure网络安全组规则中同时允许ICMP和TCP协议

Azure网络安全组(NSG)的单条安全规则不支持同时指定多个协议,这是Azure服务本身的限制,并非Terraform的问题。你遇到的「属性值类型」错误,是因为azurerm_network_security_group的security_rule块中,protocol字段仅接受单个字符串值,不能传入数组。

解决方案1:拆分两条独立的安全规则

针对ICMP和TCP分别创建规则,确保每条规则的priority(优先级)唯一:

resource "azurerm_network_security_group" "example" {
  name                = "01-tf-SG"
  location            = azurerm_resource_group.main.location
  resource_group_name = azurerm_resource_group.main.name

  # 允许ICMP协议的规则
  security_rule {
    name                       = "test123-icmp"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Icmp"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "172.16.25.10/32"
    destination_address_prefix = "10.0.1.10/32"
  }

  # 允许TCP协议的规则
  security_rule {
    name                       = "test123-tcp"
    priority                   = 101
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "172.16.25.10/32"
    destination_address_prefix = "10.0.1.10/32"
  }
}

解决方案2:允许所有协议(不推荐)

如果业务场景允许开放所有协议,可以将protocol设置为"*",这样会自动包含ICMP、TCP及其他所有协议,但会降低安全性,仅建议在测试环境使用:

resource "azurerm_network_security_group" "example" {
  name                = "01-tf-SG"
  location            = azurerm_resource_group.main.location
  resource_group_name = azurerm_resource_group.main.name

  security_rule {
    name                       = "test123-all-protocols"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "172.16.25.10/32"
    destination_address_prefix = "10.0.1.10/32"
  }
}

注:Terraform官方文档未提供多协议示例,本质是因为Azure API不支持单条NSG规则关联多个协议,因此Terraform provider也未实现该功能。

内容的提问来源于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.12 03:55:27