Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(vpcv2): vpc peering connection construct #31645

Open
wants to merge 36 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
af43218
initial skeleton code
Oct 2, 2024
16c8c3e
improve readability and update missing params
Oct 3, 2024
7ebbfe5
add test cases
Oct 3, 2024
9f60103
add integration test
Oct 3, 2024
7222bf4
additional test coverage
Oct 3, 2024
cc7c813
Merge branch 'main' into vpc_peering_connection_construct
1kaileychen Oct 3, 2024
d920b57
add vpc peering connection into readme
Oct 3, 2024
49780bf
Merge branch 'vpc_peering_connection_construct' of https://github.com…
Oct 3, 2024
65a0846
Merge branch 'main' into vpc_peering_connection_construct
1kaileychen Oct 3, 2024
b21736e
fix rosetta readme errors
Oct 4, 2024
41f0fb7
Merge branch 'vpc_peering_connection_construct' of https://github.com…
Oct 4, 2024
3baf408
Merge branch 'main' into vpc_peering_connection_construct
paulhcsun Oct 4, 2024
39f7072
move validateVpcCidrOverlap to utils file
Oct 7, 2024
2b4c5c6
initial design change implementation
Oct 10, 2024
0c3bc8b
add region & ownerAccountId to VpcV2Props
Oct 10, 2024
ac63088
remove old tests
Oct 10, 2024
9f96a92
error msg modifications & use ownerAccountId
Oct 10, 2024
57df8ed
update policies and warning
Oct 11, 2024
5299751
add tests and integration tests
Oct 11, 2024
0143dbc
add readme
Oct 11, 2024
1c0f389
Merge remote-tracking branch 'origin/main' into vpc_peering_connectio…
Oct 11, 2024
d31b6ca
fix lint fail due to ordering in readme
Oct 11, 2024
751530c
update readme errors
Oct 11, 2024
98d39d2
update readme peering connection class to function
Oct 11, 2024
49e2e4f
add createPeeringConnection test
Oct 15, 2024
b8fc4a0
change warning to error when peerRoleArn is defined for same account
Oct 16, 2024
e810bd7
update description for peerRoleArn
Oct 16, 2024
b926d86
add clarity in readme different types of peering
Oct 16, 2024
9ff9da6
return integ.route-v2 to original test case
Oct 16, 2024
b13d363
integration test for peering connection
Oct 16, 2024
6607192
Apply suggestions from code review
shikha372 Oct 16, 2024
2f78a5a
Update wording suggestion
1kaileychen Oct 17, 2024
5773a08
remove region and ownerAccountId from VpcV2Props
Oct 17, 2024
8e3ff5f
update test cases and readme
Oct 17, 2024
9022843
Merge branch 'vpc_peering_connection_construct' of https://github.com…
Oct 17, 2024
951abf0
update account ids that are allowed in readme and tests
Oct 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions packages/@aws-cdk/aws-ec2-alpha/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,151 @@ new Route(this, 'DynamoDBRoute', {
destination: '0.0.0.0/0',
target: { 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.
shikha372 marked this conversation as resolved.
Show resolved Hide resolved

1kaileychen marked this conversation as resolved.
Show resolved Hide resolved
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.

**Case 1: Same Account and Same Region Peering Connection**

```ts
const stack = new Stack();

const vpcA = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
region: 'us-east-1',
ownerAccountId: '123456789012',
});

const vpcB = new VpcV2(this, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
region: 'us-east-1',
ownerAccountId: '123456789012',
});

const peeringConnection = vpcA.createPeeringConnection('sameAccountSameRegionPeering', {
acceptorVpc: vpcB,
});
```

**Case 2: Same Account and Cross Region Peering Connection**

The only change from Case 1 is specifying a different region in the VpcV2 class for each VPC.

```ts
const stack = new Stack();

const vpcA = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
region: 'us-east-1',
ownerAccountId: '123456789012',
});

const vpcB = new VpcV2(this, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
region: 'us-west-2',
ownerAccountId: '123456789012',
});

const peeringConnection = vpcA.createPeeringConnection('sameAccountCrossRegionPeering', {
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 restrictive IAM role in the acceptor account to provide the necessary permissions.
shikha372 marked this conversation as resolved.
Show resolved Hide resolved

```ts
const stack = new Stack();

const acceptorVpc = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
});

const acceptorRoleArn = acceptorVpc.createAcceptorVpcRole('987654321098') // Requestor account ID
```

After creating an IAM role in the acceptor account, we can initiate the peering connection request from the requestor VPC.

1kaileychen marked this conversation as resolved.
Show resolved Hide resolved
```ts
const stack = new Stack();

// TODO: Import acceptorVpc into the requestor stack
const acceptorVpc = new VpcV2(this, 'VpcA', {
primaryAddressBlock: IpAddresses.ipv4('10.0.0.0/16'),
region: 'us-east-1',
ownerAccountId: '123456789012',
});

const acceptorRoleArn = 'arn:aws:iam::123456789012:role/VpcPeeringRole';

const requestorVpc = new VpcV2(this, 'VpcB', {
primaryAddressBlock: IpAddresses.ipv4('10.1.0.0/16'),
region: 'us-west-2',
ownerAccountId: '987654321098',
});

const peeringConnection = requestorVpc.createPeeringConnection('crossAccountCrossRegionPeering', {
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](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html).

```ts
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 });
```

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.
Expand Down
139 changes: 135 additions & 4 deletions packages/@aws-cdk/aws-ec2-alpha/lib/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { CfnEIP, CfnEgressOnlyInternetGateway, CfnInternetGateway, CfnNatGateway, CfnRoute, CfnRouteTable, CfnVPCGatewayAttachment, CfnVPNGateway, CfnVPNGatewayRoutePropagation, GatewayVpcEndpoint, IRouteTable, IVpcEndpoint, RouterType } from 'aws-cdk-lib/aws-ec2';
import { CfnEIP, CfnEgressOnlyInternetGateway, CfnInternetGateway, CfnNatGateway, CfnVPCPeeringConnection, CfnRoute, CfnRouteTable, CfnVPCGatewayAttachment, CfnVPNGateway, CfnVPNGatewayRoutePropagation, GatewayVpcEndpoint, IRouteTable, IVpcEndpoint, RouterType } from 'aws-cdk-lib/aws-ec2';
import { Construct, IDependable } from 'constructs';
import { Annotations, Duration, IResource, Resource } from 'aws-cdk-lib/core';
import { IVpcV2, VPNGatewayV2Options } from './vpc-v2-base';
import { NetworkUtils, allRouteTableIds } from './util';
import { NetworkUtils, allRouteTableIds, CidrBlock } from './util';
import { ISubnetV2 } from './subnet-v2';

/**
Expand Down Expand Up @@ -175,6 +175,40 @@ export interface NatGatewayProps extends NatGatewayOptions {
readonly vpc?: IVpcV2;
}

/**
* Options to define a VPC peering connection.
*/
export interface VPCPeeringConnectionOptions {
/**
* The VPC that is accepting the peering connection.
*/
readonly acceptorVpc: IVpcV2;

/**
* The role arn created in the acceptor account.
*
* @default - no peerRoleArn needed if not cross account connection
*/
readonly peerRoleArn?: string;

/**
* The resource name of the peering connection.
*
* @default - peering connection provisioned without any name
*/
readonly vpcPeeringConnectionName?: string;
}

/**
* Properties to define a VPC peering connection.
*/
export interface VPCPeeringConnectionProps extends VPCPeeringConnectionOptions {
/**
* The VPC that is requesting the peering connection.
*/
readonly requestorVpc: IVpcV2;
}

/**
* Creates an egress-only internet gateway
* @resource AWS::EC2::EgressOnlyInternetGateway
Expand Down Expand Up @@ -312,7 +346,7 @@ export class VPNGatewayV2 extends Resource implements IRouteTarget {
const routeTableIds = allRouteTableIds(subnets);

if (routeTableIds.length === 0) {
Annotations.of(this).addWarningV2('@aws-cdk:aws-ec2-elpha:enableVpnGatewayV2', `No subnets matching selection: '${JSON.stringify(vpnRoutePropagation)}'. Select other subnets to add routes to.`);
Annotations.of(scope).addWarningV2('@aws-cdk:aws-ec2-elpha:enableVpnGatewayV2', `No subnets matching selection: '${JSON.stringify(vpnRoutePropagation)}'. Select other subnets to add routes to.`);
}

this._routePropagation = new CfnVPNGatewayRoutePropagation(this, 'RoutePropagation', {
Expand Down Expand Up @@ -402,6 +436,103 @@ export class NatGateway extends Resource implements IRouteTarget {
}
}

/**
* Creates a peering connection between two VPCs
* @resource AWS::EC2::VPCPeeringConnection
*/
export class VPCPeeringConnection extends Resource implements IRouteTarget {

/**
* The type of router used in the route.
*/
readonly routerType: RouterType;
1kaileychen marked this conversation as resolved.
Show resolved Hide resolved

/**
* The ID of the route target.
*/
readonly routerTargetId: string;
1kaileychen marked this conversation as resolved.
Show resolved Hide resolved

/**
* The VPC peering connection CFN resource.
*/
public readonly resource: CfnVPCPeeringConnection;

constructor(scope: Construct, id: string, props: VPCPeeringConnectionProps) {
super(scope, id);

this.routerType = RouterType.VPC_PEERING_CONNECTION;

const isCrossAccount = props.requestorVpc.ownerAccountId !== props.acceptorVpc.ownerAccountId;

if (!isCrossAccount && props.peerRoleArn) {
throw new Error('peerRoleArn is not needed for same account peering');
}

if (isCrossAccount && !props.peerRoleArn) {
throw new Error('Cross account VPC peering requires peerRoleArn');
}

const overlap = this.validateVpcCidrOverlap(props.requestorVpc, props.acceptorVpc);
if (overlap) {
throw new Error('CIDR block should not overlap with each other for establishing a peering connection');
}

this.resource = new CfnVPCPeeringConnection(this, 'VPCPeeringConnection', {
vpcId: props.requestorVpc.vpcId,
peerVpcId: props.acceptorVpc.vpcId,
peerOwnerId: props.acceptorVpc.ownerAccountId,
peerRegion: props.acceptorVpc.region,
peerRoleArn: isCrossAccount ? props.peerRoleArn : undefined,
});

this.routerTargetId = this.resource.attrId;
this.node.defaultChild = this.resource;
}

/**
* Validates if the provided IPv4 CIDR block overlaps with existing subnet CIDR blocks within the given VPC.
*
* @param requestorVpc The VPC of the requestor.
* @param acceptorVpc The VPC of the acceptor.
* @returns True if the IPv4 CIDR block overlaps with existing subnet CIDR blocks, false otherwise.
1kaileychen marked this conversation as resolved.
Show resolved Hide resolved
* @internal
*/
private validateVpcCidrOverlap(requestorVpc: IVpcV2, acceptorVpc: IVpcV2): boolean {

const requestorCidrs = [requestorVpc.ipv4CidrBlock];
const acceptorCidrs = [acceptorVpc.ipv4CidrBlock];

if (requestorVpc.secondaryCidrBlock) {
requestorCidrs.push(...requestorVpc.secondaryCidrBlock
.map(block => block.cidrBlock)
.filter((cidr): cidr is string => cidr !== undefined));
}

if (acceptorVpc.secondaryCidrBlock) {
acceptorCidrs.push(...acceptorVpc.secondaryCidrBlock
.map(block => block.cidrBlock)
.filter((cidr): cidr is string => cidr !== undefined));
}

for (const requestorCidr of requestorCidrs) {
const requestorRange = new CidrBlock(requestorCidr);
const requestorIpRange: [string, string] = [requestorRange.minIp(), requestorRange.maxIp()];

for (const acceptorCidr of acceptorCidrs) {
const acceptorRange = new CidrBlock(acceptorCidr);
const acceptorIpRange: [string, string] = [acceptorRange.minIp(), acceptorRange.maxIp()];

if (requestorRange.rangesOverlap(acceptorIpRange, requestorIpRange)) {
return true;
}
}
}

return false;
}

}

/**
* The type of endpoint or gateway being targeted by the route.
*/
Expand Down Expand Up @@ -534,7 +665,7 @@ export class Route extends Resource implements IRouteV2 {
/**
* The type of router the route is targetting
*/
public readonly targetRouterType: RouterType
public readonly targetRouterType: RouterType;

/**
* The route CFN resource.
Expand Down
3 changes: 1 addition & 2 deletions packages/@aws-cdk/aws-ec2-alpha/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,5 +378,4 @@ export class CidrBlockIpv6 {
}
return ipv6Number;
}
}

}
Loading