Is there a way to create multiple AWS VPCs and multiple subnets for each VPC using the same terraform script?

318 Views Asked by At

Terraform novice here. I would like to create a scaled environment on AWS using terraform cli. My input variables are N_vpc (count), region, aws_profile, M_subnet_per_vpc. Is it possible to use count and for_each meta arguments to write a terraform script that creates N VPCs and M subnets in each of those VPCs within a single terraform custom module?

I tried to use count meta argument in the VPC resource block to create N VPCs in a given region and then tried to create a subnet resource block with count = M and for_each = vpc[*].id but realized that count and for_each meta arguments cannot be used in the same resource block.

# -------------------------------------------------------------------
# CREATE THE VPC, and Subnets
# N VPC
# M SUBNETS PER VPC
# -------------------------------------------------------------------

resource "aws_vpc" "customer_vpc" {
  count      = var.vpc_count
  cidr_block = var.vpc_cidr
  tags = {
    Name = "vpc-${random_id.deployment_id.hex}"
  }
}

resource "aws_subnet" "customer_subnet" {
  count    = var.subnet_count # --> count and for_each cannot be used in the same block
  for_each = aws_vpc.customer_vpc.id
  vpc_id   = each.value
  tags = {
    Name = "subnet-${random_id.deployment_id.hex}-${count.index}"
  }
}
0

There are 0 best solutions below