Instantly share code, notes, and snippets.

What would you like to do? for VPC NAT Instance
# Configure the instance to run as a Port Address Translator (PAT) to provide
# Internet connectivity to private instances.
# This is pretty much the same as the script from a AWS AmazonLinux NAT instance except that we tweak
#the iptables rule to NOT NAT traffic that has to flow over the VPN but NAT anything that does'nt match our remote ends
#VPC CIDR value. This way access to remote subnet over VPN will be normally routed and not NATted to IP of our NAT instance.
#E.g. in this script, the assumption is that the VPC CIDR for the "other" end is YMMV.
#See for full atricle.
# Srinivas - 20120820.
set -x
echo "Determining the MAC address on eth0"
ETH0_MAC=`/sbin/ifconfig | /bin/grep eth0 | awk '{print tolower($5)}' | grep '^[0-9a-f]\{2\}\(:[0-9a-f]\{2\}\)\{5\}$'`
if [ $? -ne 0 ] ; then
echo "Unable to determine MAC address on eth0" | logger -t "ec2"
exit 1
echo "Found MAC: ${ETH0_MAC} on eth0" | logger -t "ec2"
echo "Metadata location for vpc ipv4 range: ${VPC_CIDR_URI}" | logger -t "ec2"
VPC_CIDR_RANGE=`curl --retry 3 --retry-delay 0 --silent --fail ${VPC_CIDR_URI}`
if [ $? -ne 0 ] ; then
echo "Unable to retrive VPC CIDR range from meta-data. Using instead. PAT may not function correctly" | logger -t "ec2"
echo "Retreived the VPC CIDR range: ${VPC_CIDR_RANGE} from meta-data" |logger -t "ec2"
echo 1 > /proc/sys/net/ipv4/ip_forward && \
echo 0 > /proc/sys/net/ipv4/conf/eth0/send_redirects && \
/sbin/iptables -t nat -A POSTROUTING -o eth0 -s ${VPC_CIDR_RANGE} -d -j ACCEPT && \
/sbin/iptables -t nat -A POSTROUTING -o eth0 -s ${VPC_CIDR_RANGE} -j MASQUERADE
if [ $? -ne 0 ] ; then
echo "Configuration of PAT failed" | logger -t "ec2"
exit 0
echo "Configuration of PAT complete" |logger -t "ec2"
exit 0

This comment has been minimized.

j0nes2k commented Dec 3, 2014

If you are using this for a NAT box on a recent AMI (like Ubuntu 14.04 or Amazon NAT 2014.09), you may have slow download speeds. You can fix this by running on the NAT machine (as root):

ethtool -K eth0 sg off

This comment has been minimized.

markstos commented Feb 16, 2015

The reference to '' is a hardcoded reference to us-west or us-east (I'm not sure which, but I've seen this before). Here's a newer version that I think works in all regions without that hardcoding:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment