Skip to content

Instantly share code, notes, and snippets.

@stefanorg
Forked from jewelsjacobs/network-stack.ts
Created April 28, 2019 05:45
Show Gist options
  • Save stefanorg/c46270a0a288667c195166de6efa78ed to your computer and use it in GitHub Desktop.
Save stefanorg/c46270a0a288667c195166de6efa78ed to your computer and use it in GitHub Desktop.
CDK VPC Subnets with CIDR Addresses
import cdk = require('@aws-cdk/cdk');
import ec2 = require('@aws-cdk/aws-ec2');
import { SubnetType } from '@aws-cdk/aws-ec2';
const region = 'us-east';
const azA = `${region}-1a`;
const azB = `${region}-1b`;
const azC = `${region}-1c`;
const availabilityZones = [azA, azB, azC];
const publicCidrs = ['10.1.192.0/24', '10.1.194.0/24', '10.1.196.0/24']
const privateCidrs = ['10.1.193.0/24', '10.1.195.0/24', '10.1.197.0/24']
export class KhCdkInfrastructureStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.VpcNetwork(this, 'VPC', {
maxAZs: 3,
cidr: '10.1.192.0/18',
enableDnsHostnames: true,
enableDnsSupport: true,
vpnGateway: true, // export bug: https://github.com/awslabs/aws-cdk/issues/2339 - will remove when fixed
subnetConfiguration: [
{
cidrMask: 24,
name: 'Public',
subnetType: SubnetType.Public,
},
{
cidrMask: 24,
name: 'Private',
subnetType: SubnetType.Private,
}
],
});
const vpcResource = vpc.node.findChild('Resource') as ec2.CfnVPC;
vpcResource.addPropertyOverride('Tags', {
"Key" : 'Application',
"Value" : 'HeyKind'
});
// Iterate the public subnets
for (let [key, subnet] of vpc.publicSubnets.entries()) {
const subnetSource = subnet.node.findChild('Subnet') as ec2.CfnSubnet;
subnetSource.addPropertyOverride('CidrBlock', publicCidrs[key]);
subnetSource.addPropertyOverride('AvailabilityZone', availabilityZones[key]);
}
// Iterate the private subnets
for (let [key, subnet] of vpc.privateSubnets.entries()) {
const subnetSource = subnet.node.findChild('Subnet') as ec2.CfnSubnet;
subnetSource.addPropertyOverride('CidrBlock', privateCidrs[key]);
subnetSource.addPropertyOverride('AvailabilityZone', availabilityZones[key]);
}
/* Outputs to be for App Stack.
* Will be imported with: cdk.Fn.importValue('VpcId')
* @see {@link: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html}
* @see {@link: https://awslabs.github.io/aws-cdk/refs/_aws-cdk_cdk.html?highlight=importvalue#@aws-cdk/cdk.Fn.importValue}
* @see {@link: https://awslabs.github.io/aws-cdk/refs/_aws-cdk_aws-ec2.html#@aws-cdk/aws-ec2.VpcNetwork.importFromContext}
*/
vpc.export();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment