Using Terraform for_each to create subnets in AWS VPC

An extended explanation of the differences between for_each, for and count can be find on the link below https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9

The two main drawbacks of using count are :
- Can’t be used to loop over inline blocks
- Difficult to remove entry from a list because it changes the index and those Terraform may want to destroy the resource because it has a different index

Below is an example of the variables used to create subnets within AWS VPCs and the main file with the for_each. The variables contain a map of subnets maps with cidr and az (availability zone) attributes. The for_each loop over the map of subnets maps to create the subnets.

variables.tf

variable "tag_name" {
   default = "main-vpc"
}

variable "vpc-cidr" {
   default = "10.0.0.0/16"
}

variable "basename" {
   description = "Prefix used for all resources names"
   default = "nbo"
}

#map of maps for create subnets
variable "prefix" {
   type = map
   default = {
      sub-1 = {
         az = "use2-az1"
         cidr = "10.0.198.0/24"
      }
      sub-2 = {
         az = "use2-az2"
         cidr = "10.0.199.0/24"
      }
      sub-3 = {
         az = "use2-az3"
         cidr = "10.0.200.0/24"
      }
   }
}

main.tf

resource "aws_vpc" "main-vpc" {
  cidr_block = var.vpc-cidr

  tags = {
    Name = var.tag_name
  }
}

resource "aws_subnet" "main-subnet" {
  for_each = var.prefix
 
  availability_zone_id = each.value["az"]
  cidr_block = each.value["cidr"]
  vpc_id     = aws_vpc.main-vpc.id

  tags = {
    Name = "${var.basename}-subnet-${each.key}"
  }
}

You can find the output of the terraform plan/apply, the terraform.state and the others tf files in the below links.

https://github.com/netmemo/tf-for-each-exemple