Skip to content

Instantly share code, notes, and snippets.

@clayrichardson
Created February 8, 2014 07:54
Show Gist options
  • Save clayrichardson/ee7beff2c7e0bbf888da to your computer and use it in GitHub Desktop.
Save clayrichardson/ee7beff2c7e0bbf888da to your computer and use it in GitHub Desktop.
#!/bin/bash
set -ex
# Swap file commands from:
# https://www.digitalocean.com/community/articles/how-to-add-swap-on-ubuntu-12-04
# Create swapfile
echo "Creating swap file..."
dd if=/dev/zero of=/swapfile bs=1024 count=4096k
# Create linux swap area
mkswap /swapfile
# Activate the swap file
swapon /swapfile
# Display summary
swapon -s
# Add entry to fstab
# Notice: running this script multiple times
# will append duplicate entries in fstab
echo "/swapfile none swap sw 0 0" >> /etc/fstab
# Set swapiness to 0, so swap is only used when
# physical memory is not available
echo 0 | sudo tee /proc/sys/vm/swappiness
echo vm.swappiness = 0 | sudo tee -a /etc/sysctl.conf
# Change ownership, so only root can view
chown root:root /swapfile
chmod 0600 /swapfile
# Some useful tools I like to use
# You may omit this line if you wish
apt-get install -y htop git bmon iotop traceroute curl
# Add the connected user "${USER}" to the docker group.
# Change the user name to match your preferred user.
# You may have to logout and log back in again for
# this to take effect.
sudo gpasswd -a ubuntu docker
# Restart the docker daemon.
sudo service docker restart
# Configure the instance to run as a Port Address Translator (PAT) to provide
# Internet connectivity to private instances.
function log { logger -t "vpc" -- $1; }
function die {
[ -n "$1" ] && log "$1"
log "Configuration of PAT failed!"
exit 1
}
# Sanitize PATH
PATH="/usr/sbin:/sbin:/usr/bin:/bin"
log "Determining the MAC address on eth0..."
ETH0_MAC=$(cat /sys/class/net/eth0/address) ||
die "Unable to determine MAC address on eth0."
log "Found MAC ${ETH0_MAC} for eth0."
VPC_CIDR_URI="http://169.254.169.254/latest/meta-data/network/interfaces/macs/${ETH0_MAC}/vpc-ipv4-cidr-block"
log "Metadata location for vpc ipv4 range: ${VPC_CIDR_URI}"
VPC_CIDR_RANGE=$(curl --retry 3 --silent --fail ${VPC_CIDR_URI})
if [ $? -ne 0 ]; then
log "Unable to retrive VPC CIDR range from meta-data, using 0.0.0.0/0 instead. PAT may be insecure!"
VPC_CIDR_RANGE="0.0.0.0/0"
else
log "Retrieved VPC CIDR range ${VPC_CIDR_RANGE} from meta-data."
fi
log "Enabling PAT..."
sysctl -q -w net.ipv4.ip_forward=1 net.ipv4.conf.eth0.send_redirects=0 && (
iptables -t nat -C POSTROUTING -o eth0 -s ${VPC_CIDR_RANGE} -j MASQUERADE 2> /dev/null ||
iptables -t nat -A POSTROUTING -o eth0 -s ${VPC_CIDR_RANGE} -j MASQUERADE ) ||
die
sysctl net.ipv4.ip_forward net.ipv4.conf.eth0.send_redirects | log
iptables -n -t nat -L POSTROUTING | log
log "Configuration of PAT complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment