Last active
October 18, 2019 08:53
-
-
Save dnmvisser/2659defa5a1974b109413b2941472ff6 to your computer and use it in GitHub Desktop.
AWS instance that provided IPv4 internet connectivity for backend hosts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Configure the instance to run as a Port Address Translator (PAT) to provide | |
# Internet connectivity to private instances. | |
# | |
#set -x | |
echo "Determining default interface" | |
IFACE=`ip -o route show default | grep default | awk '{print $5}'` | |
echo "Determining the MAC address on default interface" | |
IFACE_MAC=`cat /sys/class/net/${IFACE}/address` | |
if [ $? -ne 0 ] ; then | |
echo "Unable to determine MAC address on ${IFACE}" | logger -t "ec2" | |
exit 1 | |
fi | |
echo "Found MAC: ${IFACE_MAC} on ${IFACE}" | logger -t "ec2" | |
VPC_CIDR_URI="http://169.254.169.254/latest/meta-data/network/interfaces/macs/${IFACE_MAC}/vpc-ipv4-cidr-block" | |
echo "Metadata location for VPC IPv4 range: ${VPC_CIDR_URI}" | logger -t "ec2" | |
VPC_CIDR_RANGE=`wget --retry-connrefused --waitretry=0 --quiet -O - "${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 "Retrived 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/${IFACE}/send_redirects && \ | |
/sbin/iptables -t nat -A POSTROUTING -o ${IFACE} -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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment