Amazon EC2 Construct Library
@aws-cdk/aws-ec2 package contains primitives for setting up networking and
Most projects need a Virtual Private Cloud to provide security by means of
network partitioning. This is achieved by creating an instance of
All default constructs require EC2 instances to be launched inside a VPC, so you should generally start by defining a VPC whenever you need to launch instances for your project.
A VPC consists of one or more subnets that instances can be placed into. CDK distinguishes three different subnet types:
- Public - public subnets connect directly to the Internet using an Internet Gateway. If you want your instances to have a public IP address and be directly reachable from the Internet, you must place them in a public subnet.
- Private - instances in private subnets are not directly routable from the Internet, and connect out to the Internet via a NAT gateway. By default, a NAT gateway is created in every public subnet for maximum availability. Be aware that you will be charged for NAT gateways.
- Isolated - isolated subnets do not route from or to the Internet, and as such do not require NAT gateways. They can only connect to or be connected to from other instances in the same VPC. A default VPC configuration will not include isolated subnets,
A default VPC configuration will create public and private subnets, but not isolated subnets. See Advanced Subnet Configuration below for information on how to change the default subnet configuration.
Constructs using the VPC will "launch instances" (or more accurately, create
Elastic Network Interfaces) into one or more of the subnets. They all accept
a property called
subnetSelection (sometimes called
vpcSubnets) to allow
you to select in what subnet to place the ENIs, usually defaulting to
private subnets if the property is omitted.
If you would like to save on the cost of NAT gateways, you can use
isolated subnets instead of private subnets (as described in Advanced
Subnet Configuration). If you need private instances to have
internet connectivity, another option is to reduce the number of NAT gateways
created by setting the
natGateways property to a lower value (the default
is one NAT gateway per availability zone). Be aware that this may have
availability implications for your application.
Control over availability zones
By default, a VPC will spread over at most 3 Availability Zones available to
it. To change the number of Availability Zones that the VPC will spread over,
maxAzs property when defining it.
The number of Availability Zones that are available depends on the region and account of the Stack containing the VPC. If the region and account are specified on the Stack, the CLI will look up the existing Availability Zones and get an accurate count. If region and account are not specified, the stack could be deployed anywhere and it will have to make a safe choice, limiting itself to 2 Availability Zones.
Therefore, to get the VPC to spread over 3 or more availability zones, you must specify the environment where the stack will be deployed.
Using NAT instances
By default, the
Vpc construct will create NAT gateways for you, which
are managed by AWS. If you would prefer to use your own managed NAT
instances instead, specify a different value for the
property, as follows:
The construct will automatically search for the most recent NAT gateway AMI.
If you prefer to use a custom AMI, pass a
for the instance's
machineImage parameter and configure the right AMI ID
for the regions you want to deploy to.
Advanced Subnet Configuration
If the default VPC configuration (public and private subnets spanning the
size of the VPC) don't suffice for you, you can configure what subnets to
create by specifying the
subnetConfiguration property. It allows you
to configure the number and size of all subnets. Specifying an advanced
subnet configuration could look like this:
The example above is one possible configuration, but the user can use the constructs above to implement many other network configurations.
Vpc from the above configuration in a Region with three
availability zones will be the following:
|Subnet Name||Type||IP Block||AZ||Features|
||#1||Route to NAT in IngressSubnet1|
||#2||Route to NAT in IngressSubnet2|
||#3||Route to NAT in IngressSubnet3|
||#1||Only routes within the VPC|
||#2||Only routes within the VPC|
||#3||Only routes within the VPC|
Reserving subnet IP space
There are situations where the IP space for a subnet or number of subnets
will need to be reserved. This is useful in situations where subnets would
need to be added after the vpc is originally deployed, without causing IP
renumbering for existing subnets. The IP space for a subnet may be reserved
by setting the
reserved subnetConfiguration property to true, as shown
In the example above, the subnet for Application2 is not actually provisioned
but its IP space is still reserved. If in the future this subnet needs to be
provisioned, then the
reserved: true property should be removed. Reserving
parts of the IP space prevents the other subnets from getting renumbered.
Sharing VPCs between stacks
If you are creating multiple
Stacks inside the same CDK application, you
can reuse a VPC defined in one Stack in another by simply passing the VPC
Importing an existing VPC
If your VPC is created outside your CDK app, you can use
The CDK CLI will search for the specified VPC in the the stack's region and
account, and import the subnet configuration. Looking up can be done by VPC
ID, but more flexibly by searching for a specific tag on the VPC.
Subnet types will be determined from the
aws-cdk:subnet-type tag on the
subnet if it exists, or the presence of a route to an Internet Gateway
otherwise. Subnet names will be determined from the
on the subnet if it exists, or will mirror the subnet type otherwise (i.e.
a public subnet will have the name
Vpc.fromLookup() can be used:
In AWS, all network traffic in and out of Elastic Network Interfaces (ENIs)
is controlled by Security Groups. You can think of Security Groups as a
firewall with a set of rules. By default, Security Groups allow no incoming
(ingress) traffic and all outgoing (egress) traffic. You can add ingress rules
to them to allow incoming traffic streams. To exert fine-grained control over
egress traffic, set
allowAllOutbound: false on the
which you can add egress traffic rules.
You can manipulate Security Groups directly:
;mySecurityGroup.addIngressRuleec2.Peer.anyIpv4, ec2.Port.tcp22, 'allow ssh access from the world';
All constructs that create ENIs on your behalf (typically constructs that create EC2 instances or other VPC-connected resources) will all have security groups automatically assigned. Those constructs have an attribute called connections, which is an object that makes it convenient to update the security groups. If you want to allow connections between two constructs that have security groups, you have to add an Egress rule to one Security Group, and an Ingress rule to the other. The connections object will automatically take care of this for you:
// Allow connections from anywhereloadBalancer.connections.allowFromAnyIpv4ec2.Port.tcp443, 'Allow inbound HTTPS';// The same, but an explicit IP addressloadBalancer.connections.allowFromec2.Peer.ipv4'126.96.36.199/32', ec2.Port.tcp443, 'Allow inbound HTTPS';// Allow connection between AutoScalingGroupsappFleet.connections.allowTodbFleet, ec2.Port.tcp443, 'App can call database';
There are various classes that implement the connection peer part:
// Simple connection peers;peer = ec2.Peer.anyIpv4;peer = ec2.Peer.ipv6"::0/0";peer = ec2.Peer.anyIpv6;peer = ec2.Peer.prefixList"pl-12345";appFleet.connections.allowTopeer, ec2.Port.tcp443, 'Allow outbound HTTPS';
Any object that has a security group can itself be used as a connection peer:
// These automatically create appropriate ingress and egress rules in both security groupsfleet1.connections.allowTofleet2, ec2.Port.tcp80, 'Allow between fleets';appFleet.connections.allowFromAnyIpv4ec2.Port.tcp80, 'Allow from load balancer';
The connections that are allowed are specified by port ranges. A number of classes provide the connection specifier:
NOTE: This set is not complete yet; for example, there is no library support for ICMP at the moment. However, you can write your own classes to implement those.
Some Constructs have default ports associated with them. For example, the listener of a load balancer does (it's the public port), or instances of an RDS database (it's the port the database is accepting connections on).
If the object you're calling the peering method on has a default port associated with it, you can call
allowDefaultPortFrom() and omit the port specifier. If the argument has an associated default port, call
// Port implicit in listenerlistener.connections.allowDefaultPortFromAnyIpv4'Allow public';// Port implicit in peerappFleet.connections.allowDefaultPortTordsDatabase, 'Fleet can access database';
Machine Images (AMIs)
AMIs control the OS that gets launched when you start your EC2 instance. The EC2 library contains constructs to select the AMI you want to use.
Depending on the type of AMI, you select it a different way. Here are some examples of things you might want to use:
NOTE: The AMIs selected by
LookupImagewill be cached in
cdk.context.json, so that your AutoScalingGroup instances aren't replaced while you are making unrelated changes to your CDK app.
To query for the latest AMI again, remove the relevant cache entry from
cdk.context.json, or use the
cdk contextcommand. For more information, see Runtime Context in the CDK developer guide.
VPN connections to a VPC
Create your VPC with VPN connections by specifying the
vpnConnections props (keys are construct
To create a VPC that can accept VPN connections, set
VPN connections can then be added:
Routes will be propagated on the route tables associated with the private subnets.
VPN connections expose metrics (cloudwatch.Metric) across all tunnels in the account/region and per connection:
// Across all tunnels in the account/region;// For a specific vpn connection;;
A VPC endpoint enables you to privately connect your VPC to supported AWS services and VPC endpoint services powered by PrivateLink without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Instances in your VPC do not require public IP addresses to communicate with resources in the service. Traffic between your VPC and the other service does not leave the Amazon network.
Endpoints are virtual devices. They are horizontally scaled, redundant, and highly available VPC components that allow communication between instances in your VPC and services without imposing availability risks or bandwidth constraints on your network traffic.
Security groups for interface VPC endpoints
By default, interface VPC endpoints create a new security group and traffic is not automatically allowed from the VPC CIDR.
connections object to allow traffic to flow to the endpoint:
Alternatively, existing security groups can be used by specifying the
VPC endpoint services
A VPC endpoint service enables you to expose a Network Load Balancer(s) as a provider service to consumers, who connect to your service over a VPC endpoint. You can restrict access to your service via whitelisted principals (anything that extends ArnPrincipal), and require that new connections be manually accepted.
new VpcEndpointServicethis, "EndpointService",;
A bastion host functions as an instance used to access servers and resources in a VPC without open up the complete VPC on a network level. You can use bastion hosts using a standard SSH connection targetting port 22 on the host. As an alternative, you can connect the SSH connection feature of AWS Systems Manager Session Manager, which does not need an opened security group. (https://aws.amazon.com/about-aws/whats-new/2019/07/session-manager-launches-tunneling-support-for-ssh-and-scp/)
A default bastion host for use via SSM can be configured like:
If you want to connect from the internet using SSH, you need to place the host into a public subnet. You can then configure allowed source hosts.
As there are no SSH public keys deployed on this machine, you need to use EC2 Instance Connect
with the command
aws ec2-instance-connect send-ssh-public-key to provide your SSH public key.
To add EBS block device mappings, specify the
blockDeviceMappings property. The follow example sets the EBS-backed
root device (
/dev/sda1) size to 50 GiB, and adds another EBS-backed device mapped to
/dev/sdm that is 100 GiB in
new ec2.Instancethis, 'Instance',;