Azure Terraform模块化实现NSG与子网关联的配置问题
解决Terraform Azure NSG与子网模块化关联的问题
要实现NSG模块和子网模块的关联,核心是通过模块输出-变量传递的方式把子网ID传入NSG模块,具体步骤如下:
1. 配置子网模块的输出(subnet/output.tf)
先确保子网模块能对外导出子网的ID:
output "subnet_id" { type = string description = "The ID of the created subnet" value = azurerm_subnet.this.id }
注:这里假设子网模块main.tf中定义的子网资源是azurerm_subnet.this,可根据你实际的资源名称调整。
2. 在根模块调用子网模块并获取输出
在根目录main.tf中调用子网模块,保存它的输出值:
module "my_subnet" { source = "./modules/subnet" # 传入子网模块所需变量,示例如下 virtual_network_id = azurerm_virtual_network.my_vnet.id subnet_name = "example-subnet" address_prefixes = ["10.0.1.0/24"] }
3. 配置NSG模块的变量(networksecuritygroup/variable.tf)
在NSG模块中定义变量,接收外部传入的子网ID:
variable "subnet_id" { type = string description = "The ID of the subnet to associate with this NSG" } # NSG其他必填变量示例 variable "resource_group_name" { type = string description = "Name of the resource group" } variable "nsg_name" { type = string description = "Name of the NSG" }
4. 在NSG模块中实现关联(networksecuritygroup/main.tf)
先创建NSG资源,再用传入的var.subnet_id完成关联:
# 创建NSG资源 resource "azurerm_network_security_group" "this" { name = var.nsg_name location = azurerm_resource_group.this.location # 可替换为你定义的location变量 resource_group_name = var.resource_group_name # 按需添加NSG规则示例 security_rule { name = "allow-ssh" priority = 100 direction = "Inbound" access = "Allow" protocol = "Tcp" source_port_range = "*" destination_port_range = "22" source_address_prefix = "*" destination_address_prefix = "*" } } # 关联NSG与子网 resource "azurerm_subnet_network_security_group_association" "this" { subnet_id = var.subnet_id network_security_group_id = azurerm_network_security_group.this.id }
5. 在根模块调用NSG模块并传递子网ID
在根目录main.tf中调用NSG模块,将子网模块输出的ID传入:
module "my_nsg" { source = "./modules/networksecuritygroup" resource_group_name = azurerm_resource_group.my_rg.name nsg_name = "example-nsg" subnet_id = module.my_subnet.subnet_id # 关键:传递子网模块的输出ID }
关键说明
你之前尝试的var.subnetname.id错误在于,NSG模块需要的是子网ID字符串,而非子网对象。通过子网模块输出ID,再传递给NSG模块的字符串变量,直接使用var.subnet_id即可,无需额外加.id。
内容的提问来源于stack exchange,提问作者soldier
相关产品推荐
相关产品推荐

