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

如何在Azure Terraform中用for_each为NSG动态配置目标IP?

解决Terraform NSG动态目标地址配置问题

你的核心问题是误用了dynamic块处理destination_address_prefixes,同时错误地直接引用模块内部资源。下面是修正方案:

第一步:在appserver模块中添加输出

模块内部资源无法直接被外部引用,需要先在../modules/appserver里添加输出,暴露虚拟机的私网IP:

output "private_ips" {
  type = map(string)
  value = {
    for instance_key, nic in azurerm_network_interface.appserver-nic : instance_key => nic.private_ip_address
  }
}

第二步:修改NSG规则配置

destination_address_prefixes本身是列表类型参数,不需要用dynamic块,直接传入模块输出的IP列表即可:

resource "azurerm_network_security_rule" "appserver" {
  name                         = "appserver_in_from_xt"
  priority                     = 670 # 建议用数字类型,避免字符串转义问题
  direction                    = "Inbound"
  access                       = "Allow"
  protocol                     = "Tcp"
  source_port_range            = "*"
  destination_port_range       = "8679"
  source_address_prefixes      = ["IP.IP.IP.IP"]
  # 直接从模块输出中获取所有虚拟机的私网IP列表
  destination_address_prefixes = values(module.appserver.private_ips)
  resource_group_name          = var.resource_group
  network_security_group_name  = var.nsg
}

补充说明

  • dynamic块仅用于生成Terraform资源的嵌套块结构(比如部分资源中的rule或attribute嵌套块),而destination_address_prefixes是顶层列表参数,直接赋值列表即可。
  • 模块内部资源(如azurerm_network_interface.appserver-nic)属于模块私有范围,外部必须通过模块输出才能访问,否则会报错资源不存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:55:24