Skip to content
v2.273.0

VpcV2 L2 construct ​

This class provides a foundation for creating and configuring a VPC with advanced features such as IPAM (IP Address Management) and IPv6 support.

For more information, see the {@link https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html AWS CDK Documentation on VPCs}.

Example ​

ts
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc',{
      primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
      secondaryAddressBlocks: [IpAddresses.amazonProvidedIpv6({
      cidrBlockName: 'AmazonProvided',
    })]
    });

const eigw = new EgressOnlyInternetGateway(this, 'EIGW', {
  vpc: myVpc,
});

const routeTable = new RouteTable(this, 'RouteTable', {
  vpc: myVpc,
});

routeTable.addRoute('EIGW', '::/0', { gateway: eigw });
python
stack = Stack()
my_vpc = VpcV2(self, "Vpc",
    primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
    secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
        cidr_block_name="AmazonProvided"
    )]
)

eigw = EgressOnlyInternetGateway(self, "EIGW",
    vpc=my_vpc
)

route_table = RouteTable(self, "RouteTable",
    vpc=my_vpc
)

route_table.add_route("EIGW", "::/0", {"gateway": eigw})
java
Stack stack = new Stack();
VpcV2 myVpc = VpcV2.Builder.create(this, "Vpc")
        .primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
        .secondaryAddressBlocks(List.of(IpAddresses.amazonProvidedIpv6(SecondaryAddressProps.builder()
                .cidrBlockName("AmazonProvided")
                .build())))
        .build();

EgressOnlyInternetGateway eigw = EgressOnlyInternetGateway.Builder.create(this, "EIGW")
        .vpc(myVpc)
        .build();

RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
        .vpc(myVpc)
        .build();

routeTable.addRoute("EIGW", "::/0", Map.of("gateway", eigw));
csharp
// Install: dotnet add package Amazon.CDK.AWS.ec2.Alpha
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc", new VpcV2Props {
    PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16"),
    SecondaryAddressBlocks = new [] { IpAddresses.AmazonProvidedIpv6(new SecondaryAddressProps {
        CidrBlockName = "AmazonProvided"
    }) }
});

var eigw = new EgressOnlyInternetGateway(this, "EIGW", new EgressOnlyInternetGatewayProps {
    Vpc = myVpc
});

var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
    Vpc = myVpc
});

routeTable.AddRoute("EIGW", "::/0", new Dictionary<string, IRouteTarget?> { { "gateway", eigw } });
go
// Install: go get github.com/aws/aws-cdk-go/awsec2alpha/v2
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"), &VpcV2Props{
	PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.1.0.0/16")),
	SecondaryAddressBlocks: []IIpAddresses{
		awsec2alpha.IpAddresses_AmazonProvidedIpv6(&SecondaryAddressProps{
			CidrBlockName: jsii.String("AmazonProvided"),
		}),
	},
})

eigw := awsec2alpha.NewEgressOnlyInternetGateway(this, jsii.String("EIGW"), &EgressOnlyInternetGatewayProps{
	Vpc: myVpc,
})

routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
	Vpc: myVpc,
})

routeTable.AddRoute(jsii.String("EIGW"), jsii.String("::/0"), map[string]iRouteTarget{
	"gateway": eigw,
})

Initializer ​

ts
new VpcV2(scope: Construct, id: string, props?: VpcV2Props)
python
VpcV2(scope: Construct, id: str, props: typing.Optional[VpcV2Props] = None)
java
new VpcV2(Construct scope, String id, VpcV2Props props)
csharp
new VpcV2(Construct scope, string id, VpcV2Props? props = null)
go
NewVpcV2(Scope Construct, Id *string, Props VpcV2Props)

Construct Props ​

defaultInstanceTenancyDefaultInstanceTenancydefault_instance_tenancyDefaultInstanceTenancydefaultInstanceTenancyDefaultInstanceTenancyDefaultInstanceTenancyDefaultInstanceTenancyDefaultInstanceTenancyDefaultInstanceTenancy= DefaultInstanceTenancy.Default (…#
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

Default: DefaultInstanceTenancy.Default (shared) tenancy

enableDnsHostnamesbooleanenable_dns_hostnamesboolenableDnsHostnamesBooleanEnableDnsHostnamesboolEnableDnsHostnames*bool= true#
Indicates whether the instances launched in the VPC get DNS hostnames.
enableDnsSupportbooleanenable_dns_supportboolenableDnsSupportBooleanEnableDnsSupportboolEnableDnsSupport*bool= true#
Indicates whether the DNS resolution is supported for the VPC.
primaryAddressBlockIIpAddressesprimary_address_blockIIpAddressesprimaryAddressBlockIIpAddressesPrimaryAddressBlockIIpAddressesPrimaryAddressBlockIIpAddresses= Ipv4 CIDR Block ('10.0.0.0/16')#
A must IPv4 CIDR block for the VPC.
secondaryAddressBlocksIIpAddresses[]secondary_address_blockstyping.List[IIpAddresses]secondaryAddressBlocksList<IIpAddresses>SecondaryAddressBlocksIIpAddresses[]SecondaryAddressBlocks*[]IIpAddresses= No secondary IP address#
The secondary CIDR blocks associated with the VPC.

Can be IPv4 or IPv6, two IPv4 ranges must follow RFC#1918 convention For more information,

vpcNamestringvpc_namestrvpcNameStringVpcNamestringVpcName*string= autogenerated by CDK#
Physical name for the VPC.

Properties ​

availabilityZonesstring[]availability_zonestyping.List[str]availabilityZonesList<String>AvailabilityZonesstring[]AvailabilityZones*[]*stringrequired#
AZs for this VPC.
dnsHostnamesEnabledbooleandns_hostnames_enabledbooldnsHostnamesEnabledBooleanDnsHostnamesEnabledboolDnsHostnamesEnabled*boolrequired#
Indicates if instances launched in this VPC will have public DNS hostnames.
dnsSupportEnabledbooleandns_support_enabledbooldnsSupportEnabledBooleanDnsSupportEnabledboolDnsSupportEnabled*boolrequired#
Indicates if DNS support is enabled for this VPC.
egressOnlyInternetGatewayIdstringegress_only_internet_gateway_idstregressOnlyInternetGatewayIdStringEgressOnlyInternetGatewayIdstringEgressOnlyInternetGatewayId*string#
Returns the id of the Egress Only Internet Gateway (if enabled).
The environment this resource belongs to.
notes

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.

internetConnectivityEstablishedIDependableinternet_connectivity_establishedIDependableinternetConnectivityEstablishedIDependableInternetConnectivityEstablishedIDependableInternetConnectivityEstablishedIDependablerequired#
To define dependency on internet connectivity.
internetGatewayIdstringinternet_gateway_idstrinternetGatewayIdStringInternetGatewayIdstringInternetGatewayId*string#
Returns the id of the Internet Gateway (if enabled).
ipAddressesIIpAddressesip_addressesIIpAddressesipAddressesIIpAddressesIpAddressesIIpAddressesIpAddressesIIpAddressesrequired#
The provider of ipv4 addresses.
ipv4CidrBlockstringipv4_cidr_blockstripv4CidrBlockStringIpv4CidrBlockstringIpv4CidrBlock*stringrequired#
The primary IPv4 CIDR block associated with the VPC.

Needed in order to validate the vpc range of subnet current prop vpcCidrBlock refers to the token value For more information, see the {@link https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html#vpc-sizing-ipv4}.

ipv4IpamProvisionedCidrsstring[]ipv4_ipam_provisioned_cidrstyping.List[str]ipv4IpamProvisionedCidrsList<String>Ipv4IpamProvisionedCidrsstring[]Ipv4IpamProvisionedCidrs*[]*string#
IPv4 CIDR provisioned using IPAM pool Required to check for overlapping CIDRs after provisioning is complete under IPAM.
ipv6CidrBlocksstring[]ipv6_cidr_blockstyping.List[str]ipv6CidrBlocksList<String>Ipv6CidrBlocksstring[]Ipv6CidrBlocks*[]*stringrequired#
The IPv6 CIDR blocks for the VPC.
isolatedSubnetsISubnet[]isolated_subnetstyping.List[ISubnet]isolatedSubnetsList<ISubnet>IsolatedSubnetsISubnet[]IsolatedSubnets*[]ISubnetrequired#
Isolated Subnets that are part of this VPC.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
ownerAccountIdstringowner_account_idstrownerAccountIdStringOwnerAccountIdstringOwnerAccountId*stringrequired#
Identifier of the owner for this VPC.
privateSubnetsISubnet[]private_subnetstyping.List[ISubnet]privateSubnetsList<ISubnet>PrivateSubnetsISubnet[]PrivateSubnets*[]ISubnetrequired#
Public Subnets that are part of this VPC.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
publicSubnetsISubnet[]public_subnetstyping.List[ISubnet]publicSubnetsList<ISubnet>PublicSubnetsISubnet[]PublicSubnets*[]ISubnetrequired#
Public Subnets that are part of this VPC.
regionstringregionstrregionStringRegionstringRegion*stringrequired#
Region for this VPC.
resourceCfnVPCresourceCfnVPCresourceCfnVPCResourceCfnVPCResourceCfnVPCrequired#
The AWS CloudFormation resource representing the VPC.
secondaryCidrBlockIVPCCidrBlock[]secondary_cidr_blocktyping.List[IVPCCidrBlock]secondaryCidrBlockList<IVPCCidrBlock>SecondaryCidrBlockIVPCCidrBlock[]SecondaryCidrBlock*[]IVPCCidrBlock#
reference to all secondary blocks attached.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
useIpv6booleanuse_ipv6booluseIpv6BooleanUseIpv6boolUseIpv6*bool= falserequired#
For validation to define IPv6 subnets, set to true in case of Amazon Provided IPv6 cidr range if true, IPv6 addresses can be attached to the subnets.
vpcArnstringvpc_arnstrvpcArnStringVpcArnstringVpcArn*stringrequired#
Arn of this VPC.
vpcCidrBlockstringvpc_cidr_blockstrvpcCidrBlockStringVpcCidrBlockstringVpcCidrBlock*stringrequired#
CIDR range for this VPC.
vpcIdstringvpc_idstrvpcIdStringVpcIdstringVpcId*stringrequired#
Identifier for this VPC.
vpcNamestringvpc_namestrvpcNameStringVpcNamestringVpcName*string#
VpcName to be used for tagging its components.
A reference to a VPC resource.
vpnGatewayIdstringvpn_gateway_idstrvpnGatewayIdStringVpnGatewayIdstringVpnGatewayId*string#
Returns the id of the VPN Gateway (if enabled).

Methods ​

addClientVpnEndpoint(id: string, options: ClientVpnEndpointOptions): ClientVpnEndpointdef add_client_vpn_endpoint(self, id: str, options: ClientVpnEndpointOptions) -> ClientVpnEndpointpublic ClientVpnEndpoint addClientVpnEndpoint(String id, ClientVpnEndpointOptions options)public ClientVpnEndpoint AddClientVpnEndpoint(string id, ClientVpnEndpointOptions options)func AddClientVpnEndpoint(Id *string, Options ClientVpnEndpointOptions) ClientVpnEndpoint#
Adds a new client VPN endpoint to this VPC.
addEgressOnlyInternetGateway(options?: EgressOnlyInternetGatewayOptions): EgressOnlyInternetGatewaydef add_egress_only_internet_gateway(self, options: typing.Optional[EgressOnlyInternetGatewayOptions] = None) -> EgressOnlyInternetGatewaypublic EgressOnlyInternetGateway addEgressOnlyInternetGateway(EgressOnlyInternetGatewayOptions options)public EgressOnlyInternetGateway AddEgressOnlyInternetGateway(EgressOnlyInternetGatewayOptions? options = null)func AddEgressOnlyInternetGateway(Options EgressOnlyInternetGatewayOptions) EgressOnlyInternetGateway#
Adds a new Egress Only Internet Gateway to this VPC and defines a new route to the route table of given subnets.
addFlowLog(id: string, options?: FlowLogOptions): FlowLogdef add_flow_log(self, id: str, options: typing.Optional[FlowLogOptions] = None) -> FlowLogpublic FlowLog addFlowLog(String id, FlowLogOptions options)public FlowLog AddFlowLog(string id, FlowLogOptions? options = null)func AddFlowLog(Id *string, Options FlowLogOptions) FlowLog#
Adds a new flow log to this VPC.
addGatewayEndpoint(id: string, options: GatewayVpcEndpointOptions): GatewayVpcEndpointdef add_gateway_endpoint(self, id: str, options: GatewayVpcEndpointOptions) -> GatewayVpcEndpointpublic GatewayVpcEndpoint addGatewayEndpoint(String id, GatewayVpcEndpointOptions options)public GatewayVpcEndpoint AddGatewayEndpoint(string id, GatewayVpcEndpointOptions options)func AddGatewayEndpoint(Id *string, Options GatewayVpcEndpointOptions) GatewayVpcEndpoint#
Adds a new gateway endpoint to this VPC.
addInterfaceEndpoint(id: string, options: InterfaceVpcEndpointOptions): InterfaceVpcEndpointdef add_interface_endpoint(self, id: str, options: InterfaceVpcEndpointOptions) -> InterfaceVpcEndpointpublic InterfaceVpcEndpoint addInterfaceEndpoint(String id, InterfaceVpcEndpointOptions options)public InterfaceVpcEndpoint AddInterfaceEndpoint(string id, InterfaceVpcEndpointOptions options)func AddInterfaceEndpoint(Id *string, Options InterfaceVpcEndpointOptions) InterfaceVpcEndpoint#
Adds a new interface endpoint to this VPC.
addInternetGateway(options?: InternetGatewayOptions): InternetGatewaydef add_internet_gateway(self, options: typing.Optional[InternetGatewayOptions] = None) -> InternetGatewaypublic InternetGateway addInternetGateway(InternetGatewayOptions options)public InternetGateway AddInternetGateway(InternetGatewayOptions? options = null)func AddInternetGateway(Options InternetGatewayOptions) InternetGateway#
Adds a new Internet Gateway to this VPC.
addNatGateway(options: NatGatewayOptions): NatGatewaydef add_nat_gateway(self, options: NatGatewayOptions) -> NatGatewaypublic NatGateway addNatGateway(NatGatewayOptions options)public NatGateway AddNatGateway(NatGatewayOptions options)func AddNatGateway(Options NatGatewayOptions) NatGateway#
Adds a new NAT Gateway to the given subnet of this VPC of given subnets.
addVpnConnection(id: string, options: VpnConnectionOptions): VpnConnectiondef add_vpn_connection(self, id: str, options: VpnConnectionOptions) -> VpnConnectionpublic VpnConnection addVpnConnection(String id, VpnConnectionOptions options)public VpnConnection AddVpnConnection(string id, VpnConnectionOptions options)func AddVpnConnection(Id *string, Options VpnConnectionOptions) VpnConnection#
Adds a new VPN connection to this VPC.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

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

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

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

createAcceptorVpcRole(requestorAccountId: string): Roledef create_acceptor_vpc_role(self, requestor_account_id: str) -> Rolepublic Role createAcceptorVpcRole(String requestorAccountId)public Role CreateAcceptorVpcRole(string requestorAccountId)func CreateAcceptorVpcRole(RequestorAccountId *string) Role#
Creates peering connection role for acceptor VPC.
createPeeringConnection(id: string, options: VPCPeeringConnectionOptions): VPCPeeringConnectiondef create_peering_connection(self, id: str, options: VPCPeeringConnectionOptions) -> VPCPeeringConnectionpublic VPCPeeringConnection createPeeringConnection(String id, VPCPeeringConnectionOptions options)public VPCPeeringConnection CreatePeeringConnection(string id, VPCPeeringConnectionOptions options)func CreatePeeringConnection(Id *string, Options VPCPeeringConnectionOptions) VPCPeeringConnection#
Creates a peering connection.
enableVpnGateway(options: EnableVpnGatewayOptions): voiddef enable_vpn_gateway(self, options: EnableVpnGatewayOptions) -> Nonepublic void enableVpnGateway(EnableVpnGatewayOptions options)public void EnableVpnGateway(EnableVpnGatewayOptions options)func EnableVpnGateway(Options EnableVpnGatewayOptions)deprecated#
use enableVpnGatewayV2 for compatibility with VPCV2.Route
enableVpnGatewayV2(options: VPNGatewayV2Options): VPNGatewayV2def enable_vpn_gateway_v2(self, options: VPNGatewayV2Options) -> VPNGatewayV2public VPNGatewayV2 enableVpnGatewayV2(VPNGatewayV2Options options)public VPNGatewayV2 EnableVpnGatewayV2(VPNGatewayV2Options options)func EnableVpnGatewayV2(Options VPNGatewayV2Options) VPNGatewayV2#
Adds VPNGAtewayV2 to this VPC.
fromVpcV2Attributes(scope: Construct, id: string, attrs: VpcV2Attributes): IVpcV2@staticmethod def from_vpc_v2_attributes(scope: Construct, id: str, attrs: VpcV2Attributes) -> IVpcV2public static IVpcV2 fromVpcV2Attributes(Construct scope, String id, VpcV2Attributes attrs)public static IVpcV2 FromVpcV2Attributes(Construct scope, string id, VpcV2Attributes attrs)func FromVpcV2Attributes(Scope Construct, Id *string, Attrs VpcV2Attributes) IVpcV2static#
Create a VPC from existing attributes.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

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

  • xxxxX — Any object.

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

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
selectSubnets(selection?: SubnetSelection): SelectedSubnetsdef select_subnets(self, selection: typing.Optional[SubnetSelection] = None) -> SelectedSubnetspublic SelectedSubnets selectSubnets(SubnetSelection selection)public SelectedSubnets SelectSubnets(SubnetSelection? selection = null)func SelectSubnets(Selection SubnetSelection) SelectedSubnets#
Return information on the subnets appropriate for the given selection strategy.

Requires that at least one subnet is matched, throws a descriptive error message otherwise.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func 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.