aws-cdk-lib.aws_ec2.Vpc

class Vpc (construct)

LanguageType name
.NETAmazon.CDK.AWS.EC2.Vpc
Gogithub.com/aws/aws-cdk-go/awscdk/v2/awsec2#Vpc
Javasoftware.amazon.awscdk.services.ec2.Vpc
Pythonaws_cdk.aws_ec2.Vpc
TypeScript (source)aws-cdk-lib » aws_ec2 » Vpc

Implements IConstruct, IDependable, IResource, IVpc

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:

const vpc = new ec2.Vpc(this, 'TheVPC', {
  ipAddresses: ec2.IpAddresses.cidr('10.0.0.0/16'),
})

// Iterate the private subnets
const selection = vpc.selectSubnets({
  subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS
});

for (const subnet of selection.subnets) {
  // ...
}

Example

import * as ec2 from 'aws-cdk-lib/aws-ec2';

const vpc = new ec2.Vpc(this, 'Vpc', {
  ipAddresses: ec2.IpAddresses.cidr('10.0.0.0/16')
});

const vpcConnector = new apprunner.VpcConnector(this, 'VpcConnector', {
  vpc,
  vpcSubnets: vpc.selectSubnets({ subnetType: ec2.SubnetType.PUBLIC }),
  vpcConnectorName: 'MyVpcConnector',
});

new apprunner.Service(this, 'Service', {
  source: apprunner.Source.fromEcrPublic({
    imageConfiguration: { port: 8000 },
    imageIdentifier: 'public.ecr.aws/aws-containers/hello-app-runner:latest',
  }),
  vpcConnector,
});

Initializer

new Vpc(scope: Construct, id: string, props?: VpcProps)

Parameters

  • scope Construct
  • id string
  • props VpcProps

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).

Construct Props

NameTypeDescription
availabilityZones?string[]Availability zones this VPC spans.
cidr?⚠️stringThe CIDR range to use for the VPC, e.g. '10.0.0.0/16'.
defaultInstanceTenancy?DefaultInstanceTenancyThe default tenancy of instances launched into the VPC.
enableDnsHostnames?booleanIndicates whether the instances launched in the VPC get public DNS hostnames.
enableDnsSupport?booleanIndicates whether the DNS resolution is supported for the VPC.
flowLogs?{ [string]: FlowLogOptions }Flow logs to add to this VPC.
gatewayEndpoints?{ [string]: GatewayVpcEndpointOptions }Gateway endpoints to add to this VPC.
ipAddresses?IIpAddressesThe Provider to use to allocate IP Space to your VPC.
maxAzs?numberDefine the maximum number of AZs to use in this region.
natGatewayProvider?NatProviderWhat type of NAT provider to use.
natGatewaySubnets?SubnetSelectionConfigures the subnets which will have NAT Gateways/Instances.
natGateways?numberThe number of NAT Gateways/Instances to create.
reservedAzs?numberDefine the number of AZs to reserve.
restrictDefaultSecurityGroup?booleanIf set to true then the default inbound & outbound rules will be removed from the default security group.
subnetConfiguration?SubnetConfiguration[]Configure the subnets to build for each AZ.
vpcName?stringThe VPC name.
vpnConnections?{ [string]: VpnConnectionOptions }VPN connections to this VPC.
vpnGateway?booleanIndicates whether a VPN gateway should be created and attached to this VPC.
vpnGatewayAsn?numberThe private Autonomous System Number (ASN) for the VPN gateway.
vpnRoutePropagation?SubnetSelection[]Where to propagate VPN routes.

availabilityZones?

Type: string[] (optional, default: a subset of AZs of the stack)

Availability zones this VPC spans.

Specify this option only if you do not specify maxAzs.


cidr?⚠️

⚠️ Deprecated: Use ipAddresses instead

Type: string (optional, default: Vpc.DEFAULT_CIDR_RANGE)

The CIDR range to use for the VPC, e.g. '10.0.0.0/16'.

Should be a minimum of /28 and maximum size of /16. The range will be split across all subnets per Availability Zone.


defaultInstanceTenancy?

Type: DefaultInstanceTenancy (optional, default: DefaultInstanceTenancy.Default (shared) tenancy)

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.


enableDnsHostnames?

Type: boolean (optional, default: true)

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.


enableDnsSupport?

Type: boolean (optional, default: true)

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 169.254.169.253 IP address, or the reserved IP address at the base of the VPC IPv4 network range plus two will succeed.


flowLogs?

Type: { [string]: FlowLogOptions } (optional, default: No flow logs.)

