Amazon VpcV2 Construct Library
Version 2.273.0-alpha.0
Separate package
@aws-cdk/aws-ec2-alpha is not part of aws-cdk-lib — install it separately:
npm install @aws-cdk/aws-ec2-alpha
pip install aws-cdk.aws-ec2-alpha
This module is experimental (alpha): its API may change in any release, without a major version bump.
The APIs of higher level constructs in this module are in developer preview before they become stable. We will only make breaking changes to address unforeseen API issues. Therefore, these APIs are not subject to Semantic Versioning, and breaking changes will be announced in release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.
VpcV2
VpcV2 is a re-write of the ec2.Vpc construct. This new construct enables higher level of customization on the VPC being created. VpcV2 implements the existing IVpc, therefore, VpcV2 is compatible with other constructs that accepts IVpc (e.g. ApplicationLoadBalancer).
VpcV2 supports the addition of both primary and secondary addresses. The primary address must be an IPv4 address, which can be specified as a CIDR string or assigned from an IPAM pool. Secondary addresses can be either IPv4 or IPv6. By default, VpcV2 assigns 10.0.0.0/16 as the primary CIDR if no other CIDR is specified.
Below is an example of creating a VPC with both IPv4 and IPv6 support:
const stack = new Stack();
new VpcV2(this, 'Vpc', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/24'),
secondaryAddressBlocks: [
IpAddresses.amazonProvidedIpv6({cidrBlockName: 'AmazonProvidedIpv6'}),
],
});
stack = Stack()
VpcV2(self, "Vpc",
primary_address_block=IpAddresses.ipv4("10.0.0.0/24"),
secondary_address_blocks=[
IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonProvidedIpv6")
]
)
Stack stack = new Stack();
VpcV2.Builder.create(this, "Vpc")
.primaryAddressBlock(IpAddresses.ipv4("10.0.0.0/24"))
.secondaryAddressBlocks(List.of(IpAddresses.amazonProvidedIpv6(SecondaryAddressProps.builder().cidrBlockName("AmazonProvidedIpv6").build())))
.build();
var stack = new Stack();
new VpcV2(this, "Vpc", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.0.0.0/24"),
SecondaryAddressBlocks = new [] { IpAddresses.AmazonProvidedIpv6(new SecondaryAddressProps { CidrBlockName = "AmazonProvidedIpv6" }) }
});
stack := awscdk.Newstack()
awsec2alpha.NewVpcV2(this, jsii.String("Vpc"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.0.0.0/24")),
SecondaryAddressBlocks: []IIpAddresses{
awsec2alpha.IpAddresses_AmazonProvidedIpv6(&SecondaryAddressProps{
CidrBlockName: jsii.String("AmazonProvidedIpv6"),
}),
},
})
VpcV2 does not automatically create subnets or allocate IP addresses, which is different from the Vpc construct.
SubnetV2
SubnetV2 is a re-write of the ec2.Subnet construct. This new construct can be used to add subnets to a VpcV2 instance: Note: When defining a subnet with SubnetV2, CDK automatically creates a new route table, unless a route table is explicitly provided as an input to the construct. To enable the mapPublicIpOnLaunch feature (which is false by default), set the property to true when creating the subnet.
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc', {
secondaryAddressBlocks: [
IpAddresses.amazonProvidedIpv6({ cidrBlockName: 'AmazonProvidedIp'}),
],
});
new SubnetV2(this, 'subnetA', {
vpc: myVpc,
availabilityZone: 'us-east-1a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
ipv6CidrBlock: new IpCidr('2a05:d02c:25:4000::/60'),
subnetType: SubnetType.PUBLIC,
mapPublicIpOnLaunch: true,
})
stack = Stack()
my_vpc = VpcV2(self, "Vpc",
secondary_address_blocks=[
IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonProvidedIp")
]
)
SubnetV2(self, "subnetA",
vpc=my_vpc,
availability_zone="us-east-1a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
ipv6_cidr_block=IpCidr("2a05:d02c:25:4000::/60"),
subnet_type=SubnetType.PUBLIC,
map_public_ip_on_launch=True
)
Stack stack = new Stack();
VpcV2 myVpc = VpcV2.Builder.create(this, "Vpc")
.secondaryAddressBlocks(List.of(IpAddresses.amazonProvidedIpv6(SecondaryAddressProps.builder().cidrBlockName("AmazonProvidedIp").build())))
.build();
SubnetV2.Builder.create(this, "subnetA")
.vpc(myVpc)
.availabilityZone("us-east-1a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.ipv6CidrBlock(new IpCidr("2a05:d02c:25:4000::/60"))
.subnetType(SubnetType.PUBLIC)
.mapPublicIpOnLaunch(true)
.build();
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc", new VpcV2Props {
SecondaryAddressBlocks = new [] { IpAddresses.AmazonProvidedIpv6(new SecondaryAddressProps { CidrBlockName = "AmazonProvidedIp" }) }
});
new SubnetV2(this, "subnetA", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "us-east-1a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
Ipv6CidrBlock = new IpCidr("2a05:d02c:25:4000::/60"),
SubnetType = SubnetType.PUBLIC,
MapPublicIpOnLaunch = true
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"), &VpcV2Props{
SecondaryAddressBlocks: []IIpAddresses{
awsec2alpha.IpAddresses_AmazonProvidedIpv6(&SecondaryAddressProps{
CidrBlockName: jsii.String("AmazonProvidedIp"),
}),
},
})
awsec2alpha.NewSubnetV2(this, jsii.String("subnetA"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("us-east-1a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
Ipv6CidrBlock: awsec2alpha.NewIpCidr(jsii.String("2a05:d02c:25:4000::/60")),
SubnetType: awscdk.SubnetType_PUBLIC,
MapPublicIpOnLaunch: jsii.Boolean(true),
})
Since VpcV2 does not create subnets automatically, users have full control over IP addresses allocation across subnets.
IP Addresses Management
Additional CIDRs can be added to the VPC via the secondaryAddressBlocks property. The following example illustrates the options of defining these secondary address blocks using IPAM:
Note: There’s currently an issue with IPAM pool deletion that may affect the cdk --destroy command. This is because IPAM takes time to detect when the IP address pool has been deallocated after the VPC is deleted. The current workaround is to wait until the IP address is fully deallocated from the pool before retrying the deletion. Below command can be used to check allocations for a pool using CLI
aws ec2 get-ipam-pool-allocations --ipam-pool-id <ipam-pool-id>
const stack = new Stack();
const ipam = new Ipam(this, 'Ipam', {
operatingRegions: ['us-west-1']
});
const ipamPublicPool = ipam.publicScope.addPool('PublicPoolA', {
addressFamily: AddressFamily.IP_V6,
awsService: AwsServiceName.EC2,
locale: 'us-west-1',
publicIpSource: IpamPoolPublicIpSource.AMAZON,
});
ipamPublicPool.provisionCidr('PublicPoolACidrA', { netmaskLength: 52 } );
const ipamPrivatePool = ipam.privateScope.addPool('PrivatePoolA', {
addressFamily: AddressFamily.IP_V4,
});
ipamPrivatePool.provisionCidr('PrivatePoolACidrA', { netmaskLength: 8 } );
new VpcV2(this, 'Vpc', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/24'),
secondaryAddressBlocks: [
IpAddresses.amazonProvidedIpv6({ cidrBlockName: 'AmazonIpv6' }),
IpAddresses.ipv6Ipam({
ipamPool: ipamPublicPool,
netmaskLength: 52,
cidrBlockName: 'ipv6Ipam',
}),
IpAddresses.ipv4Ipam({
ipamPool: ipamPrivatePool,
netmaskLength: 8,
cidrBlockName: 'ipv4Ipam',
}),
],
});
stack = Stack()
ipam = Ipam(self, "Ipam",
operating_regions=["us-west-1"]
)
ipam_public_pool = ipam.public_scope.add_pool("PublicPoolA",
address_family=AddressFamily.IP_V6,
aws_service=AwsServiceName.EC2,
locale="us-west-1",
public_ip_source=IpamPoolPublicIpSource.AMAZON
)
ipam_public_pool.provision_cidr("PublicPoolACidrA", netmask_length=52)
ipam_private_pool = ipam.private_scope.add_pool("PrivatePoolA",
address_family=AddressFamily.IP_V4
)
ipam_private_pool.provision_cidr("PrivatePoolACidrA", netmask_length=8)
VpcV2(self, "Vpc",
primary_address_block=IpAddresses.ipv4("10.0.0.0/24"),
secondary_address_blocks=[
IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonIpv6"),
IpAddresses.ipv6_ipam(
ipam_pool=ipam_public_pool,
netmask_length=52,
cidr_block_name="ipv6Ipam"
),
IpAddresses.ipv4_ipam(
ipam_pool=ipam_private_pool,
netmask_length=8,
cidr_block_name="ipv4Ipam"
)
]
)
Stack stack = new Stack();
Ipam ipam = Ipam.Builder.create(this, "Ipam")
.operatingRegions(List.of("us-west-1"))
.build();
IIpamPool ipamPublicPool = ipam.publicScope.addPool("PublicPoolA", PoolOptions.builder()
.addressFamily(AddressFamily.IP_V6)
.awsService(AwsServiceName.EC2)
.locale("us-west-1")
.publicIpSource(IpamPoolPublicIpSource.AMAZON)
.build());
ipamPublicPool.provisionCidr("PublicPoolACidrA", IpamPoolCidrProvisioningOptions.builder().netmaskLength(52).build());
IIpamPool ipamPrivatePool = ipam.privateScope.addPool("PrivatePoolA", PoolOptions.builder()
.addressFamily(AddressFamily.IP_V4)
.build());
ipamPrivatePool.provisionCidr("PrivatePoolACidrA", IpamPoolCidrProvisioningOptions.builder().netmaskLength(8).build());
VpcV2.Builder.create(this, "Vpc")
.primaryAddressBlock(IpAddresses.ipv4("10.0.0.0/24"))
.secondaryAddressBlocks(List.of(IpAddresses.amazonProvidedIpv6(SecondaryAddressProps.builder().cidrBlockName("AmazonIpv6").build()), IpAddresses.ipv6Ipam(IpamOptions.builder()
.ipamPool(ipamPublicPool)
.netmaskLength(52)
.cidrBlockName("ipv6Ipam")
.build()), IpAddresses.ipv4Ipam(IpamOptions.builder()
.ipamPool(ipamPrivatePool)
.netmaskLength(8)
.cidrBlockName("ipv4Ipam")
.build())))
.build();
var stack = new Stack();
var ipam = new Ipam(this, "Ipam", new IpamProps {
OperatingRegions = new [] { "us-west-1" }
});
var ipamPublicPool = ipam.PublicScope.AddPool("PublicPoolA", new PoolOptions {
AddressFamily = AddressFamily.IP_V6,
AwsService = AwsServiceName.EC2,
Locale = "us-west-1",
PublicIpSource = IpamPoolPublicIpSource.AMAZON
});
ipamPublicPool.ProvisionCidr("PublicPoolACidrA", new IpamPoolCidrProvisioningOptions { NetmaskLength = 52 });
var ipamPrivatePool = ipam.PrivateScope.AddPool("PrivatePoolA", new PoolOptions {
AddressFamily = AddressFamily.IP_V4
});
ipamPrivatePool.ProvisionCidr("PrivatePoolACidrA", new IpamPoolCidrProvisioningOptions { NetmaskLength = 8 });
new VpcV2(this, "Vpc", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.0.0.0/24"),
SecondaryAddressBlocks = new [] { IpAddresses.AmazonProvidedIpv6(new SecondaryAddressProps { CidrBlockName = "AmazonIpv6" }), IpAddresses.Ipv6Ipam(new IpamOptions {
IpamPool = ipamPublicPool,
NetmaskLength = 52,
CidrBlockName = "ipv6Ipam"
}), IpAddresses.Ipv4Ipam(new IpamOptions {
IpamPool = ipamPrivatePool,
NetmaskLength = 8,
CidrBlockName = "ipv4Ipam"
}) }
});
stack := awscdk.Newstack()
ipam := awsec2alpha.NewIpam(this, jsii.String("Ipam"), &IpamProps{
OperatingRegions: []*string{
jsii.String("us-west-1"),
},
})
ipamPublicPool := ipam.PublicScope.AddPool(jsii.String("PublicPoolA"), &PoolOptions{
AddressFamily: awsec2alpha.AddressFamily_IP_V6,
AwsService: awsec2alpha.AwsServiceName_EC2,
Locale: jsii.String("us-west-1"),
PublicIpSource: awsec2alpha.IpamPoolPublicIpSource_AMAZON,
})
ipamPublicPool.ProvisionCidr(jsii.String("PublicPoolACidrA"), &IpamPoolCidrProvisioningOptions{
NetmaskLength: jsii.Number(52),
})
ipamPrivatePool := ipam.PrivateScope.AddPool(jsii.String("PrivatePoolA"), &PoolOptions{
AddressFamily: awsec2alpha.AddressFamily_IP_V4,
})
ipamPrivatePool.ProvisionCidr(jsii.String("PrivatePoolACidrA"), &IpamPoolCidrProvisioningOptions{
NetmaskLength: jsii.Number(8),
})
awsec2alpha.NewVpcV2(this, jsii.String("Vpc"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.0.0.0/24")),
SecondaryAddressBlocks: []IIpAddresses{
awsec2alpha.IpAddresses_AmazonProvidedIpv6(&SecondaryAddressProps{
CidrBlockName: jsii.String("AmazonIpv6"),
}),
awsec2alpha.IpAddresses_Ipv6Ipam(&IpamOptions{
IpamPool: ipamPublicPool,
NetmaskLength: jsii.Number(52),
CidrBlockName: jsii.String("ipv6Ipam"),
}),
awsec2alpha.IpAddresses_Ipv4Ipam(&IpamOptions{
IpamPool: ipamPrivatePool,
NetmaskLength: jsii.Number(8),
CidrBlockName: jsii.String("ipv4Ipam"),
}),
},
})
Bring your own IPv6 addresses (BYOIP)
If you have your own IP address that you would like to use with EC2, you can set up an IPv6 pool via the AWS CLI, and use that pool ID in your application.
Once you have certified your IP address block with an ROA and have obtained an X-509 certificate, you can run the following command to provision your CIDR block in your AWS account:
aws ec2 provision-byoip-cidr --region <region> --cidr <your CIDR block> --cidr-authorization-context Message="1|aws|<account>|<your CIDR block>|<expiration date>|SHA256".Signature="<signature>"
When your BYOIP CIDR is provisioned, you can run the following command to retrieve your IPv6 pool ID, which will be used in your VPC declaration:
aws ec2 describe-byoip-cidr --region <region>
For more help on setting up your IPv6 address, please review the EC2 Documentation.
Once you have provisioned your address block, you can use the IPv6 in your VPC as follows:
const myVpc = new VpcV2(this, 'Vpc', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
secondaryAddressBlocks: [IpAddresses.ipv6ByoipPool({
cidrBlockName: 'MyByoipCidrBlock',
ipv6PoolId: 'ipv6pool-ec2-someHashValue',
ipv6CidrBlock: '2001:db8::/32'
})],
enableDnsHostnames: true,
enableDnsSupport: true,
});
my_vpc = VpcV2(self, "Vpc",
primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
secondary_address_blocks=[IpAddresses.ipv6_byoip_pool(
cidr_block_name="MyByoipCidrBlock",
ipv6_pool_id="ipv6pool-ec2-someHashValue",
ipv6_cidr_block="2001:db8::/32"
)],
enable_dns_hostnames=True,
enable_dns_support=True
)
VpcV2 myVpc = VpcV2.Builder.create(this, "Vpc")
.primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
.secondaryAddressBlocks(List.of(IpAddresses.ipv6ByoipPool(Ipv6PoolSecondaryAddressProps.builder()
.cidrBlockName("MyByoipCidrBlock")
.ipv6PoolId("ipv6pool-ec2-someHashValue")
.ipv6CidrBlock("2001:db8::/32")
.build())))
.enableDnsHostnames(true)
.enableDnsSupport(true)
.build();
var myVpc = new VpcV2(this, "Vpc", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16"),
SecondaryAddressBlocks = new [] { IpAddresses.Ipv6ByoipPool(new Ipv6PoolSecondaryAddressProps {
CidrBlockName = "MyByoipCidrBlock",
Ipv6PoolId = "ipv6pool-ec2-someHashValue",
Ipv6CidrBlock = "2001:db8::/32"
}) },
EnableDnsHostnames = true,
EnableDnsSupport = true
});
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.1.0.0/16")),
SecondaryAddressBlocks: []IIpAddresses{
awsec2alpha.IpAddresses_Ipv6ByoipPool(&Ipv6PoolSecondaryAddressProps{
CidrBlockName: jsii.String("MyByoipCidrBlock"),
Ipv6PoolId: jsii.String("ipv6pool-ec2-someHashValue"),
Ipv6CidrBlock: jsii.String("2001:db8::/32"),
}),
},
EnableDnsHostnames: jsii.Boolean(true),
EnableDnsSupport: jsii.Boolean(true),
})
Routing
RouteTable is a new construct that allows for route tables to be customized in a variety of ways. Using this construct, a customized route table can be added to the subnets defined using SubnetV2. For instance, the following example shows how a custom route table can be created and appended to a SubnetV2:
const myVpc = new VpcV2(this, 'Vpc');
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: myVpc,
});
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
routeTable,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PRIVATE_ISOLATED,
});
my_vpc = VpcV2(self, "Vpc")
route_table = RouteTable(self, "RouteTable",
vpc=my_vpc
)
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
route_table=route_table,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PRIVATE_ISOLATED
)
VpcV2 myVpc = new VpcV2(this, "Vpc");
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(myVpc)
.build();
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.routeTable(routeTable)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PRIVATE_ISOLATED)
.build();
var myVpc = new VpcV2(this, "Vpc");
var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = myVpc
});
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
RouteTable = routeTable,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PRIVATE_ISOLATED
});
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: myVpc,
})
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
RouteTable: RouteTable,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PRIVATE_ISOLATED,
})
Routes can be created to link subnets to various different AWS services via gateways and endpoints. Each unique route target has its own dedicated construct that can be routed to a given subnet via the Route construct. An example using the InternetGateway construct can be seen below:
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: myVpc,
});
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PRIVATE_ISOLATED });
const igw = new InternetGateway(this, 'IGW', {
vpc: myVpc,
});
new Route(this, 'IgwRoute', {
routeTable,
destination: '0.0.0.0/0',
target: { gateway: igw },
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
route_table = RouteTable(self, "RouteTable",
vpc=my_vpc
)
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PRIVATE_ISOLATED
)
igw = InternetGateway(self, "IGW",
vpc=my_vpc
)
Route(self, "IgwRoute",
route_table=route_table,
destination="0.0.0.0/0",
target={"gateway": igw}
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(myVpc)
.build();
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PRIVATE_ISOLATED)
.build();
InternetGateway igw = InternetGateway.Builder.create(this, "IGW")
.vpc(myVpc)
.build();
Route.Builder.create(this, "IgwRoute")
.routeTable(routeTable)
.destination("0.0.0.0/0")
.target(Map.of("gateway", igw))
.build();
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = myVpc
});
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PRIVATE_ISOLATED
});
var igw = new InternetGateway(this, "IGW", new InternetGatewayProps {
Vpc = myVpc
});
new Route(this, "IgwRoute", new RouteProps {
RouteTable = routeTable,
Destination = "0.0.0.0/0",
Target = new Dictionary<string, IRouteTarget?> { { "gateway", igw } }
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: myVpc,
})
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PRIVATE_ISOLATED,
})
igw := awsec2alpha.NewInternetGateway(this, jsii.String("IGW"), &InternetGatewayProps{
Vpc: myVpc,
})
awsec2alpha.NewRoute(this, jsii.String("IgwRoute"), &RouteProps{
RouteTable: RouteTable,
Destination: jsii.String("0.0.0.0/0"),
Target: map[string]iRouteTarget{
"gateway": igw,
},
})
Alternatively, Routes can also be created via method addRoute in the RouteTable class. An example using the EgressOnlyInternetGateway construct can be seen below: Note: EgressOnlyInternetGateway can only be used to set up outbound IPv6 routing.
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 });
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})
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));
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 } });
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,
})
Other route targets may require a deeper set of parameters to set up properly. For instance, the example below illustrates how to set up a NatGateway:
const myVpc = new VpcV2(this, 'Vpc');
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: myVpc,
});
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PRIVATE_ISOLATED });
const natgw = new NatGateway(this, 'NatGW', {
subnet: subnet,
vpc: myVpc,
connectivityType: NatConnectivityType.PRIVATE,
privateIpAddress: '10.0.0.42',
});
new Route(this, 'NatGwRoute', {
routeTable,
destination: '0.0.0.0/0',
target: { gateway: natgw },
});
my_vpc = VpcV2(self, "Vpc")
route_table = RouteTable(self, "RouteTable",
vpc=my_vpc
)
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PRIVATE_ISOLATED
)
natgw = NatGateway(self, "NatGW",
subnet=subnet,
vpc=my_vpc,
connectivity_type=NatConnectivityType.PRIVATE,
private_ip_address="10.0.0.42"
)
Route(self, "NatGwRoute",
route_table=route_table,
destination="0.0.0.0/0",
target={"gateway": natgw}
)
VpcV2 myVpc = new VpcV2(this, "Vpc");
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(myVpc)
.build();
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PRIVATE_ISOLATED)
.build();
NatGateway natgw = NatGateway.Builder.create(this, "NatGW")
.subnet(subnet)
.vpc(myVpc)
.connectivityType(NatConnectivityType.PRIVATE)
.privateIpAddress("10.0.0.42")
.build();
Route.Builder.create(this, "NatGwRoute")
.routeTable(routeTable)
.destination("0.0.0.0/0")
.target(Map.of("gateway", natgw))
.build();
var myVpc = new VpcV2(this, "Vpc");
var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = myVpc
});
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PRIVATE_ISOLATED
});
var natgw = new NatGateway(this, "NatGW", new NatGatewayProps {
Subnet = subnet,
Vpc = myVpc,
ConnectivityType = NatConnectivityType.PRIVATE,
PrivateIpAddress = "10.0.0.42"
});
new Route(this, "NatGwRoute", new RouteProps {
RouteTable = routeTable,
Destination = "0.0.0.0/0",
Target = new Dictionary<string, IRouteTarget?> { { "gateway", natgw } }
});
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: myVpc,
})
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PRIVATE_ISOLATED,
})
natgw := awsec2alpha.NewNatGateway(this, jsii.String("NatGW"), &NatGatewayProps{
Subnet: subnet,
Vpc: myVpc,
ConnectivityType: awsec2alpha.NatConnectivityType_PRIVATE,
PrivateIpAddress: jsii.String("10.0.0.42"),
})
awsec2alpha.NewRoute(this, jsii.String("NatGwRoute"), &RouteProps{
RouteTable: RouteTable,
Destination: jsii.String("0.0.0.0/0"),
Target: map[string]iRouteTarget{
"gateway": natgw,
},
})
It is also possible to set up endpoints connecting other AWS services. For instance, the example below illustrates the linking of a Dynamo DB endpoint via the existing ec2.GatewayVpcEndpoint construct as a route target:
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: myVpc,
});
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PRIVATE });
const dynamoEndpoint = new ec2.GatewayVpcEndpoint(this, 'DynamoEndpoint', {
service: ec2.GatewayVpcEndpointAwsService.DYNAMODB,
vpc: myVpc,
subnets: [subnet],
});
new Route(this, 'DynamoDBRoute', {
routeTable,
destination: '0.0.0.0/0',
target: { endpoint: dynamoEndpoint },
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
route_table = RouteTable(self, "RouteTable",
vpc=my_vpc
)
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PRIVATE
)
dynamo_endpoint = ec2.GatewayVpcEndpoint(self, "DynamoEndpoint",
service=ec2.GatewayVpcEndpointAwsService.DYNAMODB,
vpc=my_vpc,
subnets=[subnet]
)
Route(self, "DynamoDBRoute",
route_table=route_table,
destination="0.0.0.0/0",
target={"endpoint": dynamo_endpoint}
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(myVpc)
.build();
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PRIVATE)
.build();
GatewayVpcEndpoint dynamoEndpoint = GatewayVpcEndpoint.Builder.create(this, "DynamoEndpoint")
.service(GatewayVpcEndpointAwsService.DYNAMODB)
.vpc(myVpc)
.subnets(List.of(subnet))
.build();
Route.Builder.create(this, "DynamoDBRoute")
.routeTable(routeTable)
.destination("0.0.0.0/0")
.target(Map.of("endpoint", dynamoEndpoint))
.build();
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = myVpc
});
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PRIVATE
});
var dynamoEndpoint = new GatewayVpcEndpoint(this, "DynamoEndpoint", new GatewayVpcEndpointProps {
Service = GatewayVpcEndpointAwsService.DYNAMODB,
Vpc = myVpc,
Subnets = new [] { subnet }
});
new Route(this, "DynamoDBRoute", new RouteProps {
RouteTable = routeTable,
Destination = "0.0.0.0/0",
Target = new Dictionary<string, IVpcEndpoint?> { { "endpoint", dynamoEndpoint } }
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: myVpc,
})
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PRIVATE,
})
dynamoEndpoint := ec2.NewGatewayVpcEndpoint(this, jsii.String("DynamoEndpoint"), &GatewayVpcEndpointProps{
Service: ec2.GatewayVpcEndpointAwsService_DYNAMODB(),
Vpc: myVpc,
Subnets: []SubnetSelection{
subnet,
},
})
awsec2alpha.NewRoute(this, jsii.String("DynamoDBRoute"), &RouteProps{
RouteTable: RouteTable,
Destination: jsii.String("0.0.0.0/0"),
Target: map[string]iVpcEndpoint{
"endpoint": dynamoEndpoint,
},
})
VPC Peering Connection
VPC peering connection allows you to connect two VPCs and route traffic between them using private IP addresses. The VpcV2 construct supports creating VPC peering connections through the VPCPeeringConnection construct from the route module.
Peering Connection cannot be established between two VPCs with overlapping CIDR ranges. Please make sure the two VPC CIDRs do not overlap with each other else it will throw an error.
For more information, see What is VPC peering?.
The following show examples of how to create a peering connection between two VPCs for all possible combinations of same-account or cross-account, and same-region or cross-region configurations.
Note: You cannot create a VPC peering connection between VPCs that have matching or overlapping CIDR blocks
Case 1: Same Account and Same Region Peering Connection
const stack = new Stack();
const vpcA = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
});
const vpcB = new VpcV2(this, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
});
const peeringConnection = vpcA.createPeeringConnection('sameAccountSameRegionPeering', {
acceptorVpc: vpcB,
});
stack = Stack()
vpc_a = VpcV2(self, "VpcA",
primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
)
vpc_b = VpcV2(self, "VpcB",
primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
)
peering_connection = vpc_a.create_peering_connection("sameAccountSameRegionPeering",
acceptor_vpc=vpc_b
)
Stack stack = new Stack();
VpcV2 vpcA = VpcV2.Builder.create(this, "VpcA")
.primaryAddressBlock(IpAddresses.ipv4("10.0.0.0/16"))
.build();
VpcV2 vpcB = VpcV2.Builder.create(this, "VpcB")
.primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
.build();
VPCPeeringConnection peeringConnection = vpcA.createPeeringConnection("sameAccountSameRegionPeering", VPCPeeringConnectionOptions.builder()
.acceptorVpc(vpcB)
.build());
var stack = new Stack();
var vpcA = new VpcV2(this, "VpcA", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.0.0.0/16")
});
var vpcB = new VpcV2(this, "VpcB", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16")
});
var peeringConnection = vpcA.CreatePeeringConnection("sameAccountSameRegionPeering", new VPCPeeringConnectionOptions {
AcceptorVpc = vpcB
});
stack := awscdk.Newstack()
vpcA := awsec2alpha.NewVpcV2(this, jsii.String("VpcA"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.0.0.0/16")),
})
vpcB := awsec2alpha.NewVpcV2(this, jsii.String("VpcB"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_*Ipv4(jsii.String("10.1.0.0/16")),
})
peeringConnection := vpcA.CreatePeeringConnection(jsii.String("sameAccountSameRegionPeering"), &VPCPeeringConnectionOptions{
AcceptorVpc: vpcB,
})
Case 2: Same Account and Cross Region Peering Connection
There is no difference from Case 1 when calling createPeeringConnection. The only change is that one of the VPCs are created in another stack with a different region. To establish cross region VPC peering connection, acceptorVpc needs to be imported to the requestor VPC stack using fromVpcV2Attributes method.
const app = new App();
const stackA = new Stack(app, 'VpcStackA', { env: { account: '000000000000', region: 'us-east-1' } });
const stackB = new Stack(app, 'VpcStackB', { env: { account: '000000000000', region: 'us-west-2' } });
const vpcA = new VpcV2(stackA, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
});
new VpcV2(stackB, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
});
const vpcB = VpcV2.fromVpcV2Attributes(stackA, 'ImportedVpcB', {
vpcId: 'MockVpcBid',
vpcCidrBlock: '10.1.0.0/16',
region: 'us-west-2',
ownerAccountId: '000000000000',
});
const peeringConnection = vpcA.createPeeringConnection('sameAccountCrossRegionPeering', {
acceptorVpc: vpcB,
});
from aws_cdk import Environment, Environment
app = App()
stack_a = Stack(app, "VpcStackA", env=Environment(account="000000000000", region="us-east-1"))
stack_b = Stack(app, "VpcStackB", env=Environment(account="000000000000", region="us-west-2"))
vpc_a = VpcV2(stack_a, "VpcA",
primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
)
VpcV2(stack_b, "VpcB",
primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
)
vpc_b = VpcV2.from_vpc_v2_attributes(stack_a, "ImportedVpcB",
vpc_id="MockVpcBid",
vpc_cidr_block="10.1.0.0/16",
region="us-west-2",
owner_account_id="000000000000"
)
peering_connection = vpc_a.create_peering_connection("sameAccountCrossRegionPeering",
acceptor_vpc=vpc_b
)
App app = new App();
Stack stackA = Stack.Builder.create(app, "VpcStackA").env(Environment.builder().account("000000000000").region("us-east-1").build()).build();
Stack stackB = Stack.Builder.create(app, "VpcStackB").env(Environment.builder().account("000000000000").region("us-west-2").build()).build();
VpcV2 vpcA = VpcV2.Builder.create(stackA, "VpcA")
.primaryAddressBlock(IpAddresses.ipv4("10.0.0.0/16"))
.build();
VpcV2.Builder.create(stackB, "VpcB")
.primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
.build();
IVpcV2 vpcB = VpcV2.fromVpcV2Attributes(stackA, "ImportedVpcB", VpcV2Attributes.builder()
.vpcId("MockVpcBid")
.vpcCidrBlock("10.1.0.0/16")
.region("us-west-2")
.ownerAccountId("000000000000")
.build());
VPCPeeringConnection peeringConnection = vpcA.createPeeringConnection("sameAccountCrossRegionPeering", VPCPeeringConnectionOptions.builder()
.acceptorVpc(vpcB)
.build());
var app = new App();
var stackA = new Stack(app, "VpcStackA", new StackProps { Env = new Environment { Account = "000000000000", Region = "us-east-1" } });
var stackB = new Stack(app, "VpcStackB", new StackProps { Env = new Environment { Account = "000000000000", Region = "us-west-2" } });
var vpcA = new VpcV2(stackA, "VpcA", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.0.0.0/16")
});
new VpcV2(stackB, "VpcB", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16")
});
var vpcB = VpcV2.FromVpcV2Attributes(stackA, "ImportedVpcB", new VpcV2Attributes {
VpcId = "MockVpcBid",
VpcCidrBlock = "10.1.0.0/16",
Region = "us-west-2",
OwnerAccountId = "000000000000"
});
var peeringConnection = vpcA.CreatePeeringConnection("sameAccountCrossRegionPeering", new VPCPeeringConnectionOptions {
AcceptorVpc = vpcB
});
app := awscdk.NewApp()
stackA := awscdk.Newstack(app, jsii.String("VpcStackA"), &StackProps{
Env: &Environment{
Account: jsii.String("000000000000"),
Region: jsii.String("us-east-1"),
},
})
stackB := awscdk.Newstack(app, jsii.String("VpcStackB"), &StackProps{
Env: &Environment{
Account: jsii.String("000000000000"),
Region: jsii.String("us-west-2"),
},
})
vpcA := awsec2alpha.NewVpcV2(stackA, jsii.String("VpcA"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.0.0.0/16")),
})
awsec2alpha.NewVpcV2(stackB, jsii.String("VpcB"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_*Ipv4(jsii.String("10.1.0.0/16")),
})
vpcB := awsec2alpha.VpcV2_FromVpcV2Attributes(stackA, jsii.String("ImportedVpcB"), &VpcV2Attributes{
VpcId: jsii.String("MockVpcBid"),
VpcCidrBlock: jsii.String("10.1.0.0/16"),
Region: jsii.String("us-west-2"),
OwnerAccountId: jsii.String("000000000000"),
})
peeringConnection := vpcA.CreatePeeringConnection(jsii.String("sameAccountCrossRegionPeering"), &VPCPeeringConnectionOptions{
AcceptorVpc: vpcB,
})
Case 3: Cross Account Peering Connection
For cross-account connections, the acceptor account needs an IAM role that grants the requestor account permission to initiate the connection. Create a new IAM role in the acceptor account using method createAcceptorVpcRole to provide the necessary permissions.
Once role is created in account, provide role arn for field peerRoleArn under method createPeeringConnection
const stack = new Stack();
const acceptorVpc = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
});
const acceptorRoleArn = acceptorVpc.createAcceptorVpcRole('000000000000'); // Requestor account ID
stack = Stack()
acceptor_vpc = VpcV2(self, "VpcA",
primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
)
acceptor_role_arn = acceptor_vpc.create_acceptor_vpc_role("000000000000")
Stack stack = new Stack();
VpcV2 acceptorVpc = VpcV2.Builder.create(this, "VpcA")
.primaryAddressBlock(IpAddresses.ipv4("10.0.0.0/16"))
.build();
Role acceptorRoleArn = acceptorVpc.createAcceptorVpcRole("000000000000");
var stack = new Stack();
var acceptorVpc = new VpcV2(this, "VpcA", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.0.0.0/16")
});
var acceptorRoleArn = acceptorVpc.CreateAcceptorVpcRole("000000000000");
stack := awscdk.Newstack()
acceptorVpc := awsec2alpha.NewVpcV2(this, jsii.String("VpcA"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.0.0.0/16")),
})
acceptorRoleArn := acceptorVpc.CreateAcceptorVpcRole(jsii.String("000000000000"))
After creating an IAM role in the acceptor account, we can initiate the peering connection request from the requestor VPC. Import acceptorVpc to the stack using fromVpcV2Attributes method, it is recommended to specify owner account id of the acceptor VPC in case of cross account peering connection, if acceptor VPC is hosted in different region provide region value for import as well. The following code snippet demonstrates how to set up VPC peering between two VPCs in different AWS accounts using CDK:
const stack = new Stack();
const acceptorVpc = VpcV2.fromVpcV2Attributes(this, 'acceptorVpc', {
vpcId: 'vpc-XXXX',
vpcCidrBlock: '10.0.0.0/16',
region: 'us-east-2',
ownerAccountId: '111111111111',
});
const acceptorRoleArn = 'arn:aws:iam::111111111111:role/VpcPeeringRole';
const requestorVpc = new VpcV2(this, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
});
const peeringConnection = requestorVpc.createPeeringConnection('crossAccountCrossRegionPeering', {
acceptorVpc: acceptorVpc,
peerRoleArn: acceptorRoleArn,
});
stack = Stack()
acceptor_vpc = VpcV2.from_vpc_v2_attributes(self, "acceptorVpc",
vpc_id="vpc-XXXX",
vpc_cidr_block="10.0.0.0/16",
region="us-east-2",
owner_account_id="111111111111"
)
acceptor_role_arn = "arn:aws:iam::111111111111:role/VpcPeeringRole"
requestor_vpc = VpcV2(self, "VpcB",
primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
)
peering_connection = requestor_vpc.create_peering_connection("crossAccountCrossRegionPeering",
acceptor_vpc=acceptor_vpc,
peer_role_arn=acceptor_role_arn
)
Stack stack = new Stack();
IVpcV2 acceptorVpc = VpcV2.fromVpcV2Attributes(this, "acceptorVpc", VpcV2Attributes.builder()
.vpcId("vpc-XXXX")
.vpcCidrBlock("10.0.0.0/16")
.region("us-east-2")
.ownerAccountId("111111111111")
.build());
String acceptorRoleArn = "arn:aws:iam::111111111111:role/VpcPeeringRole";
VpcV2 requestorVpc = VpcV2.Builder.create(this, "VpcB")
.primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
.build();
VPCPeeringConnection peeringConnection = requestorVpc.createPeeringConnection("crossAccountCrossRegionPeering", VPCPeeringConnectionOptions.builder()
.acceptorVpc(acceptorVpc)
.peerRoleArn(acceptorRoleArn)
.build());
var stack = new Stack();
var acceptorVpc = VpcV2.FromVpcV2Attributes(this, "acceptorVpc", new VpcV2Attributes {
VpcId = "vpc-XXXX",
VpcCidrBlock = "10.0.0.0/16",
Region = "us-east-2",
OwnerAccountId = "111111111111"
});
var acceptorRoleArn = "arn:aws:iam::111111111111:role/VpcPeeringRole";
var requestorVpc = new VpcV2(this, "VpcB", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16")
});
var peeringConnection = requestorVpc.CreatePeeringConnection("crossAccountCrossRegionPeering", new VPCPeeringConnectionOptions {
AcceptorVpc = acceptorVpc,
PeerRoleArn = acceptorRoleArn
});
stack := awscdk.Newstack()
acceptorVpc := awsec2alpha.VpcV2_FromVpcV2Attributes(this, jsii.String("acceptorVpc"), &VpcV2Attributes{
VpcId: jsii.String("vpc-XXXX"),
VpcCidrBlock: jsii.String("10.0.0.0/16"),
Region: jsii.String("us-east-2"),
OwnerAccountId: jsii.String("111111111111"),
})
acceptorRoleArn := "arn:aws:iam::111111111111:role/VpcPeeringRole"
requestorVpc := awsec2alpha.NewVpcV2(this, jsii.String("VpcB"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.1.0.0/16")),
})
peeringConnection := requestorVpc.CreatePeeringConnection(jsii.String("crossAccountCrossRegionPeering"), &VPCPeeringConnectionOptions{
AcceptorVpc: acceptorVpc,
PeerRoleArn: acceptorRoleArn,
})
Route Table Configuration
After establishing the VPC peering connection, routes must be added to the respective route tables in the VPCs to enable traffic flow. If a route is added to the requestor stack, information will be able to flow from the requestor VPC to the acceptor VPC, but not in the reverse direction. For bi-directional communication, routes need to be added in both VPCs from their respective stacks.
For more information, see Update your route tables for a VPC peering connection.
const stack = new Stack();
const acceptorVpc = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
});
const requestorVpc = new VpcV2(this, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
});
const peeringConnection = requestorVpc.createPeeringConnection('peeringConnection', {
acceptorVpc: acceptorVpc,
});
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: requestorVpc,
});
routeTable.addRoute('vpcPeeringRoute', '10.0.0.0/16', { gateway: peeringConnection });
stack = Stack()
acceptor_vpc = VpcV2(self, "VpcA",
primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
)
requestor_vpc = VpcV2(self, "VpcB",
primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
)
peering_connection = requestor_vpc.create_peering_connection("peeringConnection",
acceptor_vpc=acceptor_vpc
)
route_table = RouteTable(self, "RouteTable",
vpc=requestor_vpc
)
route_table.add_route("vpcPeeringRoute", "10.0.0.0/16", {"gateway": peering_connection})
Stack stack = new Stack();
VpcV2 acceptorVpc = VpcV2.Builder.create(this, "VpcA")
.primaryAddressBlock(IpAddresses.ipv4("10.0.0.0/16"))
.build();
VpcV2 requestorVpc = VpcV2.Builder.create(this, "VpcB")
.primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
.build();
VPCPeeringConnection peeringConnection = requestorVpc.createPeeringConnection("peeringConnection", VPCPeeringConnectionOptions.builder()
.acceptorVpc(acceptorVpc)
.build());
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(requestorVpc)
.build();
routeTable.addRoute("vpcPeeringRoute", "10.0.0.0/16", Map.of("gateway", peeringConnection));
var stack = new Stack();
var acceptorVpc = new VpcV2(this, "VpcA", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.0.0.0/16")
});
var requestorVpc = new VpcV2(this, "VpcB", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16")
});
var peeringConnection = requestorVpc.CreatePeeringConnection("peeringConnection", new VPCPeeringConnectionOptions {
AcceptorVpc = acceptorVpc
});
var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = requestorVpc
});
routeTable.AddRoute("vpcPeeringRoute", "10.0.0.0/16", new Dictionary<string, IRouteTarget?> { { "gateway", peeringConnection } });
stack := awscdk.Newstack()
acceptorVpc := awsec2alpha.NewVpcV2(this, jsii.String("VpcA"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.0.0.0/16")),
})
requestorVpc := awsec2alpha.NewVpcV2(this, jsii.String("VpcB"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_*Ipv4(jsii.String("10.1.0.0/16")),
})
peeringConnection := requestorVpc.CreatePeeringConnection(jsii.String("peeringConnection"), &VPCPeeringConnectionOptions{
AcceptorVpc: acceptorVpc,
})
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: requestorVpc,
})
routeTable.AddRoute(jsii.String("vpcPeeringRoute"), jsii.String("10.0.0.0/16"), map[string]iRouteTarget{
"gateway": peeringConnection,
})
This can also be done using AWS CLI. For more information, see create-route.
# Add a route to the requestor VPC route table
aws ec2 create-route --route-table-id rtb-requestor --destination-cidr-block 10.0.0.0/16 --vpc-peering-connection-id pcx-xxxxxxxx
# For bi-directional add a route in the acceptor vpc account as well
aws ec2 create-route --route-table-id rtb-acceptor --destination-cidr-block 10.1.0.0/16 --vpc-peering-connection-id pcx-xxxxxxxx
Deleting the Peering Connection
To delete a VPC peering connection, use the following command:
aws ec2 delete-vpc-peering-connection --vpc-peering-connection-id pcx-xxxxxxxx
For more information, see Delete a VPC peering connection.
Adding Egress-Only Internet Gateway to VPC
An egress-only internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows outbound communication over IPv6 from instances in your VPC to the internet, and prevents the internet from initiating an IPv6 connection with your instances.
For more information see Enable outbound IPv6 traffic using an egress-only internet gateway.
VpcV2 supports adding an egress only internet gateway to VPC using the addEgressOnlyInternetGateway method.
By default, this method sets up a route to all outbound IPv6 address ranges, unless a specific destination is provided by the user. It can only be configured for IPv6-enabled VPCs. The Subnets parameter accepts a SubnetFilter, which can be based on a SubnetType in VpcV2. A new route will be added to the route tables of all subnets that match this filter.
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc',{
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
secondaryAddressBlocks: [IpAddresses.amazonProvidedIpv6({
cidrBlockName: 'AmazonProvided',
})]
});
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: myVpc,
});
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
ipv6CidrBlock: new IpCidr('2001:db8:1::/64'),
subnetType: SubnetType.PRIVATE });
myVpc.addEgressOnlyInternetGateway({
subnets: [{subnetType: SubnetType.PRIVATE}],
destination: '::/60',
})
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"
)]
)
route_table = RouteTable(self, "RouteTable",
vpc=my_vpc
)
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
ipv6_cidr_block=IpCidr("2001:db8:1::/64"),
subnet_type=SubnetType.PRIVATE
)
my_vpc.add_egress_only_internet_gateway(
subnets=[ec2.SubnetSelection(subnet_type=SubnetType.PRIVATE)],
destination="::/60"
)
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();
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(myVpc)
.build();
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.ipv6CidrBlock(new IpCidr("2001:db8:1::/64"))
.subnetType(SubnetType.PRIVATE)
.build();
myVpc.addEgressOnlyInternetGateway(EgressOnlyInternetGatewayOptions.builder()
.subnets(List.of(SubnetSelection.builder().subnetType(SubnetType.PRIVATE).build()))
.destination("::/60")
.build());
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 routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = myVpc
});
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
Ipv6CidrBlock = new IpCidr("2001:db8:1::/64"),
SubnetType = SubnetType.PRIVATE
});
myVpc.AddEgressOnlyInternetGateway(new EgressOnlyInternetGatewayOptions {
Subnets = new [] { new SubnetSelection { SubnetType = SubnetType.PRIVATE } },
Destination = "::/60"
});
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"),
}),
},
})
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: myVpc,
})
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
Ipv6CidrBlock: awsec2alpha.NewIpCidr(jsii.String("2001:db8:1::/64")),
SubnetType: awscdk.SubnetType_PRIVATE,
})
myVpc.AddEgressOnlyInternetGateway(&EgressOnlyInternetGatewayOptions{
Subnets: []SubnetSelection{
&SubnetSelection{
SubnetType: awscdk.SubnetType_PRIVATE,
},
},
Destination: jsii.String("::/60"),
})
Adding NATGateway to the VPC
A NAT gateway is a Network Address Translation (NAT) service.You can use a NAT gateway so that instances in a private subnet can connect to services outside your VPC but external services cannot initiate a connection with those instances.
For more information, see NAT gateway basics.
When you create a NAT gateway, you specify one of the following connectivity types:
Public – (Default): Instances in private subnets can connect to the internet through a public NAT gateway, but cannot receive unsolicited inbound connections from the internet
Private: Instances in private subnets can connect to other VPCs or your on-premises network through a private NAT gateway.
To define the NAT gateway connectivity type as ConnectivityType.Public, you need to ensure that there is an IGW(Internet Gateway) attached to the subnet's VPC. Since a NATGW is associated with a particular subnet, providing subnet field in the input props is mandatory.
Additionally, you can set up a route in any route table with the target set to the NAT Gateway. The function addNatGateway returns a NATGateway object that you can reference later.
The code example below provides the definition for adding a NAT gateway to your subnet:
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
const routeTable = new RouteTable(this, 'RouteTable', {
vpc: myVpc,
});
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC });
myVpc.addInternetGateway();
myVpc.addNatGateway({
subnet: subnet,
connectivityType: NatConnectivityType.PUBLIC,
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
route_table = RouteTable(self, "RouteTable",
vpc=my_vpc
)
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
my_vpc.add_internet_gateway()
my_vpc.add_nat_gateway(
subnet=subnet,
connectivity_type=NatConnectivityType.PUBLIC
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
RouteTable routeTable = RouteTable.Builder.create(this, "RouteTable")
.vpc(myVpc)
.build();
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
myVpc.addInternetGateway();
myVpc.addNatGateway(NatGatewayOptions.builder()
.subnet(subnet)
.connectivityType(NatConnectivityType.PUBLIC)
.build());
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
var routeTable = new RouteTable(this, "RouteTable", new RouteTableProps {
Vpc = myVpc
});
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
myVpc.AddInternetGateway();
myVpc.AddNatGateway(new NatGatewayOptions {
Subnet = subnet,
ConnectivityType = NatConnectivityType.PUBLIC
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
routeTable := awsec2alpha.NewRouteTable(this, jsii.String("RouteTable"), &RouteTableProps{
Vpc: myVpc,
})
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
myVpc.AddInternetGateway()
myVpc.AddNatGateway(&NatGatewayOptions{
Subnet: subnet,
ConnectivityType: awsec2alpha.NatConnectivityType_PUBLIC,
})
Enable VPNGateway for the VPC
A virtual private gateway is the endpoint on the VPC side of your VPN connection.
For more information, see What is AWS Site-to-Site VPN?.
VPN route propagation is a feature in Amazon Web Services (AWS) that automatically updates route tables in your Virtual Private Cloud (VPC) with routes learned from a VPN connection.
To enable VPN route propagation, use the vpnRoutePropagation property to specify the subnets as an input to the function. VPN route propagation will then be enabled for each subnet with the corresponding route table IDs.
Additionally, you can set up a route in any route table with the target set to the VPN Gateway. The function enableVpnGatewayV2 returns a VPNGatewayV2 object that you can reference later.
The code example below provides the definition for setting up a VPN gateway with vpnRoutePropagation enabled:
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
const vpnGateway = myVpc.enableVpnGatewayV2({
vpnRoutePropagation: [{ subnetType: SubnetType.PUBLIC }],
type: VpnConnectionType.IPSEC_1,
});
const routeTable = new RouteTable(stack, 'routeTable', {
vpc: myVpc
} );
new Route(stack, 'route', {
destination: '172.31.0.0/24',
target: { gateway: vpnGateway },
routeTable: routeTable,
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
vpn_gateway = my_vpc.enable_vpn_gateway_v2(
vpn_route_propagation=[ec2.SubnetSelection(subnet_type=SubnetType.PUBLIC)],
type=VpnConnectionType.IPSEC_1
)
route_table = RouteTable(stack, "routeTable",
vpc=my_vpc
)
Route(stack, "route",
destination="172.31.0.0/24",
target={"gateway": vpn_gateway},
route_table=route_table
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
VPNGatewayV2 vpnGateway = myVpc.enableVpnGatewayV2(VPNGatewayV2Options.builder()
.vpnRoutePropagation(List.of(SubnetSelection.builder().subnetType(SubnetType.PUBLIC).build()))
.type(VpnConnectionType.IPSEC_1)
.build());
RouteTable routeTable = RouteTable.Builder.create(stack, "routeTable")
.vpc(myVpc)
.build();
Route.Builder.create(stack, "route")
.destination("172.31.0.0/24")
.target(Map.of("gateway", vpnGateway))
.routeTable(routeTable)
.build();
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
var vpnGateway = myVpc.EnableVpnGatewayV2(new VPNGatewayV2Options {
VpnRoutePropagation = new [] { new SubnetSelection { SubnetType = SubnetType.PUBLIC } },
Type = VpnConnectionType.IPSEC_1
});
var routeTable = new RouteTable(stack, "routeTable", new RouteTableProps {
Vpc = myVpc
});
new Route(stack, "route", new RouteProps {
Destination = "172.31.0.0/24",
Target = new Dictionary<string, IRouteTarget?> { { "gateway", vpnGateway } },
RouteTable = routeTable
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
vpnGateway := myVpc.EnableVpnGatewayV2(&VPNGatewayV2Options{
VpnRoutePropagation: []SubnetSelection{
&SubnetSelection{
SubnetType: awscdk.SubnetType_PUBLIC,
},
},
Type: awscdk.VpnConnectionType_IPSEC_1,
})
routeTable := awsec2alpha.NewRouteTable(stack, jsii.String("routeTable"), &RouteTableProps{
Vpc: myVpc,
})
awsec2alpha.NewRoute(stack, jsii.String("route"), &RouteProps{
Destination: jsii.String("172.31.0.0/24"),
Target: map[string]iRouteTarget{
"gateway": vpnGateway,
},
RouteTable: routeTable,
})
Adding InternetGateway to the VPC
An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between your VPC and the internet. It supports both IPv4 and IPv6 traffic.
For more information, see Enable VPC internet access using internet gateways.
You can add an internet gateway to a VPC using addInternetGateway method. By default, this method creates a route in all Public Subnets with outbound destination set to 0.0.0.0 for IPv4 and ::0 for IPv6 enabled VPC. Instead of using the default settings, you can configure a custom destination range by providing an optional input destination to the method. In addition to the custom IP range, you can also choose to filter subnets where default routes should be created.
The code example below shows how to add an internet gateway with a custom outbound destination IP range:
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC });
myVpc.addInternetGateway({
ipv4Destination: '192.168.0.0/16',
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
my_vpc.add_internet_gateway(
ipv4_destination="192.168.0.0/16"
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
myVpc.addInternetGateway(InternetGatewayOptions.builder()
.ipv4Destination("192.168.0.0/16")
.build());
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
myVpc.AddInternetGateway(new InternetGatewayOptions {
Ipv4Destination = "192.168.0.0/16"
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
myVpc.AddInternetGateway(&InternetGatewayOptions{
Ipv4Destination: jsii.String("192.168.0.0/16"),
})
The following code examples demonstrates how to add an internet gateway with a custom outbound destination IP range for specific subnets:
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
const mySubnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC });
myVpc.addInternetGateway({
ipv4Destination: '192.168.0.0/16',
subnets: [mySubnet],
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
my_subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
my_vpc.add_internet_gateway(
ipv4_destination="192.168.0.0/16",
subnets=[my_subnet]
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
SubnetV2 mySubnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
myVpc.addInternetGateway(InternetGatewayOptions.builder()
.ipv4Destination("192.168.0.0/16")
.subnets(List.of(mySubnet))
.build());
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
var mySubnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
myVpc.AddInternetGateway(new InternetGatewayOptions {
Ipv4Destination = "192.168.0.0/16",
Subnets = new [] { mySubnet }
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
mySubnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
myVpc.AddInternetGateway(&InternetGatewayOptions{
Ipv4Destination: jsii.String("192.168.0.0/16"),
Subnets: []SubnetSelection{
mySubnet,
},
})
const stack = new Stack();
const myVpc = new VpcV2(this, 'Vpc');
myVpc.addInternetGateway({
ipv4Destination: '192.168.0.0/16',
subnets: [{subnetType: SubnetType.PRIVATE_WITH_EGRESS}],
});
stack = Stack()
my_vpc = VpcV2(self, "Vpc")
my_vpc.add_internet_gateway(
ipv4_destination="192.168.0.0/16",
subnets=[ec2.SubnetSelection(subnet_type=SubnetType.PRIVATE_WITH_EGRESS)]
)
Stack stack = new Stack();
VpcV2 myVpc = new VpcV2(this, "Vpc");
myVpc.addInternetGateway(InternetGatewayOptions.builder()
.ipv4Destination("192.168.0.0/16")
.subnets(List.of(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_WITH_EGRESS).build()))
.build());
var stack = new Stack();
var myVpc = new VpcV2(this, "Vpc");
myVpc.AddInternetGateway(new InternetGatewayOptions {
Ipv4Destination = "192.168.0.0/16",
Subnets = new [] { new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS } }
});
stack := awscdk.Newstack()
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
myVpc.AddInternetGateway(&InternetGatewayOptions{
Ipv4Destination: jsii.String("192.168.0.0/16"),
Subnets: []SubnetSelection{
&SubnetSelection{
SubnetType: awscdk.SubnetType_PRIVATE_WITH_EGRESS,
},
},
})
Importing an existing VPC
You can import an existing VPC and its subnets using the VpcV2.fromVpcV2Attributes() method or an individual subnet using SubnetV2.fromSubnetV2Attributes() method.
Importing a VPC
To import an existing VPC, use the VpcV2.fromVpcV2Attributes() method. You'll need to provide the VPC ID, primary CIDR block, and information about the subnets. You can import secondary address as well created through IPAM, BYOIP(IPv4) or enabled through Amazon Provided IPv6. You must provide VPC Id and its primary CIDR block for importing it.
If you wish to add a new subnet to imported VPC, new subnet's IP range(IPv4) will be validated against provided secondary and primary address block to confirm that it is within the range of VPC.
Here's an example of importing a VPC with only the required parameters
const stack = new Stack();
const importedVpc = VpcV2.fromVpcV2Attributes(stack, 'ImportedVpc', {
vpcId: 'mockVpcID',
vpcCidrBlock: '10.0.0.0/16',
});
stack = Stack()
imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
vpc_id="mockVpcID",
vpc_cidr_block="10.0.0.0/16"
)
Stack stack = new Stack();
IVpcV2 importedVpc = VpcV2.fromVpcV2Attributes(stack, "ImportedVpc", VpcV2Attributes.builder()
.vpcId("mockVpcID")
.vpcCidrBlock("10.0.0.0/16")
.build());
var stack = new Stack();
var importedVpc = VpcV2.FromVpcV2Attributes(stack, "ImportedVpc", new VpcV2Attributes {
VpcId = "mockVpcID",
VpcCidrBlock = "10.0.0.0/16"
});
stack := awscdk.Newstack()
importedVpc := awsec2alpha.VpcV2_FromVpcV2Attributes(stack, jsii.String("ImportedVpc"), &VpcV2Attributes{
VpcId: jsii.String("mockVpcID"),
VpcCidrBlock: jsii.String("10.0.0.0/16"),
})
In case of cross account or cross region VPC, its recommended to provide region and ownerAccountId so that these values for the VPC can be used to populate correct arn value for the VPC. If a VPC region and account ID is not provided, then region and account configured in the stack will be used. Furthermore, these fields will be referenced later while setting up VPC peering connection, so its necessary to set these fields to a correct value.
Below is an example of importing a cross region and cross account VPC, VPC arn for this case would be 'arn:aws:ec2:us-west-2:123456789012:vpc/mockVpcID'
const stack = new Stack();
//Importing a cross account or cross region VPC
const importedVpc = VpcV2.fromVpcV2Attributes(stack, 'ImportedVpc', {
vpcId: 'mockVpcID',
vpcCidrBlock: '10.0.0.0/16',
ownerAccountId: '123456789012',
region: 'us-west-2',
});
stack = Stack()
# Importing a cross account or cross region VPC
imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
vpc_id="mockVpcID",
vpc_cidr_block="10.0.0.0/16",
owner_account_id="123456789012",
region="us-west-2"
)
Stack stack = new Stack();
//Importing a cross account or cross region VPC
IVpcV2 importedVpc = VpcV2.fromVpcV2Attributes(stack, "ImportedVpc", VpcV2Attributes.builder()
.vpcId("mockVpcID")
.vpcCidrBlock("10.0.0.0/16")
.ownerAccountId("123456789012")
.region("us-west-2")
.build());
var stack = new Stack();
//Importing a cross account or cross region VPC
var importedVpc = VpcV2.FromVpcV2Attributes(stack, "ImportedVpc", new VpcV2Attributes {
VpcId = "mockVpcID",
VpcCidrBlock = "10.0.0.0/16",
OwnerAccountId = "123456789012",
Region = "us-west-2"
});
stack := awscdk.Newstack()
//Importing a cross account or cross region VPC
importedVpc := awsec2alpha.VpcV2_FromVpcV2Attributes(stack, jsii.String("ImportedVpc"), &VpcV2Attributes{
VpcId: jsii.String("mockVpcID"),
VpcCidrBlock: jsii.String("10.0.0.0/16"),
OwnerAccountId: jsii.String("123456789012"),
Region: jsii.String("us-west-2"),
})
Here's an example of how to import a VPC with multiple CIDR blocks, IPv6 support, and different subnet types:
In this example, we're importing a VPC with:
- A primary CIDR block (10.1.0.0/16)
- One secondary IPv4 CIDR block (10.2.0.0/16)
- Two secondary address using IPAM pool (IPv4 and IPv6)
- VPC has Amazon-provided IPv6 CIDR enabled
- An isolated subnet in us-west-2a
- A public subnet in us-west-2b
const stack = new Stack();
const importedVpc = VpcV2.fromVpcV2Attributes(this, 'ImportedVPC', {
vpcId: 'vpc-XXX',
vpcCidrBlock: '10.1.0.0/16',
secondaryCidrBlocks: [
{
cidrBlock: '10.2.0.0/16',
cidrBlockName: 'ImportedBlock1',
},
{
ipv6IpamPoolId: 'ipam-pool-XXX',
ipv6NetmaskLength: 52,
cidrBlockName: 'ImportedIpamIpv6',
},
{
ipv4IpamPoolId: 'ipam-pool-XXX',
ipv4IpamProvisionedCidrs: ['10.2.0.0/16'],
cidrBlockName: 'ImportedIpamIpv4',
},
{
amazonProvidedIpv6CidrBlock: true,
}
],
subnets: [{
subnetName: 'IsolatedSubnet2',
subnetId: 'subnet-03cd773c0fe08ed26',
subnetType: SubnetType.PRIVATE_ISOLATED,
availabilityZone: 'us-west-2a',
ipv4CidrBlock: '10.2.0.0/24',
routeTableId: 'rtb-0871c310f98da2cbb',
},
{
subnetId: 'subnet-0fa477e01db27d820',
subnetType: SubnetType.PUBLIC,
availabilityZone: 'us-west-2b',
ipv4CidrBlock: '10.3.0.0/24',
routeTableId: 'rtb-014f3043098fe4b96',
}],
});
// You can now use the imported VPC in your stack
// Adding a new subnet to the imported VPC
const importedSubnet = new SubnetV2(this, 'NewSubnet', {
availabilityZone: 'us-west-2a',
ipv4CidrBlock: new IpCidr('10.2.2.0/24'),
vpc: importedVpc,
subnetType: SubnetType.PUBLIC,
});
// Adding gateways to the imported VPC
importedVpc.addInternetGateway();
importedVpc.addNatGateway({ subnet: importedSubnet });
importedVpc.addEgressOnlyInternetGateway();
from aws_cdk.aws_ec2_alpha import VPCCidrBlockattributes, VPCCidrBlockattributes, VPCCidrBlockattributes, VPCCidrBlockattributes, SubnetV2Attributes, SubnetV2Attributes
stack = Stack()
imported_vpc = VpcV2.from_vpc_v2_attributes(self, "ImportedVPC",
vpc_id="vpc-XXX",
vpc_cidr_block="10.1.0.0/16",
secondary_cidr_blocks=[VPCCidrBlockattributes(
cidr_block="10.2.0.0/16",
cidr_block_name="ImportedBlock1"
), VPCCidrBlockattributes(
ipv6_ipam_pool_id="ipam-pool-XXX",
ipv6_netmask_length=52,
cidr_block_name="ImportedIpamIpv6"
), VPCCidrBlockattributes(
ipv4_ipam_pool_id="ipam-pool-XXX",
ipv4_ipam_provisioned_cidrs=["10.2.0.0/16"],
cidr_block_name="ImportedIpamIpv4"
), VPCCidrBlockattributes(
amazon_provided_ipv6_cidr_block=True
)
],
subnets=[SubnetV2Attributes(
subnet_name="IsolatedSubnet2",
subnet_id="subnet-03cd773c0fe08ed26",
subnet_type=SubnetType.PRIVATE_ISOLATED,
availability_zone="us-west-2a",
ipv4_cidr_block="10.2.0.0/24",
route_table_id="rtb-0871c310f98da2cbb"
), SubnetV2Attributes(
subnet_id="subnet-0fa477e01db27d820",
subnet_type=SubnetType.PUBLIC,
availability_zone="us-west-2b",
ipv4_cidr_block="10.3.0.0/24",
route_table_id="rtb-014f3043098fe4b96"
)]
)
# You can now use the imported VPC in your stack
# Adding a new subnet to the imported VPC
imported_subnet = SubnetV2(self, "NewSubnet",
availability_zone="us-west-2a",
ipv4_cidr_block=IpCidr("10.2.2.0/24"),
vpc=imported_vpc,
subnet_type=SubnetType.PUBLIC
)
# Adding gateways to the imported VPC
imported_vpc.add_internet_gateway()
imported_vpc.add_nat_gateway(subnet=imported_subnet)
imported_vpc.add_egress_only_internet_gateway()
Stack stack = new Stack();
IVpcV2 importedVpc = VpcV2.fromVpcV2Attributes(this, "ImportedVPC", VpcV2Attributes.builder()
.vpcId("vpc-XXX")
.vpcCidrBlock("10.1.0.0/16")
.secondaryCidrBlocks(List.of(VPCCidrBlockattributes.builder()
.cidrBlock("10.2.0.0/16")
.cidrBlockName("ImportedBlock1")
.build(), VPCCidrBlockattributes.builder()
.ipv6IpamPoolId("ipam-pool-XXX")
.ipv6NetmaskLength(52)
.cidrBlockName("ImportedIpamIpv6")
.build(), VPCCidrBlockattributes.builder()
.ipv4IpamPoolId("ipam-pool-XXX")
.ipv4IpamProvisionedCidrs(List.of("10.2.0.0/16"))
.cidrBlockName("ImportedIpamIpv4")
.build(), VPCCidrBlockattributes.builder()
.amazonProvidedIpv6CidrBlock(true)
.build()))
.subnets(List.of(SubnetV2Attributes.builder()
.subnetName("IsolatedSubnet2")
.subnetId("subnet-03cd773c0fe08ed26")
.subnetType(SubnetType.PRIVATE_ISOLATED)
.availabilityZone("us-west-2a")
.ipv4CidrBlock("10.2.0.0/24")
.routeTableId("rtb-0871c310f98da2cbb")
.build(), SubnetV2Attributes.builder()
.subnetId("subnet-0fa477e01db27d820")
.subnetType(SubnetType.PUBLIC)
.availabilityZone("us-west-2b")
.ipv4CidrBlock("10.3.0.0/24")
.routeTableId("rtb-014f3043098fe4b96")
.build()))
.build());
// You can now use the imported VPC in your stack
// Adding a new subnet to the imported VPC
SubnetV2 importedSubnet = SubnetV2.Builder.create(this, "NewSubnet")
.availabilityZone("us-west-2a")
.ipv4CidrBlock(new IpCidr("10.2.2.0/24"))
.vpc(importedVpc)
.subnetType(SubnetType.PUBLIC)
.build();
// Adding gateways to the imported VPC
importedVpc.addInternetGateway();
importedVpc.addNatGateway(NatGatewayOptions.builder().subnet(importedSubnet).build());
importedVpc.addEgressOnlyInternetGateway();
var stack = new Stack();
var importedVpc = VpcV2.FromVpcV2Attributes(this, "ImportedVPC", new VpcV2Attributes {
VpcId = "vpc-XXX",
VpcCidrBlock = "10.1.0.0/16",
SecondaryCidrBlocks = new [] { new VPCCidrBlockattributes {
CidrBlock = "10.2.0.0/16",
CidrBlockName = "ImportedBlock1"
}, new VPCCidrBlockattributes {
Ipv6IpamPoolId = "ipam-pool-XXX",
Ipv6NetmaskLength = 52,
CidrBlockName = "ImportedIpamIpv6"
}, new VPCCidrBlockattributes {
Ipv4IpamPoolId = "ipam-pool-XXX",
Ipv4IpamProvisionedCidrs = new [] { "10.2.0.0/16" },
CidrBlockName = "ImportedIpamIpv4"
}, new VPCCidrBlockattributes {
AmazonProvidedIpv6CidrBlock = true
} },
Subnets = new [] { new SubnetV2Attributes {
SubnetName = "IsolatedSubnet2",
SubnetId = "subnet-03cd773c0fe08ed26",
SubnetType = SubnetType.PRIVATE_ISOLATED,
AvailabilityZone = "us-west-2a",
Ipv4CidrBlock = "10.2.0.0/24",
RouteTableId = "rtb-0871c310f98da2cbb"
}, new SubnetV2Attributes {
SubnetId = "subnet-0fa477e01db27d820",
SubnetType = SubnetType.PUBLIC,
AvailabilityZone = "us-west-2b",
Ipv4CidrBlock = "10.3.0.0/24",
RouteTableId = "rtb-014f3043098fe4b96"
} }
});
// You can now use the imported VPC in your stack
// Adding a new subnet to the imported VPC
var importedSubnet = new SubnetV2(this, "NewSubnet", new SubnetV2Props {
AvailabilityZone = "us-west-2a",
Ipv4CidrBlock = new IpCidr("10.2.2.0/24"),
Vpc = importedVpc,
SubnetType = SubnetType.PUBLIC
});
// Adding gateways to the imported VPC
importedVpc.AddInternetGateway();
importedVpc.AddNatGateway(new NatGatewayOptions { Subnet = importedSubnet });
importedVpc.AddEgressOnlyInternetGateway();
stack := awscdk.Newstack()
importedVpc := awsec2alpha.VpcV2_FromVpcV2Attributes(this, jsii.String("ImportedVPC"), &VpcV2Attributes{
VpcId: jsii.String("vpc-XXX"),
VpcCidrBlock: jsii.String("10.1.0.0/16"),
SecondaryCidrBlocks: []VPCCidrBlockattributes{
&VPCCidrBlockattributes{
CidrBlock: jsii.String("10.2.0.0/16"),
CidrBlockName: jsii.String("ImportedBlock1"),
},
&VPCCidrBlockattributes{
Ipv6IpamPoolId: jsii.String("ipam-pool-XXX"),
Ipv6NetmaskLength: jsii.Number(52),
CidrBlockName: jsii.String("ImportedIpamIpv6"),
},
&VPCCidrBlockattributes{
Ipv4IpamPoolId: jsii.String("ipam-pool-XXX"),
Ipv4IpamProvisionedCidrs: []*string{
jsii.String("10.2.0.0/16"),
},
CidrBlockName: jsii.String("ImportedIpamIpv4"),
},
&VPCCidrBlockattributes{
AmazonProvidedIpv6CidrBlock: jsii.Boolean(true),
},
},
Subnets: []SubnetV2Attributes{
&SubnetV2Attributes{
SubnetName: jsii.String("IsolatedSubnet2"),
SubnetId: jsii.String("subnet-03cd773c0fe08ed26"),
SubnetType: awscdk.SubnetType_PRIVATE_ISOLATED,
AvailabilityZone: jsii.String("us-west-2a"),
Ipv4CidrBlock: jsii.String("10.2.0.0/24"),
RouteTableId: jsii.String("rtb-0871c310f98da2cbb"),
},
&SubnetV2Attributes{
SubnetId: jsii.String("subnet-0fa477e01db27d820"),
SubnetType: awscdk.SubnetType_PUBLIC,
AvailabilityZone: jsii.String("us-west-2b"),
Ipv4CidrBlock: jsii.String("10.3.0.0/24"),
RouteTableId: jsii.String("rtb-014f3043098fe4b96"),
},
},
})
// You can now use the imported VPC in your stack
// Adding a new subnet to the imported VPC
importedSubnet := awsec2alpha.NewSubnetV2(this, jsii.String("NewSubnet"), &SubnetV2Props{
AvailabilityZone: jsii.String("us-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.2.2.0/24")),
Vpc: importedVpc,
SubnetType: awscdk.SubnetType_PUBLIC,
})
// Adding gateways to the imported VPC
importedVpc.AddInternetGateway()
importedVpc.AddNatGateway(&NatGatewayOptions{
Subnet: importedSubnet,
})
importedVpc.AddEgressOnlyInternetGateway()
You can add more subnets as needed by including additional entries in the isolatedSubnets, publicSubnets, or other subnet type arrays (e.g., privateSubnets).
Importing Subnets
You can also import individual subnets using the SubnetV2.fromSubnetV2Attributes() method. This is useful when you need to work with specific subnets independently of a VPC.
Here's an example of how to import a subnet:
SubnetV2.fromSubnetV2Attributes(this, 'ImportedSubnet', {
subnetId: 'subnet-0123456789abcdef0',
availabilityZone: 'us-west-2a',
ipv4CidrBlock: '10.2.0.0/24',
routeTableId: 'rtb-0871c310f98da2cbb',
subnetType: SubnetType.PRIVATE_ISOLATED,
});
SubnetV2.from_subnet_v2_attributes(self, "ImportedSubnet",
subnet_id="subnet-0123456789abcdef0",
availability_zone="us-west-2a",
ipv4_cidr_block="10.2.0.0/24",
route_table_id="rtb-0871c310f98da2cbb",
subnet_type=SubnetType.PRIVATE_ISOLATED
)
SubnetV2.fromSubnetV2Attributes(this, "ImportedSubnet", SubnetV2Attributes.builder()
.subnetId("subnet-0123456789abcdef0")
.availabilityZone("us-west-2a")
.ipv4CidrBlock("10.2.0.0/24")
.routeTableId("rtb-0871c310f98da2cbb")
.subnetType(SubnetType.PRIVATE_ISOLATED)
.build());
SubnetV2.FromSubnetV2Attributes(this, "ImportedSubnet", new SubnetV2Attributes {
SubnetId = "subnet-0123456789abcdef0",
AvailabilityZone = "us-west-2a",
Ipv4CidrBlock = "10.2.0.0/24",
RouteTableId = "rtb-0871c310f98da2cbb",
SubnetType = SubnetType.PRIVATE_ISOLATED
});
awsec2alpha.SubnetV2_FromSubnetV2Attributes(this, jsii.String("ImportedSubnet"), &SubnetV2Attributes{
SubnetId: jsii.String("subnet-0123456789abcdef0"),
AvailabilityZone: jsii.String("us-west-2a"),
Ipv4CidrBlock: jsii.String("10.2.0.0/24"),
RouteTableId: jsii.String("rtb-0871c310f98da2cbb"),
SubnetType: awscdk.SubnetType_PRIVATE_ISOLATED,
})
By importing existing VPCs and subnets, you can easily integrate your existing AWS infrastructure with new resources created through CDK. This is particularly useful when you need to work with pre-existing network configurations or when you're migrating existing infrastructure to CDK.
Tagging VPC and its components
By default, when a resource name is given to the construct, it automatically adds a tag with the key Name and the value set to the provided resource name. To add additional custom tags, use the Tag Manager, like this: Tags.of(myConstruct).add('key', 'value');.
For example, if the vpcName is set to TestVpc, the following code will add a tag to the VPC with key: Name and value: TestVpc.
const vpc = new VpcV2(this, 'VPC-integ-test-tag', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
enableDnsHostnames: true,
enableDnsSupport: true,
vpcName: 'CDKintegTestVPC',
});
// Add custom tags if needed
Tags.of(vpc).add('Environment', 'Production');
vpc = VpcV2(self, "VPC-integ-test-tag",
primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
enable_dns_hostnames=True,
enable_dns_support=True,
vpc_name="CDKintegTestVPC"
)
# Add custom tags if needed
Tags.of(vpc).add("Environment", "Production")
VpcV2 vpc = VpcV2.Builder.create(this, "VPC-integ-test-tag")
.primaryAddressBlock(IpAddresses.ipv4("10.1.0.0/16"))
.enableDnsHostnames(true)
.enableDnsSupport(true)
.vpcName("CDKintegTestVPC")
.build();
// Add custom tags if needed
Tags.of(vpc).add("Environment", "Production");
var vpc = new VpcV2(this, "VPC-integ-test-tag", new VpcV2Props {
PrimaryAddressBlock = IpAddresses.Ipv4("10.1.0.0/16"),
EnableDnsHostnames = true,
EnableDnsSupport = true,
VpcName = "CDKintegTestVPC"
});
// Add custom tags if needed
Tags.Of(vpc).Add("Environment", "Production");
vpc := awsec2alpha.NewVpcV2(this, jsii.String("VPC-integ-test-tag"), &VpcV2Props{
PrimaryAddressBlock: awsec2alpha.IpAddresses_Ipv4(jsii.String("10.1.0.0/16")),
EnableDnsHostnames: jsii.Boolean(true),
EnableDnsSupport: jsii.Boolean(true),
VpcName: jsii.String("CDKintegTestVPC"),
})
// Add custom tags if needed
awscdk.Tags_Of(vpc).Add(jsii.String("Environment"), jsii.String("Production"))
Transit Gateway
The AWS Transit Gateway construct library allows you to create and configure Transit Gateway resources using AWS CDK.
See AWS Transit Gateway Docs for more info.
Overview
The Transit Gateway construct (TransitGateway) is the main entry point for creating and managing your Transit Gateway infrastructure. It provides methods to create route tables, attach VPCs, and configure cross-account access.
The Transit Gateway construct library provides four main constructs:
TransitGateway: The central hub for your network connectionsTransitGatewayRouteTable: Manages routing between attached networksTransitGatewayVpcAttachment: Connects VPCs to the Transit GatewayTransitGatewayRoute: Defines routing rules within your Transit Gateway
Basic Usage
To create a minimal deployable TransitGateway:
const transitGateway = new TransitGateway(this, 'MyTransitGateway');
transit_gateway = TransitGateway(self, "MyTransitGateway")
TransitGateway transitGateway = new TransitGateway(this, "MyTransitGateway");
var transitGateway = new TransitGateway(this, "MyTransitGateway");
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"))
Default Transit Gateway Route Table
By default, TransitGateway is created with a default TransitGatewayRouteTable, for which automatic Associations and automatic Propagations are enabled.
Note: When you create a default Transit Gateway in AWS Console, a default Transit Gateway Route Table is automatically created by AWS. However, when using the CDK Transit Gateway L2 construct, the underlying L1 construct is configured with
defaultRouteTableAssociationanddefaultRouteTablePropagationexplicitly disabled. This ensures that AWS does not create the default route table, allowing the CDK to define a custom default route table instead.As a result, in the AWS Console, the Default association route table and Default propagation route table settings will appear as disabled. Despite this, the CDK still provides automatic association and propagation functionality through its internal implementation, which can be controlled using the
defaultRouteTableAssociationanddefaultRouteTablePropagationproperties within the CDK.
You can disable the automatic Association/Propagation on the default TransitGatewayRouteTable via the TransitGateway properties. This will still create a default route table for you:
const transitGateway = new TransitGateway(this, 'MyTransitGateway', {
defaultRouteTableAssociation: false,
defaultRouteTablePropagation: false,
});
transit_gateway = TransitGateway(self, "MyTransitGateway",
default_route_table_association=False,
default_route_table_propagation=False
)
TransitGateway transitGateway = TransitGateway.Builder.create(this, "MyTransitGateway")
.defaultRouteTableAssociation(false)
.defaultRouteTablePropagation(false)
.build();
var transitGateway = new TransitGateway(this, "MyTransitGateway", new TransitGatewayProps {
DefaultRouteTableAssociation = false,
DefaultRouteTablePropagation = false
});
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"), &TransitGatewayProps{
DefaultRouteTableAssociation: jsii.Boolean(false),
DefaultRouteTablePropagation: jsii.Boolean(false),
})
Transit Gateway Route Table Management
Add additional Transit Gateway Route Tables using the addRouteTable() method:
const transitGateway = new TransitGateway(this, 'MyTransitGateway');
const routeTable = transitGateway.addRouteTable('CustomRouteTable');
transit_gateway = TransitGateway(self, "MyTransitGateway")
route_table = transit_gateway.add_route_table("CustomRouteTable")
TransitGateway transitGateway = new TransitGateway(this, "MyTransitGateway");
ITransitGatewayRouteTable routeTable = transitGateway.addRouteTable("CustomRouteTable");
var transitGateway = new TransitGateway(this, "MyTransitGateway");
var routeTable = transitGateway.AddRouteTable("CustomRouteTable");
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"))
routeTable := transitGateway.addRouteTable(jsii.String("CustomRouteTable"))
Attaching VPCs to the Transit Gateway
Currently only VPC to Transit Gateway attachments are supported.
Create an attachment from a VPC to the Transit Gateway using the attachVpc() method:
const myVpc = new VpcV2(this, 'Vpc');
const subnet1 = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC
});
const subnet2 = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.1.0/24'),
subnetType: SubnetType.PUBLIC
});
const transitGateway = new TransitGateway(this, 'MyTransitGateway');
// Create a basic attachment
const attachment = transitGateway.attachVpc('VpcAttachment', {
vpc: myVpc,
subnets: [subnet1, subnet2]
});
// Create an attachment with optional parameters
const attachmentWithOptions = transitGateway.attachVpc('VpcAttachmentWithOptions', {
vpc: myVpc,
subnets: [subnet1],
vpcAttachmentOptions: {
dnsSupport: true,
applianceModeSupport: true,
ipv6Support: true,
securityGroupReferencingSupport: true,
}
});
my_vpc = VpcV2(self, "Vpc")
subnet1 = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
subnet2 = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.1.0/24"),
subnet_type=SubnetType.PUBLIC
)
transit_gateway = TransitGateway(self, "MyTransitGateway")
# Create a basic attachment
attachment = transit_gateway.attach_vpc("VpcAttachment",
vpc=my_vpc,
subnets=[subnet1, subnet2]
)
# Create an attachment with optional parameters
attachment_with_options = transit_gateway.attach_vpc("VpcAttachmentWithOptions",
vpc=my_vpc,
subnets=[subnet1],
vpc_attachment_options={
"dns_support": True,
"appliance_mode_support": True,
"ipv6_support": True,
"security_group_referencing_support": True
}
)
VpcV2 myVpc = new VpcV2(this, "Vpc");
SubnetV2 subnet1 = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
SubnetV2 subnet2 = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.1.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
TransitGateway transitGateway = new TransitGateway(this, "MyTransitGateway");
// Create a basic attachment
ITransitGatewayVpcAttachment attachment = transitGateway.attachVpc("VpcAttachment", AttachVpcOptions.builder()
.vpc(myVpc)
.subnets(List.of(subnet1, subnet2))
.build());
// Create an attachment with optional parameters
ITransitGatewayVpcAttachment attachmentWithOptions = transitGateway.attachVpc("VpcAttachmentWithOptions", AttachVpcOptions.builder()
.vpc(myVpc)
.subnets(List.of(subnet1))
.vpcAttachmentOptions(Map.of(
"dnsSupport", true,
"applianceModeSupport", true,
"ipv6Support", true,
"securityGroupReferencingSupport", true))
.build());
var myVpc = new VpcV2(this, "Vpc");
var subnet1 = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
var subnet2 = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.1.0/24"),
SubnetType = SubnetType.PUBLIC
});
var transitGateway = new TransitGateway(this, "MyTransitGateway");
// Create a basic attachment
var attachment = transitGateway.AttachVpc("VpcAttachment", new AttachVpcOptions {
Vpc = myVpc,
Subnets = new [] { subnet1, subnet2 }
});
// Create an attachment with optional parameters
var attachmentWithOptions = transitGateway.AttachVpc("VpcAttachmentWithOptions", new AttachVpcOptions {
Vpc = myVpc,
Subnets = new [] { subnet1 },
VpcAttachmentOptions = new Dictionary<string, boolean?> {
{ "dnsSupport", true },
{ "applianceModeSupport", true },
{ "ipv6Support", true },
{ "securityGroupReferencingSupport", true }
}
});
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
subnet1 := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
subnet2 := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.1.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"))
// Create a basic attachment
attachment := transitGateway.attachVpc(jsii.String("VpcAttachment"), &AttachVpcOptions{
Vpc: myVpc,
Subnets: []ISubnet{
subnet1,
subnet2,
},
})
// Create an attachment with optional parameters
attachmentWithOptions := transitGateway.attachVpc(jsii.String("VpcAttachmentWithOptions"), &AttachVpcOptions{
Vpc: myVpc,
Subnets: []ISubnet{
subnet1,
},
VpcAttachmentOptions: map[string]*bool{
"dnsSupport": jsii.Boolean(true),
"applianceModeSupport": jsii.Boolean(true),
"ipv6Support": jsii.Boolean(true),
"securityGroupReferencingSupport": jsii.Boolean(true),
},
})
If you want to automatically associate and propagate routes with transit gateway route tables, you can pass the associationRouteTable and propagationRouteTables parameters. This will automatically create the necessary associations and propagations based on the provided route tables.
const myVpc = new VpcV2(this, 'Vpc');
const subnet1 = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC
});
const subnet2 = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.1.0/24'),
subnetType: SubnetType.PUBLIC
});
const transitGateway = new TransitGateway(this, 'MyTransitGateway');
const associationRouteTable = transitGateway.addRouteTable('AssociationRouteTable');
const propagationRouteTable1 = transitGateway.addRouteTable('PropagationRouteTable1');
const propagationRouteTable2 = transitGateway.addRouteTable('PropagationRouteTable2');
// Create an attachment with automatically created association + propagations
const attachmentWithRoutes = transitGateway.attachVpc('VpcAttachment', {
vpc: myVpc,
subnets: [subnet1, subnet2],
associationRouteTable: associationRouteTable,
propagationRouteTables: [propagationRouteTable1, propagationRouteTable2],
});
my_vpc = VpcV2(self, "Vpc")
subnet1 = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
subnet2 = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.1.0/24"),
subnet_type=SubnetType.PUBLIC
)
transit_gateway = TransitGateway(self, "MyTransitGateway")
association_route_table = transit_gateway.add_route_table("AssociationRouteTable")
propagation_route_table1 = transit_gateway.add_route_table("PropagationRouteTable1")
propagation_route_table2 = transit_gateway.add_route_table("PropagationRouteTable2")
# Create an attachment with automatically created association + propagations
attachment_with_routes = transit_gateway.attach_vpc("VpcAttachment",
vpc=my_vpc,
subnets=[subnet1, subnet2],
association_route_table=association_route_table,
propagation_route_tables=[propagation_route_table1, propagation_route_table2]
)
VpcV2 myVpc = new VpcV2(this, "Vpc");
SubnetV2 subnet1 = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
SubnetV2 subnet2 = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.1.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
TransitGateway transitGateway = new TransitGateway(this, "MyTransitGateway");
ITransitGatewayRouteTable associationRouteTable = transitGateway.addRouteTable("AssociationRouteTable");
ITransitGatewayRouteTable propagationRouteTable1 = transitGateway.addRouteTable("PropagationRouteTable1");
ITransitGatewayRouteTable propagationRouteTable2 = transitGateway.addRouteTable("PropagationRouteTable2");
// Create an attachment with automatically created association + propagations
ITransitGatewayVpcAttachment attachmentWithRoutes = transitGateway.attachVpc("VpcAttachment", AttachVpcOptions.builder()
.vpc(myVpc)
.subnets(List.of(subnet1, subnet2))
.associationRouteTable(associationRouteTable)
.propagationRouteTables(List.of(propagationRouteTable1, propagationRouteTable2))
.build());
var myVpc = new VpcV2(this, "Vpc");
var subnet1 = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
var subnet2 = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.1.0/24"),
SubnetType = SubnetType.PUBLIC
});
var transitGateway = new TransitGateway(this, "MyTransitGateway");
var associationRouteTable = transitGateway.AddRouteTable("AssociationRouteTable");
var propagationRouteTable1 = transitGateway.AddRouteTable("PropagationRouteTable1");
var propagationRouteTable2 = transitGateway.AddRouteTable("PropagationRouteTable2");
// Create an attachment with automatically created association + propagations
var attachmentWithRoutes = transitGateway.AttachVpc("VpcAttachment", new AttachVpcOptions {
Vpc = myVpc,
Subnets = new [] { subnet1, subnet2 },
AssociationRouteTable = associationRouteTable,
PropagationRouteTables = new [] { propagationRouteTable1, propagationRouteTable2 }
});
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
subnet1 := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
subnet2 := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.1.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"))
associationRouteTable := transitGateway.addRouteTable(jsii.String("AssociationRouteTable"))
propagationRouteTable1 := transitGateway.addRouteTable(jsii.String("PropagationRouteTable1"))
propagationRouteTable2 := transitGateway.addRouteTable(jsii.String("PropagationRouteTable2"))
// Create an attachment with automatically created association + propagations
attachmentWithRoutes := transitGateway.attachVpc(jsii.String("VpcAttachment"), &AttachVpcOptions{
Vpc: myVpc,
Subnets: []ISubnet{
subnet1,
subnet2,
},
AssociationRouteTable: associationRouteTable,
PropagationRouteTables: []ITransitGatewayRouteTable{
propagationRouteTable1,
propagationRouteTable2,
},
})
In this example, the associationRouteTable is set to associationRouteTable, and propagationRouteTables is set to an array containing propagationRouteTable1 and propagationRouteTable2. This triggers the automatic creation of route table associations and route propagations between the Transit Gateway and the specified route tables.
Adding static routes to the route table
Add static routes using either the addRoute() method to add an active route or addBlackholeRoute() to add a blackhole route:
const transitGateway = new TransitGateway(this, 'MyTransitGateway');
const routeTable = transitGateway.addRouteTable('CustomRouteTable');
const myVpc = new VpcV2(this, 'Vpc');
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC
});
const attachment = transitGateway.attachVpc('VpcAttachment', {
vpc: myVpc,
subnets: [subnet]
});
// Add a static route to direct traffic
routeTable.addRoute('StaticRoute', attachment, '10.0.0.0/16');
// Block unwanted traffic with a blackhole route
routeTable.addBlackholeRoute('BlackholeRoute', '172.16.0.0/16');
transit_gateway = TransitGateway(self, "MyTransitGateway")
route_table = transit_gateway.add_route_table("CustomRouteTable")
my_vpc = VpcV2(self, "Vpc")
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
attachment = transit_gateway.attach_vpc("VpcAttachment",
vpc=my_vpc,
subnets=[subnet]
)
# Add a static route to direct traffic
route_table.add_route("StaticRoute", attachment, "10.0.0.0/16")
# Block unwanted traffic with a blackhole route
route_table.add_blackhole_route("BlackholeRoute", "172.16.0.0/16")
TransitGateway transitGateway = new TransitGateway(this, "MyTransitGateway");
ITransitGatewayRouteTable routeTable = transitGateway.addRouteTable("CustomRouteTable");
VpcV2 myVpc = new VpcV2(this, "Vpc");
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
ITransitGatewayVpcAttachment attachment = transitGateway.attachVpc("VpcAttachment", AttachVpcOptions.builder()
.vpc(myVpc)
.subnets(List.of(subnet))
.build());
// Add a static route to direct traffic
routeTable.addRoute("StaticRoute", attachment, "10.0.0.0/16");
// Block unwanted traffic with a blackhole route
routeTable.addBlackholeRoute("BlackholeRoute", "172.16.0.0/16");
var transitGateway = new TransitGateway(this, "MyTransitGateway");
var routeTable = transitGateway.AddRouteTable("CustomRouteTable");
var myVpc = new VpcV2(this, "Vpc");
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
var attachment = transitGateway.AttachVpc("VpcAttachment", new AttachVpcOptions {
Vpc = myVpc,
Subnets = new [] { subnet }
});
// Add a static route to direct traffic
routeTable.AddRoute("StaticRoute", attachment, "10.0.0.0/16");
// Block unwanted traffic with a blackhole route
routeTable.AddBlackholeRoute("BlackholeRoute", "172.16.0.0/16");
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"))
routeTable := transitGateway.addRouteTable(jsii.String("CustomRouteTable"))
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
attachment := transitGateway.attachVpc(jsii.String("VpcAttachment"), &AttachVpcOptions{
Vpc: myVpc,
Subnets: []ISubnet{
subnet,
},
})
// Add a static route to direct traffic
routeTable.AddRoute(jsii.String("StaticRoute"), attachment, jsii.String("10.0.0.0/16"))
// Block unwanted traffic with a blackhole route
routeTable.AddBlackholeRoute(jsii.String("BlackholeRoute"), jsii.String("172.16.0.0/16"))
Route Table Associations and Propagations
Configure route table associations and enable route propagation:
const transitGateway = new TransitGateway(this, 'MyTransitGateway');
const routeTable = transitGateway.addRouteTable('CustomRouteTable');
const myVpc = new VpcV2(this, 'Vpc');
const subnet = new SubnetV2(this, 'Subnet', {
vpc: myVpc,
availabilityZone: 'eu-west-2a',
ipv4CidrBlock: new IpCidr('10.0.0.0/24'),
subnetType: SubnetType.PUBLIC
});
const attachment = transitGateway.attachVpc('VpcAttachment', {
vpc: myVpc,
subnets: [subnet]
});
// Associate an attachment with a route table
routeTable.addAssociation('Association', attachment);
// Enable route propagation for an attachment
routeTable.enablePropagation('Propagation', attachment);
transit_gateway = TransitGateway(self, "MyTransitGateway")
route_table = transit_gateway.add_route_table("CustomRouteTable")
my_vpc = VpcV2(self, "Vpc")
subnet = SubnetV2(self, "Subnet",
vpc=my_vpc,
availability_zone="eu-west-2a",
ipv4_cidr_block=IpCidr("10.0.0.0/24"),
subnet_type=SubnetType.PUBLIC
)
attachment = transit_gateway.attach_vpc("VpcAttachment",
vpc=my_vpc,
subnets=[subnet]
)
# Associate an attachment with a route table
route_table.add_association("Association", attachment)
# Enable route propagation for an attachment
route_table.enable_propagation("Propagation", attachment)
TransitGateway transitGateway = new TransitGateway(this, "MyTransitGateway");
ITransitGatewayRouteTable routeTable = transitGateway.addRouteTable("CustomRouteTable");
VpcV2 myVpc = new VpcV2(this, "Vpc");
SubnetV2 subnet = SubnetV2.Builder.create(this, "Subnet")
.vpc(myVpc)
.availabilityZone("eu-west-2a")
.ipv4CidrBlock(new IpCidr("10.0.0.0/24"))
.subnetType(SubnetType.PUBLIC)
.build();
ITransitGatewayVpcAttachment attachment = transitGateway.attachVpc("VpcAttachment", AttachVpcOptions.builder()
.vpc(myVpc)
.subnets(List.of(subnet))
.build());
// Associate an attachment with a route table
routeTable.addAssociation("Association", attachment);
// Enable route propagation for an attachment
routeTable.enablePropagation("Propagation", attachment);
var transitGateway = new TransitGateway(this, "MyTransitGateway");
var routeTable = transitGateway.AddRouteTable("CustomRouteTable");
var myVpc = new VpcV2(this, "Vpc");
var subnet = new SubnetV2(this, "Subnet", new SubnetV2Props {
Vpc = myVpc,
AvailabilityZone = "eu-west-2a",
Ipv4CidrBlock = new IpCidr("10.0.0.0/24"),
SubnetType = SubnetType.PUBLIC
});
var attachment = transitGateway.AttachVpc("VpcAttachment", new AttachVpcOptions {
Vpc = myVpc,
Subnets = new [] { subnet }
});
// Associate an attachment with a route table
routeTable.AddAssociation("Association", attachment);
// Enable route propagation for an attachment
routeTable.EnablePropagation("Propagation", attachment);
transitGateway := awsec2alpha.NewTransitGateway(this, jsii.String("MyTransitGateway"))
routeTable := transitGateway.addRouteTable(jsii.String("CustomRouteTable"))
myVpc := awsec2alpha.NewVpcV2(this, jsii.String("Vpc"))
subnet := awsec2alpha.NewSubnetV2(this, jsii.String("Subnet"), &SubnetV2Props{
Vpc: myVpc,
AvailabilityZone: jsii.String("eu-west-2a"),
Ipv4CidrBlock: awsec2alpha.NewIpCidr(jsii.String("10.0.0.0/24")),
SubnetType: awscdk.SubnetType_PUBLIC,
})
attachment := transitGateway.attachVpc(jsii.String("VpcAttachment"), &AttachVpcOptions{
Vpc: myVpc,
Subnets: []ISubnet{
subnet,
},
})
// Associate an attachment with a route table
routeTable.AddAssociation(jsii.String("Association"), attachment)
// Enable route propagation for an attachment
routeTable.EnablePropagation(jsii.String("Propagation"), attachment)
Associations — The linking of a Transit Gateway attachment to a specific route table, which determines which routes that attachment will use for routing decisions.
Propagation — The automatic advertisement of routes from an attachment to a route table, allowing the route table to learn about available network destinations.
Types
| Name | Kind | Summary |
|---|---|---|
EgressOnlyInternetGateway | Construct (L2) | Creates an egress-only internet gateway. |
InternetGateway | Construct (L2) | Creates an internet gateway. |
Ipam | Construct (L2) | Creates new IPAM with default public and private scope. |
NatGateway | Construct (L2) | Creates a network address translation (NAT) gateway. |
Route | Construct (L2) | Creates a new route with added functionality. |
RouteTable | Construct (L2) | Creates a route table for the specified VPC. |
SubnetV2 | Construct (L2) | The SubnetV2 class represents a subnet within a VPC (Virtual Private Cloud) in AWS. |
TransitGateway | Construct (L2) | Creates a Transit Gateway. |
TransitGatewayBlackholeRoute | Construct (L2) | Create a Transit Gateway Blackhole Route. |
TransitGatewayRoute | Construct (L2) | Create a Transit Gateway Active Route. |
TransitGatewayRouteTable | Construct (L2) | Creates a Transit Gateway route table. |
TransitGatewayRouteTableAssociation | Construct (L2) | Create a Transit Gateway Route Table Association. |
TransitGatewayRouteTablePropagation | Construct (L2) | Create a Transit Gateway Route Table Propagation. |
TransitGatewayVpcAttachment | Construct (L2) | Creates a Transit Gateway VPC Attachment. |
VPCPeeringConnection | Construct (L2) | Creates a peering connection between two VPCs. |
VpcV2 | Construct (L2) | This class provides a foundation for creating and configuring a VPC with advanced features such as IPAM (IP Address Management) and IPv6 support. |
VpcV2Base | Construct (L2) | Base class for creating a VPC (Virtual Private Cloud) in AWS. |
VPNGatewayV2 | Construct (L2) | Creates a virtual private gateway. |
AddressFamily | Enum | Represents the address family for IP addresses in an IPAM pool. |
AttachVpcOptions | Struct | Options for creating an Attachment via the attachVpc() method. |
AwsServiceName | Enum | Limits which service in AWS that the pool can be used in. |
BaseTransitGatewayRouteProps | Struct | Common properties for a Transit Gateway Route. |
EgressOnlyInternetGatewayOptions | Struct | Options to define EgressOnlyInternetGateway for VPC. |
EgressOnlyInternetGatewayProps | Struct | Properties to define an egress-only internet gateway. |
IIpAddresses | Interface | Implements ip address allocation according to the IPAdress type. |
IIpamPool | Interface | Definition used to add or create a new IPAM pool. |
IIpamScopeBase | Interface | Interface for IpamScope Class. |
InternetGatewayOptions | Struct | Options to define InternetGateway for VPC. |
InternetGatewayProps | Struct | Properties to define an internet gateway. |
IpAddresses | Class | IpAddress options to define VPC V2. |
IpamOptions | Struct | Options for configuring an IP Address Manager (IPAM). |
IpamPoolCidrProvisioningOptions | Struct | Options to provision CIDRs to an IPAM pool. |
IpamPoolPublicIpSource | Enum | The IP address source for pools in the public scope. |
IpamProps | Struct | Options to create a new Ipam in the account. |
IpamScopeOptions | Struct | Being used in IPAM class to add pools to default scope created by IPAM. |
IpamScopeType | Enum | Refers to two possible scope types under IPAM. |
IpCidr | Class | IPv4 or IPv6 CIDR range for the subnet. |
Ipv6PoolSecondaryAddressProps | Struct | Additional props needed for BYOIP IPv6 address props. |
IRouteTarget | Interface | Interface to define a routing target, such as an egress-only internet gateway or VPC endpoint. |
IRouteV2 | Interface | Interface to define a route. |
ISubnetV2 | Interface | Interface with additional properties for SubnetV2. |
ITransitGateway | Interface | Represents a Transit Gateway. |
ITransitGatewayAssociation | Interface | Represents a Transit Gateway Route Table Association. |
ITransitGatewayAttachment | Interface | Represents a Transit Gateway Attachment. |
ITransitGatewayRoute | Interface | Represents a Transit Gateway Route. |
ITransitGatewayRouteTable | Interface | Represents a Transit Gateway Route Table. |
ITransitGatewayRouteTableAssociation | Interface | Represents a Transit Gateway Route Table Association. |
ITransitGatewayRouteTablePropagation | Interface | Represents a Transit Gateway Route Table Propagation. |
ITransitGatewayVpcAttachment | Interface | Represents a Transit Gateway VPC Attachment. |
ITransitGatewayVpcAttachmentOptions | Interface | Options for Transit Gateway VPC Attachment. |
IVPCCidrBlock | Interface | Interface to create L2 for VPC Cidr Block. |
IVpcV2 | Interface | Placeholder to see what extra props we might need, will be added to original IVPC. |
NatConnectivityType | Enum | Indicates whether the NAT gateway supports public or private connectivity. |
NatGatewayOptions | Struct | Options to define a NAT gateway. |
NatGatewayProps | Struct | Properties to define a NAT gateway. |
PoolOptions | Struct | Options for configuring an IPAM pool. |
RouteProps | Struct | Properties to define a route. |
RouteTableProps | Struct | Properties to define a route table. |
RouteTargetProps | Struct | The type of endpoint or gateway being targeted by the route. |
RouteTargetType | Class | The gateway or endpoint targeted by the route. |
SecondaryAddressProps | Struct | Additional props needed for secondary Address. |
SubnetV2Attributes | Struct | Properties required to import a subnet. |
SubnetV2Props | Struct | Properties to define subnet for VPC. |
TransitGatewayBlackholeRouteProps | Struct | Properties for a Transit Gateway Blackhole Route. |
TransitGatewayProps | Struct | Common properties for creating a Transit Gateway resource. |
TransitGatewayRouteProps | Struct | Common properties for a Transit Gateway Route. |
TransitGatewayRouteTableAssociationProps | Struct | Common properties for a Transit Gateway Route Table Association. |
TransitGatewayRouteTablePropagationProps | Struct | Common properties for a Transit Gateway Route Table Propagation. |
TransitGatewayRouteTableProps | Struct | Common properties for creating a Transit Gateway Route Table resource. |
TransitGatewayVpcAttachmentProps | Struct | Common properties for creating a Transit Gateway VPC Attachment resource. |
VPCCidrBlockattributes | Struct | Attributes for VPCCidrBlock used for defining a new CIDR Block and also for importing an existing CIDR. |
VpcCidrOptions | Struct | Consolidated return parameters to pass to VPC construct. |
VPCPeeringConnectionOptions | Struct | Options to define a VPC peering connection. |
VPCPeeringConnectionProps | Struct | Properties to define a VPC peering connection. |
VpcV2Attributes | Struct | Options to import a VPC created outside of CDK stack. |
VpcV2Props | Struct | Properties to define VPC [disable-awslint:from-method]. |
VPNGatewayV2Options | Struct | Options to define VPNGatewayV2 for VPC. |
VPNGatewayV2Props | Struct | Properties to define a VPN gateway. |