Skip to content

Instantly share code, notes, and snippets.

@huevos-y-bacon
Last active February 10, 2025 16:46
Show Gist options
  • Save huevos-y-bacon/dd7ffb70cbbe3fff8d8a51e4e15e4da5 to your computer and use it in GitHub Desktop.
Save huevos-y-bacon/dd7ffb70cbbe3fff8d8a51e4e15e4da5 to your computer and use it in GitHub Desktop.
Terraform - Create peering connection between two AWS VPCs in the same AWS account and region and create route entries in all route tables in both VPCs to route traffic between them.
# Create peering copnnection between two AWS VPCs in the same AWS account and region and create route entries in all route tables in both VPCs to route traffic between them.
# variables.tf
variable "vpc_id_left" {
description = "vpc id left"
type = string
}
variable "vpc_id_right" {
description = "vpc id right"
type = string
}
# main.tf
# Get vpc details "left"
data "aws_vpc" "vpc_left" {
id = var.vpc_id_left
}
# Get vpc details "right"
data "aws_vpc" "vpc_right" {
id = var.vpc_id_right
}
locals {
cidr_left = data.aws_vpc.vpc_left.cidr_block
cidr_right = data.aws_vpc.vpc_right.cidr_block
vpc_name_left_pre = data.aws_vpc.vpc_left.tags.Name
vpc_name_right_pre = data.aws_vpc.vpc_right.tags.Name
# Replace spaces with hyphens
vpc_name_left = replace(local.vpc_name_left_pre, " ", "-")
vpc_name_right = replace(local.vpc_name_right_pre, " ", "-")
}
# Create and accept peering connection
resource "aws_vpc_peering_connection" "peering" {
vpc_id = var.vpc_id_left
peer_vpc_id = var.vpc_id_right
tags = {
Name = "${local.vpc_name_left}-TO-${local.vpc_name_right}"
}
}
resource "aws_vpc_peering_connection_accepter" "accepter" {
vpc_peering_connection_id = aws_vpc_peering_connection.peering.id
auto_accept = true
}
# Get route tables "left"
data "aws_route_tables" "route_tables_left" {
vpc_id = var.vpc_id_left
}
# Get route tables "right"
data "aws_route_tables" "route_tables_right" {
vpc_id = var.vpc_id_right
}
# Create route entries in all route tables in "left" side VPC
resource "aws_route" "route_right_to_left" {
for_each = toset(data.aws_route_tables.route_tables_right.ids)
route_table_id = each.value
destination_cidr_block = local.cidr_left
vpc_peering_connection_id = aws_vpc_peering_connection.peering.id
}
# Create route entries in all route tables in "right" side VPC
resource "aws_route" "route_left_to_right" {
for_each = toset(data.aws_route_tables.route_tables_left.ids)
route_table_id = each.value
destination_cidr_block = local.cidr_right
vpc_peering_connection_id = aws_vpc_peering_connection.peering.id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment