如何关联由 Terraform 中的循环创建的 NSG 和子网?



这是我用于创建子网和 nsg 的代码,我想在同一脚本中关联 NSG 和子网,但我无法理解如何获取此处生成的子网 ID 和 NSG ID 并在关联资源中使用它们。提前感谢您的帮助!

代码的第一部分用于创建 n 个子网和 NSG 取决于参数

provider "azurerm" {
version = "2.0.0"
features {}
}
resource "azurerm_resource_group" "new-rg" {
name     = var.rg_name
location = "West Europe"
}
resource "azurerm_virtual_network" "new-vnet" {
name                = var.vnet_name
address_space       = ["${var.vnet_address_space}"]
location            = azurerm_resource_group.new-rg.location
resource_group_name = azurerm_resource_group.new-rg.name

}
resource "azurerm_subnet" "test" {
count                = "${length(var.subnet_prefix)}"
name                 = "${element(var.subnet_subnetname, count.index)}"
resource_group_name  = azurerm_resource_group.new-rg.name
virtual_network_name = azurerm_virtual_network.new-vnet.name
address_prefix       = "${element(var.subnet_prefix, count.index)}"
}

resource "azurerm_network_security_group" "new-nsg" {
count        =  "${length(var.subnet_prefix)}"
name                = "${element(var.subnet_subnetname, count.index)}-nsg"
location            = azurerm_resource_group.new-rg.location
resource_group_name = azurerm_resource_group.new-rg.name
}

下面是我必须传递参数才能为正在创建的上述子网和 nsg 创建关联的资源。

代码的第二部分需要使以下代码可用于上述解决方案的 n 个关联。

resource "azurerm_subnet_network_security_group_association" "example" {
subnet_id                 = azurerm_subnet.example.id
network_security_group_id = azurerm_network_security_group.example.id
}

如何使用代码的第二部分关联正在创建的 n 个子网和 nsg,我找不到办法

这似乎是for_each的一个好案例。这是我用于AWS的一些代码(据我所知,相同的逻辑适用(-

(var.nr_azs只是一个整数,使用格式列表是因为for_each只喜欢字符串(

locals {
az_set = toset(formatlist("%s", range(var.nr_azs))) # create a list of numbers and convert them to strings)
}
resource "aws_subnet" "private" {
for_each                = local.az_set
availability_zone       = random_shuffle.az.result[each.key]
cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, each.key)
vpc_id                  = aws_vpc.main.id
map_public_ip_on_launch = false
}
resource "aws_eip" "nat_gw" {
vpc = true
}
resource "aws_nat_gateway" "gw" {
for_each      = aws_subnet.private
allocation_id = aws_eip.nat_gw.id
subnet_id     = each.value.id
}
resource "aws_route_table" "private_egress" {
for_each = aws_nat_gateway.gw
vpc_id   = aws_vpc.main.id
route {
cidr_block     = "0.0.0.0/0"
nat_gateway_id = each.value.id
}
}
resource "aws_route_table_association" "private" {
for_each       = local.az_set
subnet_id      = aws_subnet.private[each.key].id
route_table_id = aws_route_table.private_egress[each.key].id
}

所以我能够解决上面提到的问题,以下代码包含上述问题方案的解决方案。

resource "azurerm_subnet_network_security_group_association" "snet-nsg-association" {
count = length(var.subnet_subnetname)
subnet_id                 = element(azurerm_subnet.multi-snet.*.id, count.index)
network_security_group_id = element(azurerm_network_security_group.new-nsg.*.id, count.index)
}

最新更新