Flow logs to add to this VPC.


gatewayEndpoints?

Type: { [string]: GatewayVpcEndpointOptions } (optional, default: None.)

Gateway endpoints to add to this VPC.


ipAddresses?

Type: IIpAddresses (optional, default: ec2.IpAddresses.cidr)

The Provider to use to allocate IP Space to your VPC.

Options include static allocation or from a pool.


maxAzs?

Type: number (optional, default: 3)

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.


natGatewayProvider?

Type: NatProvider (optional, default: NatProvider.gateway())

What type of NAT provider to use.

Select between NAT gateways or NAT instances. NAT gateways may not be available in all AWS regions.


natGatewaySubnets?

Type: SubnetSelection (optional, default: All public subnets.)

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.


natGateways?

Type: number (optional, default: One NAT gateway/instance per Availability Zone)

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.


reservedAzs?

Type: number (optional, default: 0)

Define the number of AZs to reserve.

When specified, the IP space is reserved for the azs but no actual resources are provisioned.


restrictDefaultSecurityGroup?

Type: boolean (optional, default: true if '@aws-cdk/aws-ec2:restrictDefaultSecurityGroup' is enabled, false otherwise)

If set to true then the default inbound & outbound rules will be removed from the default security group.


subnetConfiguration?

Type: SubnetConfiguration[] (optional, default: The VPC CIDR will be evenly divided between 1 public and 1 private subnet per AZ.)

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,
     }
  ]
});

vpcName?

Type: string (optional, default: this.node.path)

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


vpnConnections?

Type: { [string]: VpnConnectionOptions } (optional, default: No connections.)

VPN connections to this VPC.


vpnGateway?

Type: boolean (optional, default: true when vpnGatewayAsn or vpnConnections is specified)

Indicates whether a VPN gateway should be created and attached to this VPC.


vpnGatewayAsn?

Type: number (optional, default: Amazon default ASN.)

The private Autonomous System Number (ASN) for the VPN gateway.


vpnRoutePropagation?

Type: SubnetSelection[] (optional, 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.)

Where to propagate VPN routes.

Properties

NameTypeDescription
availabilityZonesstring[]AZs for this VPC.
dnsHostnamesEnabledbooleanIndicates if instances launched in this VPC will have public DNS hostnames.
dnsSupportEnabledbooleanIndicates if DNS support is enabled for this VPC.
envResourceEnvironmentThe environment this resource belongs to.
incompleteSubnetDefinitionbooleanIf this is set to true, don't error out on trying to select subnets.
internetConnectivityEstablishedIDependableDependencies for internet connectivity.
isolatedSubnetsISubnet[]List of isolated subnets in this VPC.
nodeNodeThe tree node.
privateSubnetsISubnet[]List of private subnets in this VPC.
publicSubnetsISubnet[]List of public subnets in this VPC.
stackStackThe stack in which this resource is defined.
vpcArnstringArn of this VPC.
vpcCidrBlockstringCIDR range for this VPC.
vpcCidrBlockAssociationsstring[]
vpcDefaultNetworkAclstring
vpcDefaultSecurityGroupstring
vpcIdstringIdentifier for this VPC.
vpcIpv6CidrBlocksstring[]
internetGatewayId?stringInternet Gateway for the VPC.
vpnGatewayId?stringReturns the id of the VPN Gateway (if enabled).
static DEFAULT_CIDR_RANGEstringThe default CIDR range used when creating VPCs.
static DEFAULT_SUBNETSSubnetConfiguration[]The default subnet configuration.
static DEFAULT_SUBNETS_NO_NATSubnetConfiguration[]The default subnet configuration if natGateways specified to be 0.

availabilityZones

Type: string[]

AZs for this VPC.


dnsHostnamesEnabled

Type: boolean

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


dnsSupportEnabled

Type: boolean

Indicates if DNS support is enabled for this VPC.


env

Type: ResourceEnvironment

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.


incompleteSubnetDefinition

Type: boolean

If this is set to true, don't error out on trying to select subnets.


internetConnectivityEstablished

Type: IDependable

Dependencies for internet connectivity.


isolatedSubnets

Type: ISubnet[]

List of isolated subnets in this VPC.


node

Type: Node

The tree node.


privateSubnets

Type: ISubnet[]

List of private subnets in this VPC.


publicSubnets

Type: ISubnet[]

List of public subnets in this VPC.


stack

Type: Stack

The stack in which this resource is defined.


vpcArn

Type: string

Arn of this VPC.


