add vpcaccess role
[awsible] / roles / vpcaccess / files / ec2-pat.sh
1 #!/bin/bash
2
3 # Configure the instance to run as a Port Address Translator (PAT) to provide
4 # Internet connectivity to private instances.
5 #
6
7 IF='eth0'
8
9 set -o pipefail
10
11 function log(){
12 echo "$@" | /usr/bin/logger -t 'ec2-pat'
13 }
14
15 echo "Determining the MAC address on ${IF}"
16 if ! IF_MAC=$(/sbin/ip address show dev ${IF} |
17 /bin/grep 'link/ether' |
18 /bin/awk '{print tolower($2)}')
19 then
20 log "Unable to determine MAC address on eth0"
21 exit 1
22 fi
23 log "Found MAC: ${IF_MAC} on ${IF}"
24
25 VPC_CIDR_URI="http://169.254.169.254/latest/meta-data/network/interfaces/macs/${IF_MAC}/vpc-ipv4-cidr-block"
26 if ! VPC_CIDR_RANGE=$(/usr/bin/curl --retry 3 --retry-delay 1 --silent --fail "${VPC_CIDR_URI}")
27 then
28 VPC_CIDR_RANGE="0.0.0.0/0"
29 log "Unable to retrive VPC CIDR range from meta-data. Using ${VPC_CIDR_RANGE} instead. PAT may not function correctly!"
30 else
31 log "Retrived the VPC CIDR range: ${VPC_CIDR_RANGE} from meta-data"
32 fi
33
34 if ! /sbin/sysctl -w 'net.ipv4.ip_forward=1' &&
35 /sbin/sysctl -w "net.ipv4.conf.${IF}.send_redirects=0" &&
36 /sbin/iptables -t nat -A POSTROUTING -o ${IF} -s ${VPC_CIDR_RANGE} -j MASQUERADE
37 then
38 log "Configuration of PAT failed"
39 exit 1
40 fi
41
42 log "Configuration of PAT complete"
43 /sbin/iptables-save > /etc/sysconfig/iptables