Create a gist now

Instantly share code, notes, and snippets.

configure-pat.sh for VPC NAT Instance
#!/bin/bash
# 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 configure-pat.sh 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 172.19.0.0/16. YMMV.
#See http://www.onepwr.org/2012/08/20/link-amazon-vpcs-over-a-ipsec-site-to-site-vpn/ 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
fi
echo "Found MAC: ${ETH0_MAC} on eth0" | logger -t "ec2"
VPC_CIDR_URI="http://169.254.169.254/latest/meta-data/network/interfaces/macs/${ETH0_MAC}/vpc-ipv4-cidr-block"
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 0.0.0.0/0 instead. PAT may not function correctly" | logger -t "ec2"
VPC_CIDR_RANGE="0.0.0.0/0"
else
echo "Retreived the VPC CIDR range: ${VPC_CIDR_RANGE} from meta-data" |logger -t "ec2"
fi
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 172.19.0.0/16 -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
fi
echo "Configuration of PAT complete" |logger -t "ec2"
exit 0
@j0nes2k
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
@markstos

The reference to '172.19.0.0' 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: https://gist.github.com/natefox/9611189

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