# Vpc

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:

```ts
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) {
  // ...
}
```

Extends: Construct › Resource › Vpc
Implements: IResource, IVpc, IEnvironmentAware, IVPCRef, IConstruct, IDependable

- CloudFormation: [`AWS::EC2::VPC`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-vpc.html)
- L1 type: [`CfnVPC`](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CfnVPC.html)
- Source: [`aws-ec2/lib/vpc.ts`](https://github.com/aws/aws-cdk/blob/v2.275.0/packages/aws-cdk-lib/aws-ec2/lib/vpc.ts#L1323)
- Type last changed: v2.224.0 · 13 Nov 2025

## Example

```ts
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

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

## Construct Props

- `availabilityZones`: string[] — Availability zones this VPC spans.

  **Default:** a subset of AZs of the stack

  Specify this option only if you do not specify `maxAzs`.

- `cidr`: string = Vpc.DEFAULT_CIDR_RANGE — Use ipAddresses instead

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

- `createInternetGateway`: boolean = true — If set to false then disable the creation of the default internet gateway.

- `defaultInstanceTenancy`: [DefaultInstanceTenancy](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.DefaultInstanceTenancy.html) — The default tenancy of instances launched into the VPC.

  **Default:** DefaultInstanceTenancy.Default (shared) tenancy

  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`: boolean = 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`: boolean = 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`: { [key: string]: [FlowLogOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.FlowLogOptions.html) } — Flow logs to add to this VPC.

  **Default:** No flow logs.

- `gatewayEndpoints`: { [key: string]: [GatewayVpcEndpointOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.GatewayVpcEndpointOptions.html) } = None. — Gateway endpoints to add to this VPC.

- `ipAddresses`: [IIpAddresses](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IIpAddresses.html) = ec2.IpAddresses.cidr — The Provider to use to allocate IPv4 Space to your VPC.

  Options include static allocation or from a pool.

  Note this is specific to IPv4 addresses.

- `ipProtocol`: [IpProtocol](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IpProtocol.html) = IpProtocol.IPV4_ONLY — The protocol of the vpc.

  Options are IPv4 only or dual stack.

- `ipv6Addresses`: [IIpv6Addresses](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IIpv6Addresses.html) = Ipv6Addresses.amazonProvided — The Provider to use to allocate IPv6 Space to your VPC.

  Options include amazon provided CIDR block.

  Note this is specific to IPv6 addresses.

- `maxAzs`: number = 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`: [NatProvider](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.NatProvider.html) = 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.

- `natGateways`: number — The number of NAT Gateways/Instances to create.

  **Default:** One NAT gateway/instance per Availability Zone

  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.

- `natGatewaySubnets`: [SubnetSelection](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SubnetSelection.html) — Configures the subnets which will have NAT Gateways/Instances.

  **Default:** All public subnets.

  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.

- `reservedAzs`: number = 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`: boolean — If set to true then the default inbound & outbound rules will be removed from the default security group.

  **Default:** true if '@aws-cdk/aws-ec2:restrictDefaultSecurityGroup' is enabled, false otherwise

- `subnetConfiguration`: [SubnetConfiguration](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SubnetConfiguration.html)[] — Configure the subnets to build for each AZ.

  **Default:** The VPC CIDR will be evenly divided between 1 public and 1 private subnet per 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:

  ```ts
  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`: string = 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`: { [key: string]: [VpnConnectionOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.VpnConnectionOptions.html) } — VPN connections to this VPC.

  **Default:** No connections.

- `vpnGateway`: boolean — Indicates whether a VPN gateway should be created and attached to this VPC.

  **Default:** true when vpnGatewayAsn or vpnConnections is specified

- `vpnGatewayAsn`: number — The private Autonomous System Number (ASN) for the VPN gateway.

  **Default:** Amazon default ASN.

- `vpnRoutePropagation`: [SubnetSelection](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SubnetSelection.html)[] — 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.

## Properties

- `availabilityZones`: string[] — AZs for this VPC.

- `DEFAULT_CIDR_RANGE`: string (static) — 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' })

  Note this is specific to the IPv4 CIDR.

- `DEFAULT_SUBNETS`: [SubnetConfiguration](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SubnetConfiguration.html)[] (static) — The default subnet configuration.

  1 Public and 1 Private subnet per AZ evenly split

- `DEFAULT_SUBNETS_NO_NAT`: [SubnetConfiguration](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SubnetConfiguration.html)[] (static) — The default subnet configuration if natGateways specified to be 0.

  1 Public and 1 Isolated Subnet per AZ evenly split

- `dnsHostnamesEnabled`: boolean — Indicates if instances launched in this VPC will have public DNS hostnames.

- `dnsSupportEnabled`: boolean — Indicates if DNS support is enabled for this VPC.

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) — The environment this resource belongs to.

  For resources that are created and managed in a Stack (those created by
  creating new class instances like `new Role()`, `new Bucket()`, etc.), this
  is always the same as the environment of the stack they belong to.

  For referenced resources (those obtained from referencing methods like
  `Role.fromRoleArn()`, `Bucket.fromBucketName()`, etc.), they might be
  different than the stack they were imported into.

- `internetConnectivityEstablished`: [IDependable](/cdk/api/v2/docs/constructs.IDependable.html) — Dependencies for internet connectivity.

- `internetGatewayId`: string — Internet Gateway for the VPC.

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

- `isolatedSubnets`: [ISubnet](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.ISubnet.html)[] — List of isolated subnets in this VPC.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) — The tree node.

- `privateSubnets`: [ISubnet](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.ISubnet.html)[] — List of private subnets in this VPC.

- `PROPERTY_INJECTION_ID`: string (static) — Uniquely identifies this class.

- `publicSubnets`: [ISubnet](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.ISubnet.html)[] — List of public subnets in this VPC.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) — The stack in which this resource is defined.

- `vpcArn`: string — Arn of this VPC.

- `vpcCidrBlock`: string — CIDR range for this VPC.

- `vpcCidrBlockAssociations`: string[]

- `vpcDefaultNetworkAcl`: string

- `vpcDefaultSecurityGroup`: string

- `vpcId`: string — Identifier for this VPC.

- `vpcIpv6CidrBlocks`: string[]

- `vpcRef`: [VPCReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_ec2.VPCReference.html) — A reference to a VPC resource.

- `vpnGatewayId`: string — Returns the id of the VPN Gateway (if enabled).

## Methods

- `addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint` — Adds a new client VPN endpoint to this VPC.

- `addFlowLog(id: string, options?: FlowLogOptions): FlowLog` — Adds a new flow log to this VPC.

- `addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint` — Adds a new gateway endpoint to this VPC.

- `addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint` — Adds a new interface endpoint to this VPC.

- `addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection` — Adds a new VPN connection to this VPC.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  When set, any cross-stack reference to this resource will use the specified
  mechanism instead of the global default determined by the
  `@aws-cdk/core:defaultCrossStackReferences` context key. This is useful for
  selectively weakening specific references to avoid the "deadly embrace" problem
  without changing the app-wide default.

  **Parameters**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — 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: EnableVpnGatewayOptions): void` — Adds a VPN Gateway to this VPC.

- `fromLookup(scope: Construct, id: string, options: VpcLookupOptions): IVpc` (static) — 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.

- `fromVpcAttributes(scope: Construct, id: string, attrs: VpcAttributes): IVpc` (static) — 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.

- `isConstruct(x: any): boolean` (static) — 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.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `selectSubnets(selection?: SubnetSelection): SelectedSubnets` — Returns IDs of selected subnets.

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.
