So I have a query here , I have been researching the newer for_each and the slightly older method count.
For example
resource "aws_subnet" "public" {
count = var.create_igw ? local.availability_zones_count : 0
availability_zone = data.aws_availability_zones.available.names[count.index]
cidr_block = var.pub_cidrspace == "large" ? cidrsubnet(var.vpc_cidr_pub, 8, count.index) : cidrsubnet(var.vpc_cidr_pub, 6, count.index)
map_public_ip_on_launch = true
vpc_id = aws_vpc.main.id
}
Works as expected using the count iterator, I also tried the below method
resource "aws_subnet" "private_subnet" {
for_each = var.size == "large" ? var.subnet_map : var.subnet_map_s
vpc_id = aws_vpc.main.id
cidr_block = var.cidrspace == "large" ? cidrsubnet(var.vpc_cidr, 11, each.key) : cidrsubnet(var.vpc_cidr, 8, each.key)
availability_zone = length(regexall("^[a-z]{2}-[a-z]+-[0-9][a-z]", element(var.availability_zone_list, each.key))) > 0 ? element(var.availability_zone_list, each.key) : null
tags = {
Name = "private_subnet_{each.key}_${element(var.availability_zone_list, each.key)}"
}
}
I am trying to use conditional logic, for both subnet counts and cidr blocks. But really trying to understand if for_each is the preferred method. I grasp the idea behind for_each in that if you remove an entry it won’t behave like count which is indexed linked. I think an idea I use count for is for example ,
resource "aws_vpc_endpoint" "s3" {
count = var.s3_endpoints ? 1 : 0
vpc_id = aws_vpc.main.id
service_name = "com.amazonaws.eu-west-2.s3"
}
resource "aws_vpc_endpoint_route_table_association" "s3_endpoints" {
count = var.s3_endpoints ? 1 : 0
route_table_id = aws_default_route_table.private_route.id
vpc_endpoint_id = aws_vpc_endpoint.s3[0].id
}
Any feedback on the best approach would be great here