aws-cdk.aws-ec2-alpha


Nameaws-cdk.aws-ec2-alpha JSON
Version 2.170.0a0 PyPI version JSON
download
home_pagehttps://github.com/aws/aws-cdk
SummaryThe CDK construct library for VPC V2
upload_time2024-11-22 04:42:18
maintainerNone
docs_urlNone
authorAmazon Web Services
requires_python~=3.8
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Amazon VpcV2 Construct Library

<!--BEGIN STABILITY BANNER-->---


![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> The APIs of higher level constructs in this module are experimental and under active development.
> They are subject to non-backward compatible changes or removal in any future version. These are
> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be
> announced in the 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.

---
<!--END STABILITY BANNER-->

## VpcV2

`VpcV2` is a re-write of the [`ec2.Vpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html) construct. This new construct enables higher level of customization
on the VPC being created. `VpcV2` implements the existing [`IVpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IVpc.html), therefore,
`VpcV2` is compatible with other constructs that accepts `IVpc` (e.g. [`ApplicationLoadBalancer`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer.html#construct-props)).

To create a VPC with both IPv4 and IPv6 support:

```python
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")
    ]
)
```

`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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Subnet.html) construct.
This new construct can be used to add subnets to a `VpcV2` instance:

```python
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.PRIVATE_ISOLATED
)
```

## IP Addresses Management

By default `VpcV2` uses `10.0.0.0/16` as the primary CIDR if none is defined.
Additional CIDRs can be adding to the VPC via the `secondaryAddressBlocks` prop.
The following example illustrates the different options of defining the address blocks:

```python
stack = Stack()
ipam = Ipam(self, "Ipam",
    operating_region=["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"
        )
    ]
)
```

Since `VpcV2` does not create subnets automatically, users have full control over IP addresses allocation across subnets.

## Routing

`RouteTable` is a new construct that allows for route tables to be customized in a variety of ways. For instance, the following example shows how a custom route table can be created and appended to a subnet:

```python
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
)
```

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

```python
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}
)
```

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.

```python
stack = Stack()
my_vpc = VpcV2(self, "Vpc",
    primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
    secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
        cidr_block_name="AmazonProvided"
    )]
)

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

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

route_table.add_route("EIGW", "::/0", {"gateway": eigw})
```

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

```python
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}
)
```

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:

```python
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}
)
```

## 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?](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html).

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**

```python
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
)
```

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

```python
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
)
```

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

```python
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")
```

After creating an IAM role in the acceptor account, we can initiate the peering connection request from the requestor VPC. Import accpeptorVpc 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:

```python
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
)
```

### 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](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html).

```python
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})
```

This can also be done using AWS CLI. For more information, see [create-route](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-route.html).

```bash
# 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:

```bash
aws ec2 delete-vpc-peering-connection --vpc-peering-connection-id pcx-xxxxxxxx
```

