Terraform Vpc Peering

Posted by Zak's Notes on Thursday, February 11, 2021

Here’s an example Terraform configuration for creating two VPCs and automatically accepting VPC peering between them:

provider "aws" {
  region = "us-west-2"
}

resource "aws_vpc" "vpc_a" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "VPC A"
  }
}

resource "aws_vpc" "vpc_b" {
  cidr_block = "10.1.0.0/16"

  tags = {
    Name = "VPC B"
  }
}

resource "aws_vpc_peering_connection" "peer_a_b" {
  vpc_id = aws_vpc.vpc_a.id
  peer_vpc_id = aws_vpc.vpc_b.id

  auto_accept = true

  tags = {
    Name = "Peer A to B"
  }
}

resource "aws_vpc_peering_connection_accepter" "peer_b_a" {
  vpc_peering_connection_id = aws_vpc_peering_connection.peer_a_b.id
  auto_accept = true
}

This Terraform configuration uses the AWS provider to create two VPCs, named “VPC A” and “VPC B”. A VPC peering connection is then created between these two VPCs, with the auto_accept argument set to true. This means that the peering connection will automatically be accepted without manual intervention. The second resource, aws_vpc_peering_connection_accepter, is used to confirm the acceptance of the peering connection on the second VPC.