AWS CloudFormation template for a VPC with NAT

16 comments

I had trouble finding a nice generic CloudFormation template that would take the complexity and pain out of setting up a VPC with NAT so I made one myself.  Enjoy:

AWS VPC NAT issue with Debian

0 comments

This is an incredibly obscure issue so I doubt it will help anyone, but in the rare chance that some poor soul is about to waste 3 days on this problem I hope to spare you the grief...

AWS VPC supports some advanced network topologies, including NAT.  Using a CloudFormation template similar to this one, I created a VPC with public and private subnets and a NAT instance to route internet traffic from the private subnet.  The setup worked great for Amazon Linux and Ubuntu AMIs but I needed a Debian image for my specific use case (yes, I know Ubuntu is based on Debian but it had issues with VirtualBox...).

Unfortunately, when I switched to the Debian image, my private subnet instances simply would not connect to the internet.  Like I mentioned, I wasted three days scouring the Internet and learning more than I ever wanted to about iptables.  Long story short, you need to run the following commands as root on your NAT instance (or add it to the NAT EC2 instance UserData section in your CloudFormation template):

echo 1 > /proc/sys/net/ipv4/ip_forward
echo net.ipv4.ip_forward = 1 > /etc/sysctl.d/ip_forward.conf
iptables -t nat -A POSTROUTING -s YOUR_PRIVATE_SUBNET_CIDR -j MASQUERADE
apt-get install -y iptables-persistent
iptables-save > /etc/iptables/rules.v4