Hi guys,
I started a few days ago to play around with TF and I’m struggling with creating an association between 6 subnets and 3 route tables, maybe you can give me a hint:
Vars:
subnets = {
"private-1a" = {
"cidr" = "<cidr>",
"az" = "eu-central-1a",
"nat_gw" = false,
"tag" = "private" },
"private-1b" = {
"cidr" = "<cidr>",
"az" = "eu-central-1b",
"nat_gw" = false,
"tag" = "private" },
"private-1c" = {
"cidr" = "<cidr>",
"az" = "eu-central-1c",
"nat_gw" = false,
"tag" = "private" },
"public-1a" = {
"cidr" = "<cidr>",
"az" = "eu-central-1a",
"nat_gw" = true,
"tag" = "public" },
"public-1b" = {
"cidr" = "<cidr>",
"az" = "eu-central-1b",
"nat_gw" = true,
"tag" = "public" },
"public-1c" = {
"cidr" = "<cidr>",
"az" = "eu-central-1c",
"nat_gw" = true,
"tag" = "public" },
"private-eks-1a" = {
"cidr" = "<cidr>",
"az" = "eu-central-1a",
"nat_gw" = false,
"tag" = "private-eks" },
"private-eks-1b" = {
"cidr" = "<cidr>",
"az" = "eu-central-1b",
"nat_gw" = false,
"tag" = "private-eks" },
"private-eks-1c" = {
"cidr" = "<cidr>",
"az" = "eu-central-1c",
"nat_gw" = false,
"tag" = "private-eks" }
}
Subnets snippet:
resource "aws_subnet" "subnets" {
for_each = var.subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value["cidr"]
availability_zone = each.value["az"]
tags = {
Name = each.key
Type = each.value["tag"]
AZ = each.value["az"] }
}
Route table snippet
resource "aws_route_table" "private_rt" {
for_each = aws_nat_gateway.nat_gateways
vpc_id = aws_vpc.main.id
tags = {
Name = "Private-RT-${each.value.tags["AZ"]}"
AZ = "${each.value.tags["AZ"]}" }
}
NAT GW snippet
resource "aws_nat_gateway" "nat_gateways" {
for_each = { for private_key, private_value in var.subnets:
private_key => private_value if private_value["nat_gw"] }
subnet_id = aws_subnet.subnets[each.key].id
allocation_id = aws_eip.nat_eips[each.key].id
depends_on = [aws_internet_gateway.igw]
tags = {
Name = "NAT-GW-${each.key}"
AZ = "${each.value.az}"
}
}
Out of the 9 created subnets, I want to create a for_each “aws_route_table_association” only for my 6 private subnets which also need to be associated with each of my 3 private route tables, according to its corresponding AZ. So the Route Table in “eu-central-1a” to have associated the subnets from AZ “eu-central-1a” (private & private-eks) and so on.
Any hints are much appreciated, I got my neck stuck in this for a while now…
Cheers!
Lucian.