For more information, see [Delete a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#delete-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](https://docs.aws.amazon.com/vpc/latest/userguide/egress-only-internet-gateway.html).

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.

```python
stack = Stack()
my_vpc = VpcV2(self, "Vpc",
    primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
    secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
        cidr_block_name="AmazonProvided"
    )]
)
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"
)
```

## 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](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html).

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:

```python
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
)
```

## 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?](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html).

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 propogation, 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 `vpnRoutePropogation` enabled:

```python
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
)
```

## 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](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-igw-internet-access.html).

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 destinatation range by providing an optional input `destination` to the method.

The code example below shows how to add an internet gateway with a custom outbound destination IP range:

```python
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"
)
```

## 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 the range of VPC.

Here's an example of importing a VPC with only the required parameters

```python
stack = Stack()

imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
    vpc_id="mockVpcID",
    vpc_cidr_block="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 acount VPC, VPC arn for this case would be 'arn:aws:ec2:us-west-2:123456789012:vpc/mockVpcID'

```python
stack = Stack()

# Importing a cross acount 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"
)
```

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

```python
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()
```

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:

```python
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
)
```

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.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aws/aws-cdk",
    "name": "aws-cdk.aws-ec2-alpha",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "~=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Amazon Web Services",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/fe/a0/5fbfa178932f16547d5d9cebe8d741bc349083de176d60cd09da8f1e15e2/aws_cdk_aws_ec2_alpha-2.170.0a0.tar.gz",
    "platform": null,
    "description": "# Amazon VpcV2 Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)\n\n> The APIs of higher level constructs in this module are experimental and under active development.\n> They are subject to non-backward compatible changes or removal in any future version. These are\n> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be\n> announced in the release notes. This means that while you may use them, you may need to update\n> your source code when upgrading to a newer version of this package.\n\n---\n<!--END STABILITY BANNER-->\n\n## VpcV2\n\n`VpcV2` is a re-write of the [`ec2.Vpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html) construct. This new construct enables higher level of customization\non the VPC being created. `VpcV2` implements the existing [`IVpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IVpc.html), therefore,\n`VpcV2` is compatible with other constructs that accepts `IVpc` (e.g. [`ApplicationLoadBalancer`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer.html#construct-props)).\n\nTo create a VPC with both IPv4 and IPv6 support:\n\n```python\nstack = Stack()\nVpcV2(self, \"Vpc\",\n    primary_address_block=IpAddresses.ipv4(\"10.0.0.0/24\"),\n    secondary_address_blocks=[\n        IpAddresses.amazon_provided_ipv6(cidr_block_name=\"AmazonProvidedIpv6\")\n    ]\n)\n```\n\n`VpcV2` does not automatically create subnets or allocate IP addresses, which is different from the `Vpc` construct.\n\n## SubnetV2\n\n`SubnetV2` is a re-write of the [`ec2.Subnet`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Subnet.html) construct.\nThis new construct can be used to add subnets to a `VpcV2` instance:\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\",\n    secondary_address_blocks=[\n        IpAddresses.amazon_provided_ipv6(cidr_block_name=\"AmazonProvidedIp\")\n    ]\n)\n\nSubnetV2(self, \"subnetA\",\n    vpc=my_vpc,\n    availability_zone=\"us-east-1a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    ipv6_cidr_block=IpCidr(\"2a05:d02c:25:4000::/60\"),\n    subnet_type=SubnetType.PRIVATE_ISOLATED\n)\n```\n\n## IP Addresses Management\n\nBy default `VpcV2` uses `10.0.0.0/16` as the primary CIDR if none is defined.\nAdditional CIDRs can be adding to the VPC via the `secondaryAddressBlocks` prop.\nThe following example illustrates the different options of defining the address blocks:\n\n```python\nstack = Stack()\nipam = Ipam(self, \"Ipam\",\n    operating_region=[\"us-west-1\"]\n)\nipam_public_pool = ipam.public_scope.add_pool(\"PublicPoolA\",\n    address_family=AddressFamily.IP_V6,\n    aws_service=AwsServiceName.EC2,\n    locale=\"us-west-1\",\n    public_ip_source=IpamPoolPublicIpSource.AMAZON\n)\nipam_public_pool.provision_cidr(\"PublicPoolACidrA\", netmask_length=52)\n\nipam_private_pool = ipam.private_scope.add_pool(\"PrivatePoolA\",\n    address_family=AddressFamily.IP_V4\n)\nipam_private_pool.provision_cidr(\"PrivatePoolACidrA\", netmask_length=8)\n\nVpcV2(self, \"Vpc\",\n    primary_address_block=IpAddresses.ipv4(\"10.0.0.0/24\"),\n    secondary_address_blocks=[\n        IpAddresses.amazon_provided_ipv6(cidr_block_name=\"AmazonIpv6\"),\n        IpAddresses.ipv6_ipam(\n            ipam_pool=ipam_public_pool,\n            netmask_length=52,\n            cidr_block_name=\"ipv6Ipam\"\n        ),\n        IpAddresses.ipv4_ipam(\n            ipam_pool=ipam_private_pool,\n            netmask_length=8,\n            cidr_block_name=\"ipv4Ipam\"\n        )\n    ]\n)\n```\n\nSince `VpcV2` does not create subnets automatically, users have full control over IP addresses allocation across subnets.\n\n## Routing\n\n`RouteTable` is a new construct that allows for route tables to be customized in a variety of ways. For instance, the following example shows how a custom route table can be created and appended to a subnet:\n\n```python\nmy_vpc = VpcV2(self, \"Vpc\")\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    route_table=route_table,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    subnet_type=SubnetType.PRIVATE_ISOLATED\n)\n```\n\n`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:\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\")\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    subnet_type=SubnetType.PRIVATE_ISOLATED\n)\n\nigw = InternetGateway(self, \"IGW\",\n    vpc=my_vpc\n)\nRoute(self, \"IgwRoute\",\n    route_table=route_table,\n    destination=\"0.0.0.0/0\",\n    target={\"gateway\": igw}\n)\n```\n\nAlternatively, `Routes` can also be created via method `addRoute` in the `RouteTable` class. An example using the `EgressOnlyInternetGateway` construct can be seen below:\nNote: `EgressOnlyInternetGateway` can only be used to set up outbound IPv6 routing.\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\",\n    primary_address_block=IpAddresses.ipv4(\"10.1.0.0/16\"),\n    secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(\n        cidr_block_name=\"AmazonProvided\"\n    )]\n)\n\neigw = EgressOnlyInternetGateway(self, \"EIGW\",\n    vpc=my_vpc\n)\n\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\n\nroute_table.add_route(\"EIGW\", \"::/0\", {\"gateway\": eigw})\n```\n\nOther 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`:\n\n```python\nmy_vpc = VpcV2(self, \"Vpc\")\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    subnet_type=SubnetType.PRIVATE_ISOLATED\n)\n\nnatgw = NatGateway(self, \"NatGW\",\n    subnet=subnet,\n    vpc=my_vpc,\n    connectivity_type=NatConnectivityType.PRIVATE,\n    private_ip_address=\"10.0.0.42\"\n)\nRoute(self, \"NatGwRoute\",\n    route_table=route_table,\n    destination=\"0.0.0.0/0\",\n    target={\"gateway\": natgw}\n)\n```\n\nIt 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:\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\")\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    subnet_type=SubnetType.PRIVATE\n)\n\ndynamo_endpoint = ec2.GatewayVpcEndpoint(self, \"DynamoEndpoint\",\n    service=ec2.GatewayVpcEndpointAwsService.DYNAMODB,\n    vpc=my_vpc,\n    subnets=[subnet]\n)\nRoute(self, \"DynamoDBRoute\",\n    route_table=route_table,\n    destination=\"0.0.0.0/0\",\n    target={\"endpoint\": dynamo_endpoint}\n)\n```\n\n## VPC Peering Connection\n\nVPC 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.\n\nPeering 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.\n\nFor more information, see [What is VPC peering?](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html).\n\nThe 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.\n\nNote: You cannot create a VPC peering connection between VPCs that have matching or overlapping CIDR blocks\n\n**Case 1: Same Account and Same Region Peering Connection**\n\n```python\nstack = Stack()\n\nvpc_a = VpcV2(self, \"VpcA\",\n    primary_address_block=IpAddresses.ipv4(\"10.0.0.0/16\")\n)\n\nvpc_b = VpcV2(self, \"VpcB\",\n    primary_address_block=IpAddresses.ipv4(\"10.1.0.0/16\")\n)\n\npeering_connection = vpc_a.create_peering_connection(\"sameAccountSameRegionPeering\",\n    acceptor_vpc=vpc_b\n)\n```\n\n**Case 2: Same Account and Cross Region Peering Connection**\n\nThere 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.\n\n```python\napp = App()\n\nstack_a = Stack(app, \"VpcStackA\", env=Environment(account=\"000000000000\", region=\"us-east-1\"))\nstack_b = Stack(app, \"VpcStackB\", env=Environment(account=\"000000000000\", region=\"us-west-2\"))\n\nvpc_a = VpcV2(stack_a, \"VpcA\",\n    primary_address_block=IpAddresses.ipv4(\"10.0.0.0/16\")\n)\n\nVpcV2(stack_b, \"VpcB\",\n    primary_address_block=IpAddresses.ipv4(\"10.1.0.0/16\")\n)\n\nvpc_b = VpcV2.from_vpc_v2_attributes(stack_a, \"ImportedVpcB\",\n    vpc_id=\"MockVpcBid\",\n    vpc_cidr_block=\"10.1.0.0/16\",\n    region=\"us-west-2\",\n    owner_account_id=\"000000000000\"\n)\n\npeering_connection = vpc_a.create_peering_connection(\"sameAccountCrossRegionPeering\",\n    acceptor_vpc=vpc_b\n)\n```\n\n**Case 3: Cross Account Peering Connection**\n\nFor 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.\n\nOnce role is created in account, provide role arn for field `peerRoleArn` under method `createPeeringConnection`\n\n```python\nstack = Stack()\n\nacceptor_vpc = VpcV2(self, \"VpcA\",\n    primary_address_block=IpAddresses.ipv4(\"10.0.0.0/16\")\n)\n\nacceptor_role_arn = acceptor_vpc.create_acceptor_vpc_role(\"000000000000\")\n```\n\nAfter creating an IAM role in the acceptor account, we can initiate the peering connection request from the requestor VPC. Import accpeptorVpc 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.\nThe following code snippet demonstrates how to set up VPC peering between two VPCs in different AWS accounts using CDK:\n\n```python\nstack = Stack()\n\nacceptor_vpc = VpcV2.from_vpc_v2_attributes(self, \"acceptorVpc\",\n    vpc_id=\"vpc-XXXX\",\n    vpc_cidr_block=\"10.0.0.0/16\",\n    region=\"us-east-2\",\n    owner_account_id=\"111111111111\"\n)\n\nacceptor_role_arn = \"arn:aws:iam::111111111111:role/VpcPeeringRole\"\n\nrequestor_vpc = VpcV2(self, \"VpcB\",\n    primary_address_block=IpAddresses.ipv4(\"10.1.0.0/16\")\n)\n\npeering_connection = requestor_vpc.create_peering_connection(\"crossAccountCrossRegionPeering\",\n    acceptor_vpc=acceptor_vpc,\n    peer_role_arn=acceptor_role_arn\n)\n```\n\n### Route Table Configuration\n\nAfter 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.\n\nFor more information, see [Update your route tables for a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html).\n\n```python\nstack = Stack()\n\nacceptor_vpc = VpcV2(self, \"VpcA\",\n    primary_address_block=IpAddresses.ipv4(\"10.0.0.0/16\")\n)\n\nrequestor_vpc = VpcV2(self, \"VpcB\",\n    primary_address_block=IpAddresses.ipv4(\"10.1.0.0/16\")\n)\n\npeering_connection = requestor_vpc.create_peering_connection(\"peeringConnection\",\n    acceptor_vpc=acceptor_vpc\n)\n\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=requestor_vpc\n)\n\nroute_table.add_route(\"vpcPeeringRoute\", \"10.0.0.0/16\", {\"gateway\": peering_connection})\n```\n\nThis can also be done using AWS CLI. For more information, see [create-route](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-route.html).\n\n```bash\n# Add a route to the requestor VPC route table\naws ec2 create-route --route-table-id rtb-requestor --destination-cidr-block 10.0.0.0/16 --vpc-peering-connection-id pcx-xxxxxxxx\n\n# For bi-directional add a route in the acceptor vpc account as well\naws ec2 create-route --route-table-id rtb-acceptor --destination-cidr-block 10.1.0.0/16 --vpc-peering-connection-id pcx-xxxxxxxx\n```\n\n### Deleting the Peering Connection\n\nTo delete a VPC peering connection, use the following command:\n\n```bash\naws ec2 delete-vpc-peering-connection --vpc-peering-connection-id pcx-xxxxxxxx\n```\n\nFor more information, see [Delete a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#delete-vpc-peering-connection).\n\n## Adding Egress-Only Internet Gateway to VPC\n\nAn 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.\n\nFor more information see [Enable outbound IPv6 traffic using an egress-only internet gateway](https://docs.aws.amazon.com/vpc/latest/userguide/egress-only-internet-gateway.html).\n\nVpcV2 supports adding an egress only internet gateway to VPC using the `addEgressOnlyInternetGateway` method.\n\nBy 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.\nThe `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.\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\",\n    primary_address_block=IpAddresses.ipv4(\"10.1.0.0/16\"),\n    secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(\n        cidr_block_name=\"AmazonProvided\"\n    )]\n)\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    ipv6_cidr_block=IpCidr(\"2001:db8:1::/64\"),\n    subnet_type=SubnetType.PRIVATE\n)\n\nmy_vpc.add_egress_only_internet_gateway(\n    subnets=[ec2.SubnetSelection(subnet_type=SubnetType.PRIVATE)],\n    destination=\"::/60\"\n)\n```\n\n## Adding NATGateway to the VPC\n\nA 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.\n\nFor more information, see [NAT gateway basics](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html).\n\nWhen you create a NAT gateway, you specify one of the following connectivity types:\n\n**Public \u2013 (Default)**: Instances in private subnets can connect to the internet through a public NAT gateway, but cannot receive unsolicited inbound connections from the internet\n\n**Private**: Instances in private subnets can connect to other VPCs or your on-premises network through a private NAT gateway.\n\nTo 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.\nSince a NATGW is associated with a particular subnet, providing `subnet` field in the input props is mandatory.\n\nAdditionally, 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.\n\nThe code example below provides the definition for adding a NAT gateway to your subnet:\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\")\nroute_table = RouteTable(self, \"RouteTable\",\n    vpc=my_vpc\n)\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    subnet_type=SubnetType.PUBLIC\n)\n\nmy_vpc.add_internet_gateway()\nmy_vpc.add_nat_gateway(\n    subnet=subnet,\n    connectivity_type=NatConnectivityType.PUBLIC\n)\n```\n\n## Enable VPNGateway for the VPC\n\nA virtual private gateway is the endpoint on the VPC side of your VPN connection.\n\nFor more information, see [What is AWS Site-to-Site VPN?](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html).\n\nVPN 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.\n\nTo enable VPN route propogation, 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.\n\nAdditionally, 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.\n\nThe code example below provides the definition for setting up a VPN gateway with `vpnRoutePropogation` enabled:\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\")\nvpn_gateway = my_vpc.enable_vpn_gateway_v2(\n    vpn_route_propagation=[ec2.SubnetSelection(subnet_type=SubnetType.PUBLIC)],\n    type=VpnConnectionType.IPSEC_1\n)\n\nroute_table = RouteTable(stack, \"routeTable\",\n    vpc=my_vpc\n)\n\nRoute(stack, \"route\",\n    destination=\"172.31.0.0/24\",\n    target={\"gateway\": vpn_gateway},\n    route_table=route_table\n)\n```\n\n## Adding InternetGateway to the VPC\n\nAn 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.\n\nFor more information, see [Enable VPC internet access using internet gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-igw-internet-access.html).\n\nYou 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.\nInstead of using the default settings, you can configure a custom destinatation range by providing an optional input `destination` to the method.\n\nThe code example below shows how to add an internet gateway with a custom outbound destination IP range:\n\n```python\nstack = Stack()\nmy_vpc = VpcV2(self, \"Vpc\")\n\nsubnet = SubnetV2(self, \"Subnet\",\n    vpc=my_vpc,\n    availability_zone=\"eu-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.0.0.0/24\"),\n    subnet_type=SubnetType.PUBLIC\n)\n\nmy_vpc.add_internet_gateway(\n    ipv4_destination=\"192.168.0.0/16\"\n)\n```\n\n## Importing an existing VPC\n\nYou can import an existing VPC and its subnets using the `VpcV2.fromVpcV2Attributes()` method or an individual subnet using `SubnetV2.fromSubnetV2Attributes()` method.\n\n### Importing a VPC\n\nTo 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.\n\nIf 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 the range of VPC.\n\nHere's an example of importing a VPC with only the required parameters\n\n```python\nstack = Stack()\n\nimported_vpc = VpcV2.from_vpc_v2_attributes(stack, \"ImportedVpc\",\n    vpc_id=\"mockVpcID\",\n    vpc_cidr_block=\"10.0.0.0/16\"\n)\n```\n\nIn 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.\n\nBelow is an example of importing a cross region and cross acount VPC, VPC arn for this case would be 'arn:aws:ec2:us-west-2:123456789012:vpc/mockVpcID'\n\n```python\nstack = Stack()\n\n# Importing a cross acount or cross region VPC\nimported_vpc = VpcV2.from_vpc_v2_attributes(stack, \"ImportedVpc\",\n    vpc_id=\"mockVpcID\",\n    vpc_cidr_block=\"10.0.0.0/16\",\n    owner_account_id=\"123456789012\",\n    region=\"us-west-2\"\n)\n```\n\nHere's an example of how to import a VPC with multiple CIDR blocks, IPv6 support, and different subnet types:\n\nIn this example, we're importing a VPC with:\n\n* A primary CIDR block (10.1.0.0/16)\n* One secondary IPv4 CIDR block (10.2.0.0/16)\n* Two secondary address using IPAM pool (IPv4 and IPv6)\n* VPC has Amazon-provided IPv6 CIDR enabled\n* An isolated subnet in us-west-2a\n* A public subnet in us-west-2b\n\n```python\nstack = Stack()\n\nimported_vpc = VpcV2.from_vpc_v2_attributes(self, \"ImportedVPC\",\n    vpc_id=\"vpc-XXX\",\n    vpc_cidr_block=\"10.1.0.0/16\",\n    secondary_cidr_blocks=[VPCCidrBlockattributes(\n        cidr_block=\"10.2.0.0/16\",\n        cidr_block_name=\"ImportedBlock1\"\n    ), VPCCidrBlockattributes(\n        ipv6_ipam_pool_id=\"ipam-pool-XXX\",\n        ipv6_netmask_length=52,\n        cidr_block_name=\"ImportedIpamIpv6\"\n    ), VPCCidrBlockattributes(\n        ipv4_ipam_pool_id=\"ipam-pool-XXX\",\n        ipv4_ipam_provisioned_cidrs=[\"10.2.0.0/16\"],\n        cidr_block_name=\"ImportedIpamIpv4\"\n    ), VPCCidrBlockattributes(\n        amazon_provided_ipv6_cidr_block=True\n    )\n    ],\n    subnets=[SubnetV2Attributes(\n        subnet_name=\"IsolatedSubnet2\",\n        subnet_id=\"subnet-03cd773c0fe08ed26\",\n        subnet_type=SubnetType.PRIVATE_ISOLATED,\n        availability_zone=\"us-west-2a\",\n        ipv4_cidr_block=\"10.2.0.0/24\",\n        route_table_id=\"rtb-0871c310f98da2cbb\"\n    ), SubnetV2Attributes(\n        subnet_id=\"subnet-0fa477e01db27d820\",\n        subnet_type=SubnetType.PUBLIC,\n        availability_zone=\"us-west-2b\",\n        ipv4_cidr_block=\"10.3.0.0/24\",\n        route_table_id=\"rtb-014f3043098fe4b96\"\n    )]\n)\n\n# You can now use the imported VPC in your stack\n\n# Adding a new subnet to the imported VPC\nimported_subnet = SubnetV2(self, \"NewSubnet\",\n    availability_zone=\"us-west-2a\",\n    ipv4_cidr_block=IpCidr(\"10.2.2.0/24\"),\n    vpc=imported_vpc,\n    subnet_type=SubnetType.PUBLIC\n)\n\n# Adding gateways to the imported VPC\nimported_vpc.add_internet_gateway()\nimported_vpc.add_nat_gateway(subnet=imported_subnet)\nimported_vpc.add_egress_only_internet_gateway()\n```\n\nYou can add more subnets as needed by including additional entries in the `isolatedSubnets`, `publicSubnets`, or other subnet type arrays (e.g., `privateSubnets`).\n\n### Importing Subnets\n\nYou 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.\n\nHere's an example of how to import a subnet:\n\n```python\nSubnetV2.from_subnet_v2_attributes(self, \"ImportedSubnet\",\n    subnet_id=\"subnet-0123456789abcdef0\",\n    availability_zone=\"us-west-2a\",\n    ipv4_cidr_block=\"10.2.0.0/24\",\n    route_table_id=\"rtb-0871c310f98da2cbb\",\n    subnet_type=SubnetType.PRIVATE_ISOLATED\n)\n```\n\nBy 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.\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The CDK construct library for VPC V2",
    "version": "2.170.0a0",
    "project_urls": {
        "Homepage": "https://github.com/aws/aws-cdk",
        "Source": "https://github.com/aws/aws-cdk.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6dbf23ca0ce1494ae6679ba1e8e4fcb6100f48631fed583fb11a8208a52c90a0",
                "md5": "3d690970f475499417842ea6a39b3a9d",
                "sha256": "f2f59d6d9e99840b8c36be73f99fa588b29658c27869491e405a6ad97ed2c850"
            },
            "downloads": -1,
            "filename": "aws_cdk.aws_ec2_alpha-2.170.0a0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3d690970f475499417842ea6a39b3a9d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.8",
            "size": 239907,
            "upload_time": "2024-11-22T04:41:29",
            "upload_time_iso_8601": "2024-11-22T04:41:29.257561Z",
            "url": "https://files.pythonhosted.org/packages/6d/bf/23ca0ce1494ae6679ba1e8e4fcb6100f48631fed583fb11a8208a52c90a0/aws_cdk.aws_ec2_alpha-2.170.0a0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fea05fbfa178932f16547d5d9cebe8d741bc349083de176d60cd09da8f1e15e2",
                "md5": "05fbf694152bedb26e6beb5528aa92ad",
                "sha256": "355127d1f88085340cac4429f7a5a24974295a0c095697d4ee1797ce4b5d7771"
            },
            "downloads": -1,
            "filename": "aws_cdk_aws_ec2_alpha-2.170.0a0.tar.gz",
            "has_sig": false,
            "md5_digest": "05fbf694152bedb26e6beb5528aa92ad",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.8",
            "size": 246276,
            "upload_time": "2024-11-22T04:42:18",
            "upload_time_iso_8601": "2024-11-22T04:42:18.518986Z",
            "url": "https://files.pythonhosted.org/packages/fe/a0/5fbfa178932f16547d5d9cebe8d741bc349083de176d60cd09da8f1e15e2/aws_cdk_aws_ec2_alpha-2.170.0a0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-22 04:42:18",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aws",
    "github_project": "aws-cdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aws-cdk.aws-ec2-alpha"
}
        
Elapsed time: 0.86770s