获取使用 for_each 创建的子网 ID 列表

Getting the list of subnet ids created with for_each

如何获取使用 for_each 创建的子网 ID 列表(需要在我的脚本底部):

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

provider "aws" {
  region = "eu-west-1"
}

data "aws_availability_zones" "azs" {
  state = "available"
}

locals {
  az_names = data.aws_availability_zones.azs.names
}

variable "vpc_cidr" {
  default = "10.0.0.0/16"
}

resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
}

resource "aws_subnet" "private" {
  for_each                = {for idx, az_name in local.az_names: idx => az_name}
  vpc_id                  = aws_vpc.main.id
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.key)
  availability_zone       = local.az_names[each.key]
}

module "eks" {
  source = "terraform-aws-modules/eks/aws"

  # I need to get the list of subnet ids (aws_subnet.private) here
  subnet_ids = []
}

由于 aws_subnet 资源是使用 for_each 创建的,您可以引用这些值以使用 for [1]:

创建列表
subnet_ids = [for k, v in aws_subnet.private : aws_subnet.private[k].id]

刚刚使用与您相同的代码进行测试,terraform plan 未显示任何错误。


[1] https://www.terraform.io/language/expressions/for#for-expressions

虽然使用 for 是正确的,但更短的表达式是使用 values function with a splat 运算符:

subnet_ids = values(aws_subnet.private)[*].id