class aws_cdk.aws_ec2.Vpc(scope, id, *, availability_zones=None, cidr=None, default_instance_tenancy=None, enable_dns_hostnames=None, enable_dns_support=None, flow_logs=None, gateway_endpoints=None, ip_addresses=None, max_azs=None, nat_gateway_provider=None, nat_gateways=None, nat_gateway_subnets=None, reserved_azs=None, subnet_configuration=None, vpc_name=None, vpn_connections=None, vpn_gateway=None, vpn_gateway_asn=None, vpn_route_propagation=None)

Bases: Resource

Define an AWS Virtual Private Cloud.

See the package-level documentation of this package for an overview of the various dimensions in which you can configure your VPC.

For example:

# Example automatically generated from non-compiling source. May contain errors.
vpc = ec2.Vpc(self, "TheVPC",

# Iterate the private subnets
selection = vpc.select_subnets(

for subnet in selection.subnets:





import aws_cdk.aws_ec2 as ec2

vpc = ec2.Vpc(self, "Vpc",

vpc_connector = apprunner.VpcConnector(self, "VpcConnector",

apprunner.Service(self, "Service",

Vpc creates a VPC that spans a whole region.

It will automatically divide the provided VPC CIDR range, and create public and private subnets per Availability Zone. Network routing for the public subnets will be configured to allow outbound access directly via an Internet Gateway. Network routing for the private subnets will be configured to allow outbound access via a set of resilient NAT Gateways (one per AZ).

  • scope (Construct) –

  • id (str) –

  • availability_zones (Optional[Sequence[str]]) – Availability zones this VPC spans. Specify this option only if you do not specify maxAzs. Default: - a subset of AZs of the stack

  • cidr (Optional[str]) – (deprecated) The CIDR range to use for the VPC, e.g. ‘’. Should be a minimum of /28 and maximum size of /16. The range will be split across all subnets per Availability Zone. Default: Vpc.DEFAULT_CIDR_RANGE

  • default_instance_tenancy (Optional[DefaultInstanceTenancy]) – The default tenancy of instances launched into the VPC. By setting this to dedicated tenancy, instances will be launched on hardware dedicated to a single AWS customer, unless specifically specified at instance launch time. Please note, not all instance types are usable with Dedicated tenancy. Default: DefaultInstanceTenancy.Default (shared) tenancy

  • enable_dns_hostnames (Optional[bool]) – Indicates whether the instances launched in the VPC get public DNS hostnames. If this attribute is true, instances in the VPC get public DNS hostnames, but only if the enableDnsSupport attribute is also set to true. Default: true

  • enable_dns_support (Optional[bool]) – Indicates whether the DNS resolution is supported for the VPC. If this attribute is false, the Amazon-provided DNS server in the VPC that resolves public DNS hostnames to IP addresses is not enabled. If this attribute is true, queries to the Amazon provided DNS server at the IP address, or the reserved IP address at the base of the VPC IPv4 network range plus two will succeed. Default: true

  • flow_logs (Optional[Mapping[str, Union[FlowLogOptions, Dict[str, Any]]]]) – Flow logs to add to this VPC. Default: - No flow logs.

  • gateway_endpoints (Optional[Mapping[str, Union[GatewayVpcEndpointOptions, Dict[str, Any]]]]) – Gateway endpoints to add to this VPC. Default: - None.

  • ip_addresses (Optional[IIpAddresses]) – The Provider to use to allocate IP Space to your VPC. Options include static allocation or from a pool. Default: ec2.IpAddresses.cidr

  • max_azs (Union[int, float, None]) – Define the maximum number of AZs to use in this region. If the region has more AZs than you want to use (for example, because of EIP limits), pick a lower number here. The AZs will be sorted and picked from the start of the list. If you pick a higher number than the number of AZs in the region, all AZs in the region will be selected. To use “all AZs” available to your account, use a high number (such as 99). Be aware that environment-agnostic stacks will be created with access to only 2 AZs, so to use more than 2 AZs, be sure to specify the account and region on your stack. Specify this option only if you do not specify availabilityZones. Default: 3

  • nat_gateway_provider (Optional[NatProvider]) – What type of NAT provider to use. Select between NAT gateways or NAT instances. NAT gateways may not be available in all AWS regions. Default: NatProvider.gateway()

  • nat_gateways (Union[int, float, None]) – The number of NAT Gateways/Instances to create. The type of NAT gateway or instance will be determined by the natGatewayProvider parameter. You can set this number lower than the number of Availability Zones in your VPC in order to save on NAT cost. Be aware you may be charged for cross-AZ data traffic instead. Default: - One NAT gateway/instance per Availability Zone

  • nat_gateway_subnets (Union[SubnetSelection, Dict[str, Any], None]) – Configures the subnets which will have NAT Gateways/Instances. You can pick a specific group of subnets by specifying the group name; the picked subnets must be public subnets. Only necessary if you have more than one public subnet group. Default: - All public subnets.

  • reserved_azs (Union[int, float, None]) – Define the number of AZs to reserve. When specified, the IP space is reserved for the azs but no actual resources are provisioned. Default: 0

  • subnet_configuration (Optional[Sequence[Union[SubnetConfiguration, Dict[str, Any]]]]) – Configure the subnets to build for each AZ. Each entry in this list configures a Subnet Group; each group will contain a subnet for each Availability Zone. For example, if you want 1 public subnet, 1 private subnet, and 1 isolated subnet in each AZ provide the following:: new ec2.Vpc(this, ‘VPC’, { subnetConfiguration: [ { cidrMask: 24, name: ‘ingress’, subnetType: ec2.SubnetType.PUBLIC, }, { cidrMask: 24, name: ‘application’, subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, }, { cidrMask: 28, name: ‘rds’, subnetType: ec2.SubnetType.PRIVATE_ISOLATED, } ] }); Default: - The VPC CIDR will be evenly divided between 1 public and 1 private subnet per AZ.

  • vpc_name (Optional[str]) – The VPC name. Since the VPC resource doesn’t support providing a physical name, the value provided here will be recorded in the Name tag Default: this.node.path

  • vpn_connections (Optional[Mapping[str, Union[VpnConnectionOptions, Dict[str, Any]]]]) – VPN connections to this VPC. Default: - No connections.

  • vpn_gateway (Optional[bool]) – Indicates whether a VPN gateway should be created and attached to this VPC. Default: - true when vpnGatewayAsn or vpnConnections is specified

  • vpn_gateway_asn (Union[int, float, None]) – The private Autonomous System Number (ASN) for the VPN gateway. Default: - Amazon default ASN.

  • vpn_route_propagation (Optional[Sequence[Union[SubnetSelection, Dict[str, Any]]]]) – Where to propagate VPN routes. Default: - On the route tables associated with private subnets. If no private subnets exists, isolated subnets are used. If no isolated subnets exists, public subnets are used.


add_client_vpn_endpoint(id, *, cidr, server_certificate_arn, authorize_all_users_to_vpc_cidr=None, client_certificate_arn=None, client_connection_handler=None, client_login_banner=None, description=None, dns_servers=None, logging=None, log_group=None, log_stream=None, port=None, security_groups=None, self_service_portal=None, session_timeout=None, split_tunnel=None, transport_protocol=None, user_based_authentication=None, vpc_subnets=None)

Adds a new client VPN endpoint to this VPC.

  • id (str) –

  • cidr (str) – The IPv4 address range, in CIDR notation, from which to assign client IP addresses. The address range cannot overlap with the local CIDR of the VPC in which the associated subnet is located, or the routes that you add manually. Changing the address range will replace the Client VPN endpoint. The CIDR block should be /22 or greater.

  • server_certificate_arn (str) – The ARN of the server certificate.

  • authorize_all_users_to_vpc_cidr (Optional[bool]) – Whether to authorize all users to the VPC CIDR. This automatically creates an authorization rule. Set this to false and use addAuthorizationRule() to create your own rules instead. Default: true

  • client_certificate_arn (Optional[str]) – The ARN of the client certificate for mutual authentication. The certificate must be signed by a certificate authority (CA) and it must be provisioned in AWS Certificate Manager (ACM). Default: - use user-based authentication

  • client_connection_handler (Optional[IClientVpnConnectionHandler]) – The AWS Lambda function used for connection authorization. The name of the Lambda function must begin with the AWSClientVPN- prefix Default: - no connection handler

  • client_login_banner (Optional[str]) – Customizable text that will be displayed in a banner on AWS provided clients when a VPN session is established. UTF-8 encoded characters only. Maximum of 1400 characters. Default: - no banner is presented to the client

  • description (Optional[str]) – A brief description of the Client VPN endpoint. Default: - no description

  • dns_servers (Optional[Sequence[str]]) – Information about the DNS servers to be used for DNS resolution. A Client VPN endpoint can have up to two DNS servers. Default: - use the DNS address configured on the device

  • logging (Optional[bool]) – Whether to enable connections logging. Default: true

  • log_group (Optional[ILogGroup]) – A CloudWatch Logs log group for connection logging. Default: - a new group is created

  • log_stream (Optional[ILogStream]) – A CloudWatch Logs log stream for connection logging. Default: - a new stream is created

  • port (Optional[VpnPort]) – The port number to assign to the Client VPN endpoint for TCP and UDP traffic. Default: VpnPort.HTTPS

  • security_groups (Optional[Sequence[ISecurityGroup]]) – The security groups to apply to the target network. Default: - a new security group is created

  • self_service_portal (Optional[bool]) – Specify whether to enable the self-service portal for the Client VPN endpoint. Default: true

  • session_timeout (Optional[ClientVpnSessionTimeout]) – The maximum VPN session duration time. Default: ClientVpnSessionTimeout.TWENTY_FOUR_HOURS

  • split_tunnel (Optional[bool]) – Indicates whether split-tunnel is enabled on the AWS Client VPN endpoint. Default: false

  • transport_protocol (Optional[TransportProtocol]) – The transport protocol to be used by the VPN session. Default: TransportProtocol.UDP

  • user_based_authentication (Optional[ClientVpnUserBasedAuthentication]) – The type of user-based authentication to use. Default: - use mutual authentication

  • vpc_subnets (Union[SubnetSelection, Dict[str, Any], None]) – Subnets to associate to the client VPN endpoint. Default: - the VPC default strategy

Return type


add_flow_log(id, *, destination=None, log_format=None, max_aggregation_interval=None, traffic_type=None)

Adds a new flow log to this VPC.

  • id (str) –

  • destination (Optional[FlowLogDestination]) – Specifies the type of destination to which the flow log data is to be published. Flow log data can be published to CloudWatch Logs or Amazon S3 Default: FlowLogDestinationType.toCloudWatchLogs()

  • log_format (Optional[Sequence[LogFormat]]) – The fields to include in the flow log record, in the order in which they should appear. If multiple fields are specified, they will be separated by spaces. For full control over the literal log format string, pass a single field constructed with LogFormat.custom(). See https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html#flow-log-records Default: - default log format is used.

  • max_aggregation_interval (Optional[FlowLogMaxAggregationInterval]) – The maximum interval of time during which a flow of packets is captured and aggregated into a flow log record. Default: FlowLogMaxAggregationInterval.TEN_MINUTES

  • traffic_type (Optional[FlowLogTrafficType]) – The type of traffic to log. You can log traffic that the resource accepts or rejects, or all traffic. Default: ALL

Return type


add_gateway_endpoint(id, *, service, subnets=None)

Adds a new gateway endpoint to this VPC.

  • id (str) –

  • service (IGatewayVpcEndpointService) – The service to use for this gateway VPC endpoint.

  • subnets (Optional[Sequence[Union[SubnetSelection, Dict[str, Any]]]]) – Where to add endpoint routing. By default, this endpoint will be routable from all subnets in the VPC. Specify a list of subnet selection objects here to be more specific. Default: - All subnets in the VPC

Return type


add_interface_endpoint(id, *, service, lookup_supported_azs=None, open=None, private_dns_enabled=None, security_groups=None, subnets=None)

Adds a new interface endpoint to this VPC.

  • id (str) –

  • service (IInterfaceVpcEndpointService) – The service to use for this interface VPC endpoint.

  • lookup_supported_azs (Optional[bool]) – Limit to only those availability zones where the endpoint service can be created. Setting this to ‘true’ requires a lookup to be performed at synthesis time. Account and region must be set on the containing stack for this to work. Default: false

  • open (Optional[bool]) – Whether to automatically allow VPC traffic to the endpoint. If enabled, all traffic to the endpoint from within the VPC will be automatically allowed. This is done based on the VPC’s CIDR range. Default: true

  • private_dns_enabled (Optional[bool]) – Whether to associate a private hosted zone with the specified VPC. This allows you to make requests to the service using its default DNS hostname. Default: set by the instance of IInterfaceVpcEndpointService, or true if not defined by the instance of IInterfaceVpcEndpointService

  • security_groups (Optional[Sequence[ISecurityGroup]]) – The security groups to associate with this interface VPC endpoint. Default: - a new security group is created

  • subnets (Union[SubnetSelection, Dict[str, Any], None]) – The subnets in which to create an endpoint network interface. At most one per availability zone. Default: - private subnets

Return type


add_vpn_connection(id, *, ip, asn=None, static_routes=None, tunnel_options=None)

Adds a new VPN connection to this VPC.

  • id (str) –

  • ip (str) – The ip address of the customer gateway.

  • asn (Union[int, float, None]) – The ASN of the customer gateway. Default: 65000

  • static_routes (Optional[Sequence[str]]) – The static routes to be routed from the VPN gateway to the customer gateway. Default: Dynamic routing (BGP)

  • tunnel_options (Optional[Sequence[Union[VpnTunnelOption, Dict[str, Any]]]]) – The tunnel options for the VPN connection. At most two elements (one per tunnel). Duplicates not allowed. Default: Amazon generated tunnel options

Return type



Apply the given removal policy to this resource.

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you’ve removed it from the CDK application or because you’ve made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).


policy (RemovalPolicy) –

Return type


enable_vpn_gateway(*, vpn_route_propagation=None, type, amazon_side_asn=None)

Adds a VPN Gateway to this VPC.

  • vpn_route_propagation (Optional[Sequence[Union[SubnetSelection, Dict[str, Any]]]]) – Provide an array of subnets where the route propagation should be added. Default: noPropagation

  • type (str) – Default type ipsec.1.

  • amazon_side_asn (Union[int, float, None]) – Explicitly specify an Asn or let aws pick an Asn for you. Default: 65000

Return type


select_subnets(*, availability_zones=None, one_per_az=None, subnet_filters=None, subnet_group_name=None, subnets=None, subnet_type=None)

Returns IDs of selected subnets.

  • availability_zones (Optional[Sequence[str]]) – Select subnets only in the given AZs. Default: no filtering on AZs is done

  • one_per_az (Optional[bool]) – If true, return at most one subnet per AZ. Default: false

  • subnet_filters (Optional[Sequence[SubnetFilter]]) – List of provided subnet filters. Default: - none

  • subnet_group_name (Optional[str]) – Select the subnet group with the given name. Select the subnet group with the given name. This only needs to be used if you have multiple subnet groups of the same type and you need to distinguish between them. Otherwise, prefer subnetType. This field does not select individual subnets, it selects all subnets that share the given subnet group name. This is the name supplied in subnetConfiguration. At most one of subnetType and subnetGroupName can be supplied. Default: - Selection by type instead of by name

  • subnets (Optional[Sequence[ISubnet]]) – Explicitly select individual subnets. Use this if you don’t want to automatically use all subnets in a group, but have a need to control selection down to individual subnets. Cannot be specified together with subnetType or subnetGroupName. Default: - Use all subnets in a selected group (all private subnets by default)

  • subnet_type (Optional[SubnetType]) – Select all subnets of the given type. At most one of subnetType and subnetGroupName can be supplied. Default: SubnetType.PRIVATE_WITH_EGRESS (or ISOLATED or PUBLIC if there are no PRIVATE_WITH_EGRESS subnets)

Return type



Returns a string representation of this construct.

Return type



DEFAULT_SUBNETS = [SubnetConfiguration(name='Public', subnet_type=<SubnetType.PUBLIC: 'PUBLIC'>), SubnetConfiguration(name='Private', subnet_type=<SubnetType.PRIVATE_WITH_EGRESS: 'PRIVATE_WITH_EGRESS'>)]
DEFAULT_SUBNETS_NO_NAT = [SubnetConfiguration(name='Public', subnet_type=<SubnetType.PUBLIC: 'PUBLIC'>), SubnetConfiguration(name='Isolated', subnet_type=<SubnetType.PRIVATE_ISOLATED: 'PRIVATE_ISOLATED'>)]

AZs for this VPC.


Indicates if instances launched in this VPC will have public DNS hostnames.


Indicates if DNS support is enabled for this VPC.


The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.


Dependencies for internet connectivity.


Internet Gateway for the VPC.

Note that in case the VPC is configured only with ISOLATED subnets, this attribute will be undefined.


List of isolated subnets in this VPC.


The tree node.


List of private subnets in this VPC.


List of public subnets in this VPC.


The stack in which this resource is defined.


Arn of this VPC.




CIDR range for this VPC.
















Identifier for this VPC.






Returns the id of the VPN Gateway (if enabled).

Static Methods

classmethod from_lookup(scope, id, *, is_default=None, region=None, subnet_group_name_tag=None, tags=None, vpc_id=None, vpc_name=None)

Import an existing VPC by querying the AWS environment this stack is deployed to.

This function only needs to be used to use VPCs not defined in your CDK application. If you are looking to share a VPC between stacks, you can pass the Vpc object between stacks and use it as normal.

Calling this method will lead to a lookup when the CDK CLI is executed. You can therefore not use any values that will only be available at CloudFormation execution time (i.e., Tokens).

The VPC information will be cached in cdk.context.json and the same VPC will be used on future runs. To refresh the lookup, you will have to evict the value from the cache using the cdk context command. See https://docs.aws.amazon.com/cdk/latest/guide/context.html for more information.

  • scope (Construct) –

  • id (str) –

  • is_default (Optional[bool]) – Whether to match the default VPC. Default: Don’t care whether we return the default VPC

  • region (Optional[str]) – Optional to override inferred region. Default: Current stack’s environment region

  • subnet_group_name_tag (Optional[str]) – Optional tag for subnet group name. If not provided, we’ll look at the aws-cdk:subnet-name tag. If the subnet does not have the specified tag, we’ll use its type as the name. Default: aws-cdk:subnet-name

  • tags (Optional[Mapping[str, str]]) – Tags on the VPC. The VPC must have all of these tags Default: Don’t filter on tags

  • vpc_id (Optional[str]) – The ID of the VPC. If given, will import exactly this VPC. Default: Don’t filter on vpcId

  • vpc_name (Optional[str]) – The name of the VPC. If given, will import the VPC with this name. Default: Don’t filter on vpcName

Return type


classmethod from_vpc_attributes(scope, id, *, availability_zones, vpc_id, isolated_subnet_ids=None, isolated_subnet_ipv4_cidr_blocks=None, isolated_subnet_names=None, isolated_subnet_route_table_ids=None, private_subnet_ids=None, private_subnet_ipv4_cidr_blocks=None, private_subnet_names=None, private_subnet_route_table_ids=None, public_subnet_ids=None, public_subnet_ipv4_cidr_blocks=None, public_subnet_names=None, public_subnet_route_table_ids=None, region=None, vpc_cidr_block=None, vpn_gateway_id=None)

Import a VPC by supplying all attributes directly.

NOTE: using fromVpcAttributes() with deploy-time parameters (like a Fn.importValue() or CfnParameter to represent a list of subnet IDs) sometimes accidentally works. It happens to work for constructs that need a list of subnets (like AutoScalingGroup and eks.Cluster) but it does not work for constructs that need individual subnets (like Instance). See https://github.com/aws/aws-cdk/issues/4118 for more information.

Prefer to use Vpc.fromLookup() instead.

  • scope (Construct) –

  • id (str) –

  • availability_zones (Sequence[str]) – List of availability zones for the subnets in this VPC.

  • vpc_id (str) – VPC’s identifier.

  • isolated_subnet_ids (Optional[Sequence[str]]) – List of isolated subnet IDs. Must be undefined or match the availability zones in length and order. Default: - The VPC does not have any isolated subnets

  • isolated_subnet_ipv4_cidr_blocks (Optional[Sequence[str]]) – List of IPv4 CIDR blocks for the isolated subnets. Must be undefined or have an entry for every isolated subnet group. Default: - Retrieving the IPv4 CIDR block of any isolated subnet will fail

  • isolated_subnet_names (Optional[Sequence[str]]) – List of names for the isolated subnets. Must be undefined or have a name for every isolated subnet group. Default: - All isolated subnets will have the name Isolated

  • isolated_subnet_route_table_ids (Optional[Sequence[str]]) – List of IDs of route tables for the isolated subnets. Must be undefined or have a name for every isolated subnet group. Default: - Retrieving the route table ID of any isolated subnet will fail

  • private_subnet_ids (Optional[Sequence[str]]) – List of private subnet IDs. Must be undefined or match the availability zones in length and order. Default: - The VPC does not have any private subnets

  • private_subnet_ipv4_cidr_blocks (Optional[Sequence[str]]) – List of IPv4 CIDR blocks for the private subnets. Must be undefined or have an entry for every private subnet group. Default: - Retrieving the IPv4 CIDR block of any private subnet will fail

  • private_subnet_names (Optional[Sequence[str]]) – List of names for the private subnets. Must be undefined or have a name for every private subnet group. Default: - All private subnets will have the name Private

  • private_subnet_route_table_ids (Optional[Sequence[str]]) – List of IDs of route tables for the private subnets. Must be undefined or have a name for every private subnet group. Default: - Retrieving the route table ID of any private subnet will fail

  • public_subnet_ids (Optional[Sequence[str]]) – List of public subnet IDs. Must be undefined or match the availability zones in length and order. Default: - The VPC does not have any public subnets

  • public_subnet_ipv4_cidr_blocks (Optional[Sequence[str]]) – List of IPv4 CIDR blocks for the public subnets. Must be undefined or have an entry for every public subnet group. Default: - Retrieving the IPv4 CIDR block of any public subnet will fail

  • public_subnet_names (Optional[Sequence[str]]) – List of names for the public subnets. Must be undefined or have a name for every public subnet group. Default: - All public subnets will have the name Public

  • public_subnet_route_table_ids (Optional[Sequence[str]]) – List of IDs of route tables for the public subnets. Must be undefined or have a name for every public subnet group. Default: - Retrieving the route table ID of any public subnet will fail

  • region (Optional[str]) – The region the VPC is in. Default: - The region of the stack where the VPC belongs to

  • vpc_cidr_block (Optional[str]) – VPC’s CIDR range. Default: - Retrieving the CIDR from the VPC will fail

  • vpn_gateway_id (Optional[str]) – VPN gateway’s identifier.

Return type


classmethod is_construct(x)

Checks if x is a construct.

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.


x (Any) – Any object.

Return type



true if x is an object created from a class which extends Construct.

classmethod is_owned_resource(construct)

Returns true if the construct was created by CDK, and false otherwise.


construct (IConstruct) –

Return type


classmethod is_resource(construct)

Check whether the given construct is a Resource.


construct (IConstruct) –

Return type