🟢 VPC Peering

This architecture shows two VPCs connected via VPC Peering. Each VPC has its own subnet and EC2 instance. Peering allows communication between the two VPCs over private IPs.
provider "aws" {
region = "us-east-1"
}
# VPC A
resource "aws_vpc" "vpc_a" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "subnet_a" {
vpc_id = aws_vpc.vpc_a.id
cidr_block = "10.0.1.0/24"
}
# VPC B
resource "aws_vpc" "vpc_b" {
cidr_block = "10.1.0.0/16"
}
resource "aws_subnet" "subnet_b" {
vpc_id = aws_vpc.vpc_b.id
cidr_block = "10.1.1.0/24"
}
# VPC Peering
resource "aws_vpc_peering_connection" "peer" {
vpc_id = aws_vpc.vpc_a.id
peer_vpc_id = aws_vpc.vpc_b.id
auto_accept = true
}
# Routing for VPC A
resource "aws_route_table" "rt_a" {
vpc_id = aws_vpc.vpc_a.id
route {
cidr_block = aws_vpc.vpc_b.cidr_block
vpc_peering_connection_id = aws_vpc_peering_connection.peer.id
}
}
resource "aws_route_table_association" "rta_a" {
subnet_id = aws_subnet.subnet_a.id
route_table_id = aws_route_table.rt_a.id
}
# Routing for VPC B
resource "aws_route_table" "rt_b" {
vpc_id = aws_vpc.vpc_b.id
route {
cidr_block = aws_vpc.vpc_a.cidr_block
vpc_peering_connection_id = aws_vpc_peering_connection.peer.id
}
}
resource "aws_route_table_association" "rta_b" {
subnet_id = aws_subnet.subnet_b.id
route_table_id = aws_route_table.rt_b.id
}