subnet_id terraform 中多个子网的值

subnet_id value for multiple subnet in terraform

varaible.tf


variable "subnets" {
  type = map(any)
  default = {
    subnet1 = {
      "key"              = "subnet_1"
      "address_prefixes" = ["10.20.30.0/24"]
    }

    subnet2 = {
      "key"              = "subnet_2"
      "address_prefixes" = ["10.20.40.0/24"]
    }

  }
}



main.tf


resource "azurerm_subnet" "subnet1" {
  for_each             = var.subnets
  name                 = each.value["key"]
  resource_group_name  = azurerm_resource_group.azureDevops.name
  virtual_network_name = azurerm_virtual_network.vnet1.name
  address_prefixes     = each.value["address_prefixes"]
}

想要将安全组附加到我的所有子网。它不止一个值。它的投掷错误 subnet_id.

resource "azurerm_subnet_network_security_group_association" "example" {

subnet_id = [for subnet in azurerm_subnet.subnet1 : subnet.id]
network_security_group_id = azurerm_network_security_group.tamopsnsg.id
}

其 subnet_id 值的抛出错误。如何连接到多个子网?

您在这里尝试实现的是 chaining for_each between resources 的典型 use-case,其中由一个 for_each 资源创建的地图值成为另一个资源的 for_each 值下游资源。

例如:

variable "subnets" {
  # NOTE: Better to specify an exact type constraint
  # so that Terraform can give you better feedback
  # when you make a mistake elsewhere in the
  # configuration.
  type = map(object({
    key              = string
    address_prefixes = set(string)
  }))
}

resource "azurerm_subnet" "example" {
  for_each = var.subnets

  name                 = each.value.key
  resource_group_name  = azurerm_resource_group.azure_devops.name
  virtual_network_name = azurerm_virtual_network.vnet1.name
  address_prefixes     = each.value.address_prefixes
}

resource "azurerm_subnet_network_security_group_association" "example" {
  for_each = azurerm_subnet.example

  subnet_id                 = each.value.id
  network_security_group_id = azurerm_network_security_group.tamopsnsg.id
}

这取决于 azurerm_subnet.subnet1 是一个事实,因为该资源使用 for_each,一个从实例键到代表每个子网的对象的映射。由于 for_each 的工作方式,实例密钥将与 var.subnets 的密钥完全匹配,因此对于您声明的每个子网,您还将声明相应的安全组关联:

  • azurerm_subnet.example["subnet1"]对应于azurerm_subnet_network_security_group_association.example["subnet1"]
  • azurerm_subnet.example["subnet2"]对应于azurerm_subnet_network_security_group_association.example["subnet2"]

each.valueassociation 资源块中将是表示您声明的子网的对象而不是 var.subnets 的元素,因此您可以访问each.value.id获取对应子网的远程对象ID。