Defining Networks with VPC
Relevant source files
The following files were used as context for generating this wiki page:The AWS CDK provides high-level constructs to define and configure an Amazon Virtual Private Cloud (VPC). The primary construct for this is the Vpc class within the @aws-cdk/aws-ec2 module. This construct simplifies the creation of a VPC, its subnets, internet gateways, NAT gateways, and route tables, encapsulating best practices and reducing boilerplate CloudFormation.
By default, creating a Vpc will provision a network with both public and private subnets across a specified number of Availability Zones (AZs). This automated setup is highly configurable, allowing for custom CIDR ranges, subnet layouts, and network gateway strategies. This document details the architecture and components involved in defining a VPC using the AWS CDK.
Sources: packages/@aws-cdk/aws-ec2/lib/vpc.ts, packages/@aws-cdk/aws-ec2/test/vpc.test.ts
Core Components
The Vpc construct orchestrates several underlying resources to build a complete virtual network. The main components are the VPC itself, Subnets, NAT Gateways (or Instances), and Security Groups.
This diagram shows the high-level relationship between the main constructs used for defining a VPC.
The Vpc Construct
The Vpc class is the central point for creating a network. Instantiating it without any properties will create a default VPC with a CIDR block of 10.0.0.0/16, and public and private subnets in up to 3 Availability Zones.
Sources: packages/@aws-cdk/aws-ec2/lib/vpc.ts:177-178, packages/@aws-cdk/aws-ec2/test/vpc.test.ts:192-205
VpcProps
The behavior of the Vpc construct is controlled by the VpcProps interface.
| Property | Type | Default | Description |
|---|---|---|---|
cidr | string | 10.0.0.0/16 | The CIDR block for the VPC. Cannot be a token. |
maxAzs | number | 3 | The maximum number of Availability Zones to use. |
subnetConfiguration | SubnetConfiguration[] | Public and Private subnets | Specifies the subnet layout. If not provided, a default of one public and one private subnet group is created. |
natGateways | number | maxAzs | The number of NAT Gateways to create. Can be set to 0 to disable NAT and create PRIVATE_ISOLATED subnets instead of PRIVATE_WITH_NAT. |
natGatewayProvider | INatGatewayProvider | NatProvider.gateway() | Defines the NAT strategy, allowing for NAT Gateways or NAT Instances. |
natGatewaySubnets | SubnetSelection | - | Which subnets to place NAT Gateways in. Defaults to public subnets. |
vpnGateway | boolean | false | If true, a VPN gateway is created and attached. |
vpnGatewayAsn | number | - | The private Autonomous System Number (ASN) for the VPN gateway. |
enableDnsHostnames | boolean | true | Specifies whether DNS hostnames are enabled for the VPC. |
enableDnsSupport | boolean | true | Specifies whether DNS resolution is enabled for the VPC. |
Sources: packages/@aws-cdk/aws-ec2/lib/vpc.ts:86-174
Subnet Configuration
Subnets are defined using the subnetConfiguration property in VpcProps. Each entry in the array defines a group of subnets of a specific type.
SubnetType
The SubnetType enum determines the connectivity and purpose of a subnet group.
| Type | Description |
|---|---|
PUBLIC | Subnets in this group are connected to an Internet Gateway and can have public IP addresses. |
PRIVATE_WITH_NAT | Subnets in this group route outbound traffic through a NAT Gateway or Instance, allowing internet access without being publicly addressable. |
PRIVATE_ISOLATED | Subnets in this group have no route to the internet. |
Sources: packages/@aws-cdk/aws-ec2/lib/vpc.ts:38-53
SubnetConfiguration
This interface defines a group of subnets within the VPC.
| Property | Type | Description |
|---|---|---|
name | string | A logical name for the subnet group. |
subnetType | SubnetType | The type of subnets to create. |
cidrMask | number | The CIDR mask for the subnets in this group. The VPC's CIDR block is divided based on these masks. |
reserved | boolean | If true, the CIDR space for this group is reserved but no subnets are actually created. |
Sources: packages/@aws-cdk/aws-ec2/lib/vpc.ts:59-84
The following diagram illustrates a common VPC layout with Public and Private subnets, an Internet Gateway for public access, and a NAT Gateway for private outbound access.
This diagram shows how resources in a public subnet can communicate with the internet via an Internet Gateway, while resources in a private subnet route outbound traffic through a NAT Gateway located in the public subnet.
Sources: packages/@aws-cdk/aws-ec2/test/vpc.test.ts:251-285, packages/@aws-cdk/aws-codebuild/test/integ.project-vpc.expected.json
NAT Providers
The natGatewayProvider property on the Vpc allows for customizing how Network Address Translation is handled for private subnets. The CDK provides two built-in providers via the NatProvider class.
NatProvider.gateway(): This is the default provider. It creates and configuresAWS::EC2::NatGatewayresources in the public subnets. You can optionally provide pre-allocated Elastic IP addresses.NatProvider.instance(props): This provider creates and configures EC2 instances to act as NAT devices. This requires specifying aninstanceTypeand amachineImage.
The number of NAT gateways/instances created is determined by the natGateways property on the Vpc.
Sources: packages/@aws-cdk/aws-ec2/lib/nat.ts:44-79, packages/@aws-cdk/aws-ec2/test/vpc.test.ts:742-763
Security Groups
Security Groups act as a virtual firewall for instances to control inbound and outbound traffic. A SecurityGroup is always associated with a VPC. When creating a Project in a VPC, you can specify security groups. If none are provided, a default one may be created.
// Example of creating a Security Group and using it in a CodeBuild Project
const vpc = new ec2.Vpc(stack, 'MyVPC');
const securityGroup = new ec2.SecurityGroup(stack, 'SecurityGroup1', {
securityGroupName: 'Bob',
vpc,
allowAllOutbound: true,
description: 'Example',
});
const project = new codebuild.Project(stack, 'MyProject', {
source: /* ... */,
vpc,
securityGroups: [securityGroup],
});
Sources: packages/@aws-cdk/aws-ec2/test/vpc.test.ts:522-538, packages/@aws-cdk/aws-ec2/lib/security-group.ts
The connections property on a VPC-enabled construct (like a CodeBuild project or an EC2 instance) allows for managing traffic rules between resources.
Subnet Selection
The Vpc class provides a powerful selectSubnets() method to choose a set of subnets based on criteria. This is useful for placing resources like EC2 instances, load balancers, or VPC endpoints in specific subnets.
The SubnetSelection object can filter subnets by:
subnetType:PUBLIC,PRIVATE_WITH_NAT, orPRIVATE_ISOLATED. Defaults toPRIVATE_WITH_NATif available, otherwisePRIVATE_ISOLATED, otherwisePUBLIC.subnetGroupName: The logical name given in theSubnetConfiguration.availabilityZones: An array of AZ names to restrict the selection to.onePerAz: A boolean to select only one subnet per Availability Zone.subnets: An explicit list ofISubnetobjects to use.subnetFilters: An array ofSubnetFilterobjects for advanced filtering, such asSubnetFilter.byIds([...])orSubnetFilter.containsIpAddresses([...]).
Subnet Selection Flow
The following flowchart shows the logic for selecting subnets.
This logic allows for flexible and precise placement of resources within the VPC.
Sources: packages/@aws-cdk/aws-ec2/lib/vpc.ts:579-669, packages/@aws-cdk/aws-ec2/test/vpc.test.ts:912-1110
Conclusion
The Vpc construct in the AWS CDK offers a robust and high-level abstraction for defining cloud networks. It automates the creation and configuration of VPCs, subnets, route tables, and gateways based on a declarative configuration. By leveraging SubnetConfiguration, NatProvider, and selectSubnets, developers can easily model both simple and complex network topologies while adhering to best practices.