Skip to content

Instantly share code, notes, and snippets.

@windlessuser
Created November 6, 2019 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save windlessuser/5812b02b09dada44fde241a11effcda7 to your computer and use it in GitHub Desktop.
Save windlessuser/5812b02b09dada44fde241a11effcda7 to your computer and use it in GitHub Desktop.
This is a gist of how I created a NAT Instance for my VPC instead of using the Default NAT Gateway included in the VPC Constructor. THis worked up until version 1.13.0 of the AWS CDK. No longer works.
import cdk = require("@aws-cdk/core");
import ec2 = require("@aws-cdk/aws-ec2");
export class NATStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// We want a VPC across 2 AZs but NO NAT Gateways
const vpc = new ec2.Vpc(this, "VPC", {
natGateways: 0,
maxAzs: 2
});
const natSecurityGroup = new ec2.SecurityGroup(this, "NATSecurityGroup", {
vpc,
description: "NAT Instance Security Group",
allowAllOutbound: true
});
natSecurityGroup.connections.allowFromAnyIpv4(ec2.Port.allTcp());
const natInstance = new ec2.CfnInstance(this, "NATInstance", {
imageId: "ami-0f9c61b5a562a16af", //NAT Instance AMI for us-east-2 - Change this for your Region: https://aws.amazon.com/amazon-linux-ami/
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.BURSTABLE3,
ec2.InstanceSize.SMALL
).toString(),
subnetId: vpc.publicSubnets[0].subnetId,
tags: [
new cdk.Tag("Name", "Project NAT Instance"),
],
securityGroupIds: [natSecurityGroup.securityGroupId],
sourceDestCheck: false // Required for NAT,
});
vpc.privateSubnets.forEach(subnet => {
const defaultRoute = subnet.node.findChild(
"DefaultRoute"
) as ec2.CfnRoute;
defaultRoute.addPropertyOverride("InstanceId", natInstance.ref);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment