Getting the list of subnet ids created with for_each

Viewed 1004

How may I get the list of subnet ids created with for_each (need at the bottom of my script):

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 = []
}
2 Answers

While using a for is correct, a shorter expression would be to use values function with a splat operator:

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

Since the aws_subnet resource was created with for_each, you could reference the values to create a list using for [1]:

subnet_ids = [for k, v in aws_subnet.private : aws_subnet.private[k].id]

Just tested with the same code you have and terraform plan shows no errors.


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

Related