Using interpolation, I create multiple private subnets, one for each availability zone:
######################################
azs = "us-west-2a,us-west-2b,us-west-2c" # AZs are region specific
resource "aws_subnet" "private" {
vpc_id = "${var.vpc_id}"
cidr_block = "${element(split(",", var.cidrs), count.index)}"
availability_zone = "${element(split(",", var.azs), count.index)}"
count = "${length(split(",", var.cidrs))}"
tags { Name = "${var.name}-${element(split(",", var.azs), count.index)}-private" } lifecycle { create_before_destroy = true }
}
resource "aws_route_table" "private" {
vpc_id = "${var.vpc_id}"
count = "${length(split(",", var.cidrs))}"
route {
nat_gateway_id = "${element(split(",", var.nat_gateway_ids), count.index)}"
}
tags { Name = "${var.name}-${element(split(",", var.azs), count.index)}-private" } lifecycle { create_before_destroy = true }
}
resource "aws_route_table_association" "private" {
count = "${length(split(",", var.cidrs))}"
subnet_id = "${element(aws_subnet.private.*.id, count.index)}"
route_table_id = "${element(aws_route_table.private.*.id, count.index)}"
lifecycle { create_before_destroy = true }
}
################################################
Also using interpolation, I create multiple peering connections originating from this VPC:
################################################
variable "peer_vpc_ids" { ........ }
variable "peer_vpc_names" { ........ }
resource "aws_vpc_peering_connection" "peering" {
peer_vpc_id = "${element(split(",", var.peer_vpc_ids), count.index)}"
count = "${length(split(",", var.peer_vpc_ids))}"
auto_accept = true
tags {
Name = "${var.name} / ${element(split(",", var.peer_vpc_names), count.index)}" }
}
#################################################
But now, on each route table, I need to add routes to each peering connection. Let's say, I have 3 AZs (3 private subnets, 3 route tables), and 4 peering connections, that's a total of 12 routes that need to be distributed to those route tables.
How do I loop over both route tables and peering connections to achieve this?
I really want to keep using interpolation. This would allow to scale up/down resources by simply adjusting lists in terraform.tfvars.