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

Terraform Azurerm如何输出应用网关公网IP作为NSG入站规则变量

Terraform引用应用网关公网IP配置NSG规则的实现方法

完全可以实现,你不需要额外手动提取IP地址,Terraform天然支持同配置内的资源属性引用,会自动处理资源创建的依赖顺序,确保IP地址生成后再更新NSG规则。

常用实现场景

场景1:公网IP与NSG在同一根模块下声明

直接在NSG入站规则的source_address_prefix字段引用公网IP资源的ip_address属性即可,参考代码示例:

# 应用网关绑定的公网IP资源
resource "azurerm_public_ip" "agw_pip" {
  name                = "agw-public-ip"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  allocation_method   = "Static"
  sku                 = "Standard"
}

# 应用网关资源(省略其他非必要配置)
resource "azurerm_application_gateway" "example" {
  name                = "business-agw"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name

  frontend_ip_configuration {
    name                 = "public-frontend"
    public_ip_address_id = azurerm_public_ip.agw_pip.id
  }
}

# NSG入站规则,直接引用公网IP地址
resource "azurerm_network_security_rule" "allow_agw_access" {
  name                        = "Allow-All-From-AGW"
  priority                    = 100
  direction                   = "Inbound"
  access                      = "Allow"
  protocol                    = "*"
  source_port_range           = "*"
  destination_port_range      = "*"
  # 直接引用公网IP资源的地址属性
  source_address_prefix       = azurerm_public_ip.agw_pip.ip_address
  destination_address_prefix  = "VirtualNetwork"
  resource_group_name         = azurerm_resource_group.example.name
  network_security_group_name = azurerm_network_security_group.backend_nsg.name
}

场景2:公网IP与NSG分属不同模块

你可以在应用网关/公网IP所在的子模块中通过output导出IP地址,再在NSG所在模块引入该值即可:

  1. 应用网关子模块的outputs.tf配置:
output "agw_public_ip_address" {
  value       = azurerm_public_ip.agw_pip.ip_address
  description = "应用网关绑定的公网IP地址"
}
  1. 根模块调用时传递参数:
module "agw" {
  source = "./modules/application-gateway"
  # 其他参数省略
}

module "backend_nsg" {
  source = "./modules/nsg"
  # 引用AGW模块导出的IP地址作为允许的入站源
  allowed_agw_ip = module.agw.agw_public_ip_address
  # 其他参数省略
}

注意事项

  • 应用网关的公网IP必须设置allocation_method = "Static",避免IP动态变更导致NSG规则失效
  • 不需要提前将IP设置为Terraform变量,直接资源引用即可,Terraform会自动维护依赖关系,避免出现先创建NSG规则再生成IP的顺序错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:06:05