How Do You Implement VPC Peering with AWS CDK?

Managing infrastructure as code (IaC) is preferred for reproducibility. Below are the two primary methods to implement peering using AWS CDK in TypeScript.
Method 1: The High-Level Construct (Recommended)
This method is concise and uses CDK’s abstraction to handle the heavy lifting.
import*asec2from'aws-cdk-lib/aws-ec2';// Define your VPCsconstvpc1=newec2.Vpc(this, 'Vpc1', { maxAzs:2,cidr:'10.0.0.0/16'});constvpc2=newec2.Vpc(this, 'Vpc2', { maxAzs:2,cidr:'10.1.0.0/16'// Ensure CIDRs do not overlap});// Create the peering connection// vpc1 is the 'Requester', vpc2 is the 'Accepter'constpeeringConnection=vpc1.peer(vpc2, {peeringConnectionName:'Vpc1-to-Vpc2-Peering'});Method 2: The Low-Level CfnVPCPeeringConnection
Use this if you need granular control over specific CloudFormation properties or are working with existing VPC IDs that aren’t fully managed by your current CDK stack.
TypeScript
import*asec2from'aws-cdk-lib/aws-ec2';newec2.CfnVPCPeeringConnection(this, 'CustomPeering', {vpcId:'vpc-xxxxxx', // Requester VPC IDpeerVpcId:'vpc-yyyyyy', // Accepter VPC IDpeerRegion:'us-east-1', // Optional: if peering across regionspeerOwnerId:'123456789012'// Optional: if peering across accounts});Validating Your Infrastructure with Jest
You need to verify that your code generates the correct resources before deployment.
Why Test Infrastructure Code?
We use unit tests in CDK to ensure:
- Security Compliance:
Verify that no route tables open0.0.0.0/0to your internal peers unintentionally. - Routing Logic:
Confirm that the peering connection actually exists and links the correct VPC IDs. - Refactoring Safety:
Ensure future changes to your stack don’t accidentally delete the peering connection.
The Jest Test Script
Below is a Jest test script using the aws-cdk-lib/assertions module.
This script simulates the CloudFormation template generation and asserts that a Peering Connection exists and that routes are properly configured.
TypeScript
import*ascdkfrom'aws-cdk-lib';import{ Template, Match} from'aws-cdk-lib/assertions';import*asMyStackfrom'../lib/my-stack'; // Import your stack definitiontest('VPC Peering Connection Created', () =>{constapp=newcdk.App();// INSTANTIATE YOUR STACK HEREconststack=newMyStack.MyPeeringStack(app, 'MyTestStack');// Create a template from the stackconsttemplate=Template.fromStack(stack);// 1. Assert that the Peering Connection resource existstemplate.resourceCountIs('AWS::EC2::VPCPeeringConnection', 1);// 2. Assert that the Route Tables have a route to the peering connection// We check for a route that points to a "VpcPeeringConnectionId"template.hasResourceProperties('AWS::EC2::Route', {VpcPeeringConnectionId:{Ref:Match.stringLikeRegexp('^VpcPeering.*') // Matches the logical ID}});// 3. Verify the Peering is between the correct VPCs (Optional specific check)// This ensures the "PeerVpcId" property is presenttemplate.hasResourceProperties('AWS::EC2::VPCPeeringConnection', {VpcId:Match.anyValue(),PeerVpcId:Match.anyValue()});});VPC Peering vs. Transit Gateway: Which Should You Choose?
While VPC Peering is excellent for simple, point-to-point connections, it scales poorly. As your infrastructure grows, you might face the “mesh” problem.
- Choose VPC Peering if you have fewer than 10 VPCs and need a simple, cost-effective pipe between them.
- Choose AWS Transit Gateway if you are managing dozens of VPCs. Transit Gateway acts as a cloud router, solving the “transitive peering” limitation by allowing all connected VPCs to talk to each other through a central hub.

Recent Comments