Virtual Private Cloud (VPC) management in AWS CDK EC2 provides comprehensive control over network infrastructure including VPC creation, subnet configuration, NAT providers, and internet gateways.
The primary class for creating and managing VPCs is the Vpc construct, which automatically sets up a complete network infrastructure with subnets, route tables, and gateways.
class Vpc extends Resource implements IVpc {
constructor(scope: Construct, id: string, props?: VpcProps);
readonly vpcId: string;
readonly vpcArn: string;
readonly vpcCidrBlock: string;
readonly publicSubnets: ISubnet[];
readonly privateSubnets: ISubnet[];
readonly isolatedSubnets: ISubnet[];
readonly availabilityZones: string[];
readonly vpnGatewayId?: string;
readonly internetGatewayId?: string;
readonly internetConnectivityEstablished: IDependable;
// Static factory methods
static fromLookup(scope: Construct, id: string, options: VpcLookupOptions): IVpc;
static fromVpcAttributes(scope: Construct, id: string, attrs: VpcAttributes): IVpc;
// VPC endpoint management
addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint;
addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint;
// Flow logging
addFlowLog(id: string, options?: FlowLogOptions): FlowLog;
// VPN connectivity
addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection;
addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint;
enableVpnGateway(options: EnableVpnGatewayOptions): void;
// Subnet selection
selectSubnets(selection?: SubnetSelection): SelectedSubnets;
// Additional configuration
addDnsSupport(): void;
addNatGateway(options: NatGatewayOptions): string;
}
interface VpcProps {
readonly cidr?: string;
readonly enableDnsHostnames?: boolean;
readonly enableDnsSupport?: boolean;
readonly defaultInstanceTenancy?: DefaultInstanceTenancy;
readonly maxAzs?: number;
readonly natGateways?: number;
readonly natGatewayProvider?: NatProvider;
readonly natGatewaySubnets?: SubnetSelection;
readonly subnetConfiguration?: SubnetConfiguration[];
readonly vpnConnections?: { [id: string]: VpnConnectionOptions };
readonly vpnGateway?: boolean;
readonly vpnRoutePropagation?: SubnetSelection[];
readonly gatewayEndpoints?: { [id: string]: GatewayVpcEndpointOptions };
readonly flowLogs?: { [id: string]: FlowLogOptions };
}The IVpc interface defines the contract for VPC-like objects:
interface IVpc extends IResource {
readonly vpcId: string;
readonly vpcArn: string;
readonly vpcCidrBlock: string;
readonly publicSubnets: ISubnet[];
readonly privateSubnets: ISubnet[];
readonly isolatedSubnets: ISubnet[];
readonly availabilityZones: string[];
readonly vpnGatewayId?: string;
readonly internetConnectivityEstablished: IDependable;
addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint;
addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint;
addFlowLog(id: string, options?: FlowLogOptions): FlowLog;
addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection;
addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint;
enableVpnGateway(options: EnableVpnGatewayOptions): void;
selectSubnets(selection?: SubnetSelection): SelectedSubnets;
}NAT providers determine how outbound internet connectivity is provided for private subnets:
abstract class NatProvider {
static gateway(props?: NatGatewayProps): NatProvider;
static instance(props: NatInstanceProps): NatInstanceProvider;
abstract configureNat(options: ConfigureNatOptions): void;
abstract configureSubnet(subnet: PrivateSubnet): void;
}
class NatGatewayProvider extends NatProvider {
constructor(props?: NatGatewayProps);
configureNat(options: ConfigureNatOptions): void;
configureSubnet(subnet: PrivateSubnet): void;
}
class NatInstanceProvider extends NatProvider {
constructor(props: NatInstanceProps);
readonly connections: Connections;
readonly securityGroup: ISecurityGroup;
readonly gateway: GatewayConfig;
configureNat(options: ConfigureNatOptions): void;
configureSubnet(subnet: PrivateSubnet): void;
}
interface NatGatewayProps {
readonly eipAllocationIds?: string[];
}
interface NatInstanceProps {
readonly instanceType: InstanceType;
readonly machineImage?: IMachineImage;
readonly keyName?: string;
readonly securityGroup?: ISecurityGroup;
readonly defaultAllowedTraffic?: NatTrafficDirection;
}
enum NatTrafficDirection {
OUTBOUND_ONLY = 'OUTBOUND_ONLY',
INBOUND_AND_OUTBOUND = 'INBOUND_AND_OUTBOUND',
NONE = 'NONE'
}Subnet configuration controls how subnets are distributed across availability zones:
interface SubnetConfiguration {
readonly cidrMask: number;
readonly name: string;
readonly subnetType: SubnetType;
readonly reserved?: boolean;
readonly mapPublicIpOnLaunch?: boolean;
}
enum SubnetType {
PRIVATE_ISOLATED = 'Isolated',
PRIVATE_WITH_NAT = 'Private',
PUBLIC = 'Public'
}
interface SubnetSelection {
readonly availabilityZones?: string[];
readonly onePerAz?: boolean;
readonly subnetType?: SubnetType;
readonly subnets?: ISubnet[];
readonly subnetFilters?: SubnetFilter[];
readonly subnetGroupName?: string;
}
interface SelectedSubnets {
readonly subnetIds: string[];
readonly availabilityZones: string[];
readonly routeTableIds: string[];
readonly subnets: ISubnet[];
readonly internetConnectivityEstablished: IDependable;
readonly hasPublic: boolean;
}For working with existing VPCs:
interface VpcLookupOptions {
readonly vpcId?: string;
readonly vpcName?: string;
readonly tags?: {[key: string]: string};
readonly isDefault?: boolean;
readonly subnetGroupNameTag?: string;
readonly region?: string;
}
interface VpcAttributes {
readonly vpcId: string;
readonly vpcCidrBlock?: string;
readonly availabilityZones: string[];
readonly publicSubnetIds?: string[];
readonly privateSubnetIds?: string[];
readonly isolatedSubnetIds?: string[];
readonly publicSubnetNames?: string[];
readonly privateSubnetNames?: string[];
readonly isolatedSubnetNames?: string[];
readonly publicSubnetRouteTableIds?: string[];
readonly privateSubnetRouteTableIds?: string[];
readonly isolatedSubnetRouteTableIds?: string[];
readonly vpnGatewayId?: string;
readonly region?: string;
}import * as ec2 from "@aws-cdk/aws-ec2";
import * as cdk from "@aws-cdk/core";
const vpc = new ec2.Vpc(this, "MyVpc", {
cidr: "10.0.0.0/16",
maxAzs: 3,
natGateways: 2,
enableDnsHostnames: true,
enableDnsSupport: true
});const vpc = new ec2.Vpc(this, "CustomVpc", {
cidr: "10.0.0.0/16",
maxAzs: 2,
subnetConfiguration: [
{
cidrMask: 24,
name: "Public",
subnetType: ec2.SubnetType.PUBLIC
},
{
cidrMask: 24,
name: "Private",
subnetType: ec2.SubnetType.PRIVATE_WITH_NAT
},
{
cidrMask: 28,
name: "Database",
subnetType: ec2.SubnetType.PRIVATE_ISOLATED
}
]
});const natProvider = ec2.NatProvider.instance({
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
defaultAllowedTraffic: ec2.NatTrafficDirection.OUTBOUND_ONLY
});
const vpc = new ec2.Vpc(this, "VpcWithNatInstances", {
natGatewayProvider: natProvider,
natGateways: 1
});const existingVpc = ec2.Vpc.fromLookup(this, "ExistingVpc", {
vpcId: "vpc-12345678"
});
// Or by name
const namedVpc = ec2.Vpc.fromLookup(this, "NamedVpc", {
vpcName: "my-production-vpc"
});// Select all private subnets
const privateSubnets = vpc.selectSubnets({
subnetType: ec2.SubnetType.PRIVATE_WITH_NAT
});
// Select one subnet per AZ in specific availability zones
const selectedSubnets = vpc.selectSubnets({
availabilityZones: ["us-east-1a", "us-east-1b"],
onePerAz: true
});
// Select subnets by name
const databaseSubnets = vpc.selectSubnets({
subnetGroupName: "Database"
});const vpc = new ec2.Vpc(this, "VpcWithVpn", {
vpnGateway: true,
vpnRoutePropagation: [
{ subnetType: ec2.SubnetType.PRIVATE_WITH_NAT }
]
});const vpc = new ec2.Vpc(this, "VpcWithFlowLogs", {
flowLogs: {
"cloudwatch": {
trafficType: ec2.FlowLogTrafficType.ALL
}
}
});const vpc = new ec2.Vpc(this, "MyVpc");
// Add VPC endpoint after creation
vpc.addGatewayEndpoint("S3Endpoint", {
service: ec2.GatewayVpcEndpointAwsService.S3
});
// Add flow log
vpc.addFlowLog("VpcFlowLog", {
trafficType: ec2.FlowLogTrafficType.ALL
});
// Enable DNS support
vpc.addDnsSupport();