class Vpc (construct)
Language | Type name |
---|---|
![]() | Amazon.CDK.AWS.EC2.Vpc |
![]() | github.com/aws/aws-cdk-go/awscdk/v2/awsec2#Vpc |
![]() | software.amazon.awscdk.services.ec2.Vpc |
![]() | aws_cdk.aws_ec2.Vpc |
![]() | 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
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
Name | Type | Description |
---|---|---|
availability | string[] | Availability zones this VPC spans. |
cidr? | string | The CIDR range to use for the VPC, e.g. '10.0.0.0/16'. |
create | boolean | If set to false then disable the creation of the default internet gateway. |
default | Default | The default tenancy of instances launched into the VPC. |
enable | boolean | Indicates whether the instances launched in the VPC get public DNS hostnames. |
enable | boolean | Indicates whether the DNS resolution is supported for the VPC. |
flow | { [string]: Flow } | Flow logs to add to this VPC. |
gateway | { [string]: Gateway } | Gateway endpoints to add to this VPC. |
ip | IIp | The Provider to use to allocate IPv4 Space to your VPC. |
ip | Ip | The protocol of the vpc. |
ipv6 | IIpv6 | The Provider to use to allocate IPv6 Space to your VPC. |
max | number | Define the maximum number of AZs to use in this region. |
nat | Nat | What type of NAT provider to use. |
nat | Subnet | Configures the subnets which will have NAT Gateways/Instances. |
nat | number | The number of NAT Gateways/Instances to create. |
reserved | number | Define the number of AZs to reserve. |
restrict | boolean | If set to true then the default inbound & outbound rules will be removed from the default security group. |
subnet | Subnet [] | Configure the subnets to build for each AZ. |
vpc | string | The VPC name. |
vpn | { [string]: Vpn } | VPN connections to this VPC. |
vpn | boolean | Indicates whether a VPN gateway should be created and attached to this VPC. |
vpn | number | The private Autonomous System Number (ASN) for the VPN gateway. |
vpn | Subnet [] | 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.
createInternetGateway?
Type:
boolean
(optional, default: true)
If set to false then disable the creation of the default internet gateway.
defaultInstanceTenancy?
Type:
Default
(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]:
Flow
}
(optional, default: No flow logs.)
Flow logs to add to this VPC.
gatewayEndpoints?
Type:
{ [string]:
Gateway
}
(optional, default: None.)
Gateway endpoints to add to this VPC.
ipAddresses?
Type:
IIp
(optional, default: 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?
Type:
Ip
(optional, default: IpProtocol.IPV4_ONLY)
The protocol of the vpc.
Options are IPv4 only or dual stack.
ipv6Addresses?
Type:
IIpv6
(optional, default: 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?
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:
Nat
(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:
Subnet
(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:
Subnet
[]
(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]:
Vpn
}
(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:
Subnet
[]
(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
Name | Type | Description |
---|---|---|
availability | string[] | AZs for this VPC. |
dns | boolean | Indicates if instances launched in this VPC will have public DNS hostnames. |
dns | boolean | Indicates if DNS support is enabled for this VPC. |
env | Resource | The environment this resource belongs to. |
incomplete | boolean | If this is set to true, don't error out on trying to select subnets. |
internet | IDependable | Dependencies for internet connectivity. |
isolated | ISubnet [] | List of isolated subnets in this VPC. |
node | Node | The tree node. |
private | ISubnet [] | List of private subnets in this VPC. |
public | ISubnet [] | List of public subnets in this VPC. |
stack | Stack | The stack in which this resource is defined. |
vpc | string | Arn of this VPC. |
vpc | string | CIDR range for this VPC. |
vpc | string[] | |
vpc | string | |
vpc | string | |
vpc | string | Identifier for this VPC. |
vpc | string[] | |
internet | string | Internet Gateway for the VPC. |
vpn | string | Returns the id of the VPN Gateway (if enabled). |
static DEFAULT_CIDR_RANGE | string | The default CIDR range used when creating VPCs. |
static DEFAULT_SUBNETS | Subnet [] | The default subnet configuration. |
static DEFAULT_SUBNETS_NO_NAT | Subnet [] | 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:
Resource
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' })
Note this is specific to the IPv4 CIDR.
static DEFAULT_SUBNETS
Type:
Subnet
[]
The default subnet configuration.
1 Public and 1 Private subnet per AZ evenly split
static DEFAULT_SUBNETS_NO_NAT
Type:
Subnet
[]
The default subnet configuration if natGateways specified to be 0.
1 Public and 1 Isolated Subnet per AZ evenly split
Methods
Name | Description |
---|---|
add | Adds a new client VPN endpoint to this VPC. |
add | Adds a new flow log to this VPC. |
add | Adds a new gateway endpoint to this VPC. |
add | Adds a new interface endpoint to this VPC. |
add | Adds a new VPN connection to this VPC. |
apply | Apply the given removal policy to this resource. |
enable | Adds a VPN Gateway to this VPC. |
select | Returns IDs of selected subnets. |
to | Returns a string representation of this construct. |
protected select | Return the subnets appropriate for the placement strategy. |
static from | Import an existing VPC by querying the AWS environment this stack is deployed to. |
static from | Import a VPC by supplying all attributes directly. |
ClientVpnEndpoint(id, options)
addpublic addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpoint
Parameters
- id
string
- options
Client
Vpn Endpoint Options
Returns
Adds a new client VPN endpoint to this VPC.
FlowLog(id, options?)
addpublic addFlowLog(id: string, options?: FlowLogOptions): FlowLog
Parameters
- id
string
- options
Flow
Log Options
Returns
Adds a new flow log to this VPC.
GatewayEndpoint(id, options)
addpublic addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpoint
Parameters
- id
string
- options
Gateway
Vpc Endpoint Options
Returns
Adds a new gateway endpoint to this VPC.
InterfaceEndpoint(id, options)
addpublic addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpoint
Parameters
- id
string
- options
Interface
Vpc Endpoint Options
Returns
Adds a new interface endpoint to this VPC.
VpnConnection(id, options)
addpublic addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnection
Parameters
- id
string
- options
Vpn
Connection Options
Returns
Adds a new VPN connection to this VPC.
RemovalPolicy(policy)
applypublic applyRemovalPolicy(policy: RemovalPolicy): void
Parameters
- policy
Removal
Policy
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
).
VpnGateway(options)
enablepublic enableVpnGateway(options: EnableVpnGatewayOptions): void
Parameters
- options
Enable
Vpn Gateway Options
Adds a VPN Gateway to this VPC.
Subnets(selection?)
selectpublic selectSubnets(selection?: SubnetSelection): SelectedSubnets
Parameters
- selection
Subnet
Selection
Returns
Returns IDs of selected subnets.
String()
topublic toString(): string
Returns
string
Returns a string representation of this construct.
SubnetObjects(selection?)
protected selectprotected selectSubnetObjects(selection?: SubnetSelection): ISubnet[]
Parameters
- selection
Subnet
Selection
Returns
ISubnet
[]
Return the subnets appropriate for the placement strategy.
Lookup(scope, id, options)
static frompublic static fromLookup(scope: Construct, id: string, options: VpcLookupOptions): IVpc
Parameters
- scope
Construct
- id
string
- options
Vpc
Lookup Options
Returns
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.
VpcAttributes(scope, id, attrs)
static frompublic static fromVpcAttributes(scope: Construct, id: string, attrs: VpcAttributes): IVpc
Parameters
- scope
Construct
- id
string
- attrs
Vpc
Attributes
Returns
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.