Overview and What You Will Learn
To connect many VPCs and an on-premises network on AWS, use a Transit Gateway as the central hub, Site-to-Site VPN for quick encrypted connectivity over the internet, and Direct Connect for a dedicated private link with consistent latency. Around that core you add security tools: Traffic Mirroring to capture packets, an egress-only gateway to keep IPv6 workloads private, and Network Firewall for deep inspection.
In this lab you will:
- Compare VPC peering, Transit Gateway, VPN and Direct Connect and choose between them
- Build two VPCs joined by a Transit Gateway in CloudFormation and prove reachability with Reachability Analyzer
- Break and repair a route to learn how to read the analyzer's explanation
- Review the commands for Site-to-Site VPN, ECMP, Direct Connect and Traffic Mirroring
- Configure an egress-only internet gateway for IPv6
- Understand where AWS Network Firewall sits and when it replaces other controls
Why This Matters in Production
A bank, insurer or government body that runs applications in its own data center and extends into AWS cannot expose those applications to the open internet. A VPN gives an encrypted tunnel quickly, and Direct Connect gives predictable latency for trading systems and large data pipelines. As the company grows to dozens of VPCs across accounts, a mesh of peering connections becomes unmanageable, and a Transit Gateway turns it into a hub with one attachment per network. Choosing and wiring these correctly is the difference between a design you can operate and one you can only describe.
Core Principles
Choose the connection by scale and by what sits at each end.
| Need | Use |
|---|---|
| Two or three VPCs, lowest cost | VPC peering |
| Many VPCs, on-premises, shared routing | Transit Gateway |
| Encrypted link over the internet, quick to start | Site-to-Site VPN |
| Dedicated private link, steady latency | Direct Connect |
A full mesh of peering grows as n times (n minus 1) divided by 2, so 10 VPCs need 45 peerings and 20 need 190. Peering is also not transitive, so if A peers with B and B peers with C, A cannot reach C. A Transit Gateway (TGW) is a regional router: each VPC, VPN, Direct Connect gateway or peered TGW attaches once, and TGW route tables decide which attachments can reach which.
10.1.0.0/16] --> TGW{Transit Gateway} B[VPC B
10.2.0.0/16] --> TGW C[VPC C
10.3.0.0/16] --> TGW TGW --> VPN[Site-to-Site VPN] TGW --> DXG[Direct Connect gateway] VPN --> DC([Data center]) DXG --> DC classDef vpc fill:#D1FAE5,color:#1E293B classDef hub fill:#326CE5,color:#FFFFFF classDef link fill:#F97316,color:#FFFFFF classDef site fill:#475569,color:#FFFFFF class A,B,C vpc class TGW hub class VPN,DXG link class DC site
Transit Gateway is billed per attachment per hour plus per GB processed, while same-region VPC peering has no hourly charge, so with only two or three VPCs peering is cheaper. Both TGW and peering require non-overlapping CIDR ranges. You cannot change a VPC's primary CIDR, but you can add secondary CIDR blocks, so plan address space centrally before creating VPCs.
Site-to-Site VPN. A VPN connection joins an AWS gateway to your router over two IPsec tunnels, and you should configure both on your device for high availability. The AWS side is a Virtual Private Gateway (VGW, attached to one VPC) or a Transit Gateway. The customer side is a Customer Gateway, an AWS resource that records your device's public IP and BGP ASN. Use dynamic BGP routing so routes propagate automatically. Each tunnel carries up to 1.25 Gbps, and a single flow stays on one tunnel.
ECMP. A Transit Gateway can balance traffic across several VPN tunnels with equal cost multi-path routing when the VPNs use BGP. Four tunnels can carry about 5 Gbps in aggregate, though any one flow is still limited to a single tunnel. A VGW does not support ECMP.
VPN CloudHub. Several branch offices connect to one VGW, each through its own Customer Gateway with a distinct BGP ASN. The VGW re-advertises their routes, so branches reach each other, and because the VGW is attached to a VPC they also reach that VPC. It is cheap and works over the internet, but a Transit Gateway or SD-WAN design scales better.
Direct Connect. A dedicated physical connection runs from your site to an AWS Direct Connect location. You attach it to AWS with virtual interfaces (VIFs):
| VIF | Reaches |
|---|---|
| Private | One VPC through a VGW, or many through a Direct Connect gateway |
| Public | AWS public service endpoints such as S3 |
| Transit | Transit Gateways through a Direct Connect gateway |
A Direct Connect gateway is a global object. One connection can reach VPCs or Transit Gateways in multiple Regions through it, but the gateway does not route traffic between those VPCs. Direct Connect is private but not encrypted by default. Encrypt it with MACsec (on supported 10, 100 and 400 Gbps dedicated connections) or run IPsec VPN over it.
Direct Connect resiliency. AWS describes three models:
| Model | Layout |
|---|---|
| Maximum resiliency | Two connections at each of two or more locations, on separate devices |
| High resiliency | One connection at each of two or more locations |
| Development and test | Separate connections on separate devices at one location |
A Site-to-Site VPN is a common low-cost backup. When both exist for the same prefix, AWS prefers the Direct Connect path, and you control preference on your own router with BGP local preference.
RememberPeering is not transitive, Direct Connect gateways do not route VPC to VPC, and a single VPN tunnel is capped at 1.25 Gbps. These three limits drive most hybrid designs.
Detailed Step-by-Step Practical Lab
Milestone 1: Define Two VPCs and a Transit Gateway
This template creates two VPCs with a subnet each, a Transit Gateway with attachments, routes pointing at it, and one network interface per VPC to test between. No instances are needed.
AWSTemplateFormatVersion: "2010-09-09"Description: Two VPCs connected through a Transit Gateway Resources: VpcA: Type: AWS::EC2::VPC Properties: CidrBlock: 10.1.0.0/16 Tags: [{Key: Name, Value: vpc-a}] VpcB: Type: AWS::EC2::VPC Properties: CidrBlock: 10.2.0.0/16 Tags: [{Key: Name, Value: vpc-b}] SubnetA: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VpcA CidrBlock: 10.1.1.0/24 AvailabilityZone: !Select [0, !GetAZs ""] SubnetB: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VpcB CidrBlock: 10.2.1.0/24 AvailabilityZone: !Select [0, !GetAZs ""] RouteTableA: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VpcA RouteTableB: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VpcB AssocA: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref SubnetA RouteTableId: !Ref RouteTableA AssocB: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref SubnetB RouteTableId: !Ref RouteTableB Tgw: Type: AWS::EC2::TransitGateway Properties: Description: devops-tgw DefaultRouteTableAssociation: enable DefaultRouteTablePropagation: enable VpnEcmpSupport: enable AttachA: Type: AWS::EC2::TransitGatewayVpcAttachment Properties: TransitGatewayId: !Ref Tgw VpcId: !Ref VpcA SubnetIds: [!Ref SubnetA] AttachB: Type: AWS::EC2::TransitGatewayVpcAttachment Properties: TransitGatewayId: !Ref Tgw VpcId: !Ref VpcB SubnetIds: [!Ref SubnetB] RouteAToB: Type: AWS::EC2::Route DependsOn: AttachA Properties: RouteTableId: !Ref RouteTableA DestinationCidrBlock: 10.2.0.0/16 TransitGatewayId: !Ref Tgw RouteBToA: Type: AWS::EC2::Route DependsOn: AttachB Properties: RouteTableId: !Ref RouteTableB DestinationCidrBlock: 10.1.0.0/16 TransitGatewayId: !Ref Tgw SgA: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Allow HTTPS from the lab ranges VpcId: !Ref VpcA SecurityGroupIngress: - IpProtocol: tcp FromPort: 443 ToPort: 443 CidrIp: 10.0.0.0/8 SgB: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Allow HTTPS from the lab ranges VpcId: !Ref VpcB SecurityGroupIngress: - IpProtocol: tcp FromPort: 443 ToPort: 443 CidrIp: 10.0.0.0/8 EniA: Type: AWS::EC2::NetworkInterface Properties: SubnetId: !Ref SubnetA GroupSet: [!Ref SgA] EniB: Type: AWS::EC2::NetworkInterface Properties: SubnetId: !Ref SubnetB GroupSet: [!Ref SgB] Outputs: TgwId: Value: !Ref Tgw EniAId: Value: !Ref EniA EniBId: Value: !Ref EniB RouteTableAId: Value: !Ref RouteTableAWith default association and propagation enabled, each attachment is associated with the TGW's default route table and its CIDR is propagated into it, so VPC A and VPC B learn each other automatically. Each VPC also needs its own route to the other's CIDR pointing at the TGW, which the template adds.
Milestone 2: Deploy and Inspect
Attachments take a few minutes to become available. Billing starts as soon as they exist, so remember the cleanup.
export AWS_REGION=ap-south-1 aws cloudformation deploy --stack-name tgw-lab --template-file tgw-lab.yaml get_out() { aws cloudformation describe-stacks --stack-name tgw-lab \ --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue" --output text}export TGW_ID=$(get_out TgwId)export ENI_A=$(get_out EniAId)export ENI_B=$(get_out EniBId)export RT_A=$(get_out RouteTableAId) aws ec2 describe-transit-gateway-vpc-attachments \ --filters Name=transit-gateway-id,Values=$TGW_ID \ --query "TransitGatewayVpcAttachments[].[TransitGatewayAttachmentId,VpcId,State]" --output table # What the TGW route table learnedTGW_RT=$(aws ec2 describe-transit-gateway-route-tables \ --filters Name=transit-gateway-id,Values=$TGW_ID \ --query "TransitGatewayRouteTables[0].TransitGatewayRouteTableId" --output text) aws ec2 search-transit-gateway-routes \ --transit-gateway-route-table-id $TGW_RT \ --filters Name=state,Values=active \ --query "Routes[].[DestinationCidrBlock,Type,TransitGatewayAttachments[0].ResourceId]" --output tableMilestone 3: Prove Reachability with Reachability Analyzer
Reachability Analyzer checks a path through routes, security groups, network ACLs and gateways without sending traffic. Each analysis has a small charge.
PATH_ID=$(aws ec2 create-network-insights-path \ --source $ENI_A --destination $ENI_B \ --protocol tcp --destination-port 443 \ --query "NetworkInsightsPath.NetworkInsightsPathId" --output text) ANALYSIS_ID=$(aws ec2 start-network-insights-analysis \ --network-insights-path-id $PATH_ID \ --query "NetworkInsightsAnalysis.NetworkInsightsAnalysisId" --output text) sleep 30aws ec2 describe-network-insights-analyses \ --network-insights-analysis-ids $ANALYSIS_ID \ --query "NetworkInsightsAnalyses[0].[Status,NetworkPathFound]" --output text# succeeded TrueMilestone 4: Break a Route and Read the Explanation
Remove the route from VPC A to VPC B and run the analysis again. The failure explanation tells you which component dropped the path.
aws ec2 delete-route --route-table-id $RT_A --destination-cidr-block 10.2.0.0/16 ANALYSIS_ID=$(aws ec2 start-network-insights-analysis \ --network-insights-path-id $PATH_ID \ --query "NetworkInsightsAnalysis.NetworkInsightsAnalysisId" --output text)sleep 30 aws ec2 describe-network-insights-analyses \ --network-insights-analysis-ids $ANALYSIS_ID \ --query "NetworkInsightsAnalyses[0].[NetworkPathFound,Explanations[0].ExplanationCode]" --output text# False NO_ROUTE_TO_DESTINATION # Repair itaws ec2 create-route --route-table-id $RT_A \ --destination-cidr-block 10.2.0.0/16 --transit-gateway-id $TGW_IDA TGW attachment lets traffic in only through the AZs where you chose an attachment subnet, so attach a subnet in every AZ you use.
Milestone 5: Site-to-Site VPN to Transit Gateway
This milestone needs a real or virtual on-premises router, so treat it as reference. A VPN attached to a Transit Gateway uses BGP and supports ECMP, which a VGW does not.
# The device's public IP and BGP ASNCGW_ID=$(aws ec2 create-customer-gateway \ --type ipsec.1 --public-ip 203.0.113.5 --bgp-asn 65000 \ --query "CustomerGateway.CustomerGatewayId" --output text) # Two tunnels are created automaticallyaws ec2 create-vpn-connection \ --type ipsec.1 \ --customer-gateway-id $CGW_ID \ --transit-gateway-id $TGW_ID \ --options StaticRoutesOnly=false # Make sure ECMP is on so several VPN connections share loadaws ec2 modify-transit-gateway \ --transit-gateway-id $TGW_ID \ --options VpnEcmpSupport=enable # Check the tunnels. Both should report UP once your router is configuredaws ec2 describe-vpn-connections \ --query "VpnConnections[].VgwTelemetry[].[OutsideIpAddress,Status,StatusMessage]" --output tableDownload the vendor-specific configuration from the VPN connection page in the console and apply it to your router, configuring both tunnels. For a VGW-based VPN, create the VGW with create-vpn-gateway, attach it to the VPC, and turn on route propagation with enable-vgw-route-propagation so BGP routes appear in the route table.
Milestone 6: Direct Connect Gateway and Transit VIF
The physical connection is ordered through the console or a partner and can take weeks, so the lab covers the cloud-side resources only.
aws directconnect describe-connections \ --query "connections[].[connectionId,connectionName,connectionState,bandwidth]" --output table DXGW_ID=$(aws directconnect create-direct-connect-gateway \ --direct-connect-gateway-name devops-dxgw \ --amazon-side-asn 64512 \ --query "directConnectGateway.directConnectGatewayId" --output text) # Associate the Transit Gateway and say which on-premises-facing prefixes AWS advertisesaws directconnect create-direct-connect-gateway-association \ --direct-connect-gateway-id $DXGW_ID \ --gateway-id $TGW_ID \ --add-allowed-prefixes-to-direct-connect-gateway cidr=10.0.0.0/8 aws directconnect describe-virtual-interfaces \ --query "virtualInterfaces[].[virtualInterfaceId,virtualInterfaceType,virtualInterfaceState]" --output tableSecurityDirect Connect traffic is private but not encrypted. Enable MACsec where the connection supports it, or run an IPsec VPN over the Direct Connect link, for regulated data such as payment or personal information.
Milestone 7: Capture Traffic with Traffic Mirroring
Traffic Mirroring copies packets from an instance's network interface to a monitoring target without touching the original traffic. The source must be on a supported Nitro-based instance, and the copy is encapsulated in VXLAN on UDP port 4789.
# Target: the network interface of your IDS or packet capture applianceTARGET_ID=$(aws ec2 create-traffic-mirror-target \ --network-interface-id eni-0aaa111bbb222ccc3 \ --description "ids-appliance" \ --query "TrafficMirrorTarget.TrafficMirrorTargetId" --output text) # Filter: copy only inbound HTTPS to the web serverFILTER_ID=$(aws ec2 create-traffic-mirror-filter \ --description "https-only" \ --query "TrafficMirrorFilter.TrafficMirrorFilterId" --output text) aws ec2 create-traffic-mirror-filter-rule \ --traffic-mirror-filter-id $FILTER_ID \ --traffic-direction ingress --rule-number 100 --rule-action accept \ --protocol 6 \ --destination-port-range FromPort=443,ToPort=443 \ --source-cidr-block 0.0.0.0/0 --destination-cidr-block 10.1.1.0/24 # Session: source ENI to target using the filteraws ec2 create-traffic-mirror-session \ --network-interface-id eni-0ddd444eee555fff6 \ --traffic-mirror-target-id $TARGET_ID \ --traffic-mirror-filter-id $FILTER_ID \ --session-number 1Use it for threat detection, troubleshooting with full packet captures and forensics. Mirror only what you need, because it adds network load and storage.
Milestone 8: Keep IPv6 Workloads Outbound-Only
In a VPC, IPv6 addresses come from globally unique ranges, so there is no NAT to hide them. Reachability is controlled by routes and security groups. An egress-only internet gateway (EIGW) lets IPv6 instances start outbound connections while blocking connections initiated from the internet, which is the IPv6 equivalent of a NAT gateway's protection.
EIGW_ID=$(aws ec2 create-egress-only-internet-gateway \ --vpc-id vpc-0abc123456789def \ --query "EgressOnlyInternetGateway.EgressOnlyInternetGatewayId" --output text) aws ec2 create-route \ --route-table-id rtb-0private123456789 \ --destination-ipv6-cidr-block ::/0 \ --egress-only-internet-gateway-id $EIGW_IDThe IPv6 default route is ::/0. For IPv6-only workloads that must reach IPv4 services, use NAT gateway NAT64 with DNS64.
Milestone 9: Know Where Network Firewall Fits
AWS Network Firewall is a managed, stateful firewall with stateless and stateful rule engines, domain filtering, Suricata-compatible intrusion prevention rules, TLS inspection and managed threat rule groups. You deploy firewall endpoints into dedicated subnets in each AZ and change route tables so traffic passes through them.
firewall subnet] FW --> ALB[Load balancer
public subnet] ALB --> APP[App servers
private subnet] classDef edge fill:#F97316,color:#FFFFFF classDef fw fill:#EF4444,color:#FFFFFF classDef app fill:#10B981,color:#FFFFFF class I,IGW edge class FW fw class ALB,APP app
A Suricata-style rule that drops traffic to a blocked domain looks like this:
drop tls $HOME_NET any -> $EXTERNAL_NET any (tls.sni; content:"malware-downloads.example"; nocase; endswith; msg:"Blocked domain"; sid:1000001; rev:1;)For inspection between VPCs, attach a dedicated inspection VPC to the Transit Gateway and enable appliance mode on that attachment, so both directions of a flow use the same AZ and the stateful firewall sees complete connections.
| Control | Level | Strength |
|---|---|---|
| Security group | Instance, stateful | Per-workload allow rules |
| Network ACL | Subnet, stateless | Coarse allow and deny |
| AWS WAF | HTTP and HTTPS, layer 7 | Web exploits on ALB, CloudFront, API Gateway |
| Network Firewall | VPC traffic, layers 3 to 7 | Any protocol, domains, intrusion prevention |
Use them together. Network Firewall does not replace WAF, which understands web application attacks, and WAF does not inspect non-HTTP traffic.
Milestone 10: Clean Up
Delete the stack. Transit Gateway attachments and VPN connections are billed hourly, so confirm nothing is left.
aws ec2 delete-network-insights-path --network-insights-path-id $PATH_IDaws cloudformation delete-stack --stack-name tgw-labaws cloudformation wait stack-delete-complete --stack-name tgw-lab # If you created the optional resourcesaws ec2 delete-vpn-connection --vpn-connection-id vpn-0abc123def456789aws ec2 delete-customer-gateway --customer-gateway-id $CGW_IDaws directconnect delete-direct-connect-gateway --direct-connect-gateway-id $DXGW_IDProduction Best Practices & Common Pitfalls
- Plan address space first. Overlapping CIDRs cannot be routed between VPCs through peering or a TGW.
- Use a Transit Gateway beyond a few VPCs. Compare its hourly and data charges with peering for small designs.
- Attach a subnet in every AZ you use. Traffic is delivered only into AZs with an attachment.
- Use several route tables on the TGW. Segment production from development instead of letting everything talk to everything.
- Configure both VPN tunnels and use BGP. Monitor tunnel state in CloudWatch.
- Build resilient Direct Connect. Use at least two locations, and a VPN backup if you cannot afford four connections.
- Encrypt Direct Connect for regulated data. MACsec or IPsec over the link.
- Share the TGW with AWS Resource Access Manager. One hub can serve many accounts.
- Test paths with Reachability Analyzer. Do it before and after every change.
Common MistakeExpecting transitive routing through VPC peering. If A peers with B and B peers with C, A still cannot reach C. Create a direct peering, or move to a Transit Gateway.
Common MistakeAdding a Transit Gateway attachment and forgetting the VPC route table entry. The attachment can be healthy while no traffic flows, because the VPC has no route toward the TGW.
TipUse the VPN as a backup for Direct Connect and set BGP local preference on your router so the Direct Connect path wins while it is healthy. Test the failover by shutting the Direct Connect BGP session during a maintenance window.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
aws ec2 describe-transit-gateways |
List Transit Gateways |
aws ec2 describe-transit-gateway-vpc-attachments |
List VPC attachments and state |
aws ec2 search-transit-gateway-routes |
Show routes in a TGW route table |
aws ec2 describe-vpn-connections |
Show VPN tunnel status |
aws directconnect describe-connections |
List Direct Connect connections |
aws directconnect describe-virtual-interfaces |
List VIFs and their state |
aws ec2 start-network-insights-analysis |
Analyze a network path |
| Symptom | Likely cause and fix |
|---|---|
| VPN tunnels UP but no traffic | Missing route or propagation in the VPC or TGW route table |
| Cannot reach VPC B from VPC A through the TGW | Missing route in a VPC route table, or a security group or ACL blocking |
| Traffic fails only from one AZ | No attachment subnet in that AZ |
| Attachment stays pending | Subnet or permission problem, check the state message and account sharing |
| Slow transfer over VPN | A single flow is capped at one 1.25 Gbps tunnel, use parallel flows and ECMP |
| IPv6 instance reachable from the internet | Route to an internet gateway instead of an egress-only gateway |
| Stateful firewall drops return traffic | Asymmetric path through different AZs, enable appliance mode |