Good day all!
We are trying to achieve the following requirement using Terraform.
We need to have multiple public subnets with different Tag names across three AZs as below.
What is the best way to achieve this using terraform modules.
We currently have an approach of using separate resources defined for each subnet groups(subnet_public_group1, subnet_public_group2, subnet_public_group3) in Terraform modules.
Is there a better way to achieve this using the existing terraform modules(aws_subnet resource for public network)?
Also, we are going to associate single route table to all these subnets created above.
Is this using your own terraform module, a third party open source module, or our module? If you are using any third party module, it is likely that this level of fine grained tagging is not supported. Our module for sure does not support this level of custom tags per subnet based on the AZ.
However, if you are using your own module, then you can use for_each on the resource with for expressions to control the tags based on the AZs. For example, if you assume that you had the list of availability zones you would like to create (e.g local.all_availability_zones), you can do something like the following:
resource "aws_subnet" "public_subnets" {
for_each = toset(local.all_availability_zones)
# other args omitted for brevity
tags = {
for group in ["group1", "group2", "group3"]:
"subnet_public_${group}_${each.key}" => ""
}
}
You can read more about for_each on resources and for expressions in the official docs: