Skip to content

Instantly share code, notes, and snippets.

@mrpackethead
Created December 2, 2024 09:27
Show Gist options
  • Save mrpackethead/82c2ea029fa0191532831aae7b0d20ef to your computer and use it in GitHub Desktop.
Save mrpackethead/82c2ea029fa0191532831aae7b0d20ef to your computer and use it in GitHub Desktop.
Add Ipv6 to existing CDK VPC Using IPAM Pools
import * as core from 'aws-cdk-lib';
import {
aws_ec2 as ec2,
} from 'aws-cdk-lib';
import * as constructs from 'constructs';
export interface AddIpv6ToExisitingVpcProps extends ec2.VpcProps {
ipv6IpamPoolId: string;
ipv6IpamScopeId: string;
vpc: ec2.Vpc
vpcCidrMask?: number | undefined
}
export class AddIpv6ToExisitingVpcWithIPAM extends ec2.Vpc {
public egressOnlyInternetGatewayId?: string;
constructor(scope: constructs.Construct, id: string, props: AddIpv6ToExisitingVpcProps) {
super(scope, id, props);
// allocate a cidr from the ipam pool
const ipv6Cidr = new ec2.CfnVPCCidrBlock(this, 'Ipv6Cidr', {
vpcId: props.vpc.vpcId,
ipv6IpamPoolId: props.ipv6IpamPoolId,
ipv6NetmaskLength: props.vpcCidrMask ?? 56,
});
// create a vpc Pool to allocate IPv6 Cidrs for Subnets
const pool = new ec2.CfnIPAMPool(this, 'VpcPool', {
awsService: 'ec2',
ipamScopeId: props.ipv6IpamScopeId,
locale: core.Aws.REGION,
publicIpSource: 'amazon',
sourceResource: {
resourceId: props.vpc.vpcId,
resourceOwner: core.Aws.ACCOUNT_ID,
resourceRegion: core.Aws.REGION,
resourceType: 'vpc',
},
addressFamily: 'ipv6',
autoImport: true,
sourceIpamPoolId: props.ipv6IpamPoolId,
});
const provisioning = new ec2.CfnIPAMPoolCidr(this, `poolcidr`, {
ipamPoolId: pool.attrIpamPoolId,
cidr: core.Fn.select(0, props.vpc.vpcIpv6CidrBlocks)
});
provisioning.node.addDependency(ipv6Cidr);
// provision IP address's.
[
...props.vpc.publicSubnets,
...props.vpc.privateSubnets,
...props.vpc.isolatedSubnets,
].forEach((subnet) => {
subnet.node.addDependency(provisioning);
new ec2.CfnSubnetCidrBlock(this, `${subnet.node.addr}-cidr`, {
ipv6IpamPoolId: pool.attrIpamPoolId,
subnetId: subnet.subnetId,
ipv6NetmaskLength: 64,
})
});
// add a EgressOnlyGateway to the vpc
const egressOnlyIgw = new ec2.CfnEgressOnlyInternetGateway(this, 'EgressOnlyIGW', {
vpcId: props.vpc.vpcId,
});
// add a default route to the egress only gateway fpr all private subnets
props.vpc.privateSubnets.forEach((subnet) => {
new ec2.CfnRoute(this, `DefaultRoute-${subnet.node.addr}`, {
routeTableId: subnet.routeTable.routeTableId,
destinationIpv6CidrBlock: '::/0',
egressOnlyInternetGatewayId: egressOnlyIgw.ref,
});
});
// add a default route to the internet gateway for all public subnets
props.vpc.publicSubnets.forEach((subnet) => {
new ec2.CfnRoute(this, `DefaultRoute-${subnet.node.addr}`, {
routeTableId: subnet.routeTable.routeTableId,
destinationIpv6CidrBlock: '::/0',
gatewayId: props.vpc.internetGatewayId
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment