multiple routing tables - adding routes to multiple peering connections to each one of them

368 views
Skip to first unread message

Florin Andrei

unread,
Oct 26, 2016, 8:25:09 PM10/26/16
to Terraform
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
cidrs = "10.205.1.0/24,10.205.2.0/24,10.205.3.0/24" # Creating one private subnet per AZ

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 {
    cidr_block     = "0.0.0.0/0"
    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" {
  vpc_id      = "${aws_vpc.vpc.id}"
  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.
Reply all
Reply to author
Forward
0 new messages