For_each loop -> creating subnets

Hi all, reposting into a new thread, deleting from the other “high jack” thread :wink:

looking for some help on for_each also.

I have a set of subnets that I specify via resource blocks, as everyone can imagine allot of code repetition.

sure it can be done with a for each loop based on az’s but my az’s would be az1, az2, az3 as the v of a k, v pair, where I for example need a, b, or c in my availability_zone tag.

sure someone’s done this… how could I change the 3 blocks into 1 using a for_each config.

G

resource "aws_subnet" "public_1" {
  # The VPC ID.
  vpc_id = aws_vpc.main.id

  # The CIDR block for the subnet.
  cidr_block = "192.168.11.0/24"

  # The AZ for the subnet.
  availability_zone = "af-south-1a"

  # Required for EKS. Instances launched into the subnet should be assigned a public IP address.
  map_public_ip_on_launch = true


 
# A map of tags to assign to the resource.
  tags = merge(
    local.tags,
    {
      Name                                        = "sn_pub-af-south-1a"
      "kubernetes.io/cluster/${var.cluster_name}" = "shared"
      "kubernetes.io/role/elb"                    = 1
    }
  )
}

resource "aws_subnet" "public_2" {
  # The VPC ID
  vpc_id = aws_vpc.main.id

  # The CIDR block for the subnet.
  cidr_block = "192.168.12.0/24"

  # The AZ for the subnet.
  availability_zone = "af-south-1b"

  # Required for EKS. Instances launched into the subnet should be assigned a public IP address.
  map_public_ip_on_launch = true

  # A map of tags to assign to the resource.
  tags = merge(
    local.tags,
    {
      Name                                        = "sn_pub-af-south-1b"
      "kubernetes.io/cluster/${var.cluster_name}" = "shared"
      "kubernetes.io/role/elb"                    = 1
    }
  )
}

resource "aws_subnet" "public_3" {
  # The VPC ID
  vpc_id = aws_vpc.main.id

  # The CIDR block for the subnet.
  cidr_block = "192.168.13.0/24"

  # The AZ for the subnet.
  availability_zone = "af-south-1c"

  # Required for EKS. Instances launched into the subnet should be assigned a public IP address.
  map_public_ip_on_launch = true

  # A map of tags to assign to the resource.
  tags = merge(
    local.tags,
    {
      Name                                        = "sn_pub-af-south-1c",
      "kubernetes.io/cluster/${var.cluster_name}" = "shared"
      "kubernetes.io/role/elb"                    = 1
    }
  )
}