vpcCidrBlock

Type: string

CIDR range for this VPC.


vpcCidrBlockAssociations

Type: string[]


vpcDefaultNetworkAcl

Type: string


vpcDefaultSecurityGroup

Type: string


vpcId

Type: string

Identifier for this VPC.


vpcIpv6CidrBlocks

Type: string[]


internetGatewayId?

Type: string (optional)

Internet Gateway for the VPC.

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


vpnGatewayId?

Type: string (optional)

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


static DEFAULT_CIDR_RANGE

Type: string

The default CIDR range used when creating VPCs.

This can be overridden using VpcProps when creating a VPCNetwork resource. e.g. new VpcResource(this, { cidr: '192.168.0.0./16' })


static DEFAULT_SUBNETS

Type: SubnetConfiguration[]

The default subnet configuration.

1 Public and 1 Private subnet per AZ evenly split


static DEFAULT_SUBNETS_NO_NAT

Type: SubnetConfiguration[]

The default subnet configuration if natGateways specified to be 0.

1 Public and 1 Isolated Subnet per AZ evenly split

Methods

NameDescription
addClientVpnEndpoint(id, options)Adds a new client VPN endpoint to this VPC.
addFlowLog(id, options?)Adds a new flow log to this VPC.
addGatewayEndpoint(id, options)Adds a new gateway endpoint to this VPC.
addInterfaceEndpoint(id, options)Adds a new interface endpoint to this VPC.
addVpnConnection(id, options)Adds a new VPN connection to this VPC.
applyRemovalPolicy(policy)Apply the given removal policy to this resource.
enableVpnGateway(options)Adds a VPN Gateway to this VPC.
selectSubnets(selection?)Returns IDs of selected subnets.
toString()Returns a string representation of this construct.
protected selectSubnetObjects(selection?)Return the subnets appropriate for the placement strategy.
static fromLookup(scope, id, options)Import an existing VPC by querying the AWS environment this stack is deployed to.
static fromVpcAttributes(scope, id, attrs)Import a VPC by supplying all attributes directly.

addClientVpnEndpoint(id, options)

public addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint

Parameters

  • id string
  • options ClientVpnEndpointOptions

Returns

  • ClientVpnEndpoint

Adds a new client VPN endpoint to this VPC.


addFlowLog(id, options?)

public addFlowLog(id: string, options?: FlowLogOptions): FlowLog

Parameters

  • id string
  • options FlowLogOptions

Returns

  • FlowLog

Adds a new flow log to this VPC.


addGatewayEndpoint(id, options)

public addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint

Parameters

  • id string
  • options GatewayVpcEndpointOptions

Returns

  • GatewayVpcEndpoint

Adds a new gateway endpoint to this VPC.


addInterfaceEndpoint(id, options)

public addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint

Parameters

  • id string
  • options InterfaceVpcEndpointOptions

Returns

  • InterfaceVpcEndpoint

Adds a new interface endpoint to this VPC.


addVpnConnection(id, options)

public addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection

Parameters

  • id string
  • options VpnConnectionOptions

Returns

  • VpnConnection

Adds a new VPN connection to this VPC.


applyRemovalPolicy(policy)

public applyRemovalPolicy(policy: RemovalPolicy): void

Parameters

  • policy RemovalPolicy

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).


enableVpnGateway(options)

public enableVpnGateway(options: EnableVpnGatewayOptions): void

Parameters

  • options EnableVpnGatewayOptions

Adds a VPN Gateway to this VPC.


selectSubnets(selection?)

public selectSubnets(selection?: SubnetSelection): SelectedSubnets

Parameters

  • selection SubnetSelection

Returns

  • SelectedSubnets

Returns IDs of selected subnets.


toString()

public toString(): string

Returns

  • string

Returns a string representation of this construct.


protected selectSubnetObjects(selection?)

protected selectSubnetObjects(selection?: SubnetSelection): ISubnet[]

Parameters

  • selection SubnetSelection

Returns

  • ISubnet[]

Return the subnets appropriate for the placement strategy.


static fromLookup(scope, id, options)

public static fromLookup(scope: Construct, id: string, options: VpcLookupOptions): IVpc

Parameters

  • scope Construct
  • id string
  • options VpcLookupOptions

Returns

  • IVpc

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.


static fromVpcAttributes(scope, id, attrs)

public static fromVpcAttributes(scope: Construct, id: string, attrs: VpcAttributes): IVpc

Parameters

  • scope Construct
  • id string
  • attrs VpcAttributes

Returns

  • IVpc

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.