Skip to content

Instantly share code, notes, and snippets.

@j3tm0t0
Created February 14, 2014 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save j3tm0t0/9006492 to your computer and use it in GitHub Desktop.
Save j3tm0t0/9006492 to your computer and use it in GitHub Desktop.
same as https://gist.github.com/j3tm0t0/8980236 but with EIP for each AZ
#!/bin/sh -x
# function to get meta-data info
function m ()
{
curl --retry 3 --retry-delay 0 --silent --fail http://169.254.169.254/latest/meta-data/$1
}
# EIP for each AZ
declare -A EIP
EIP['ap-northeast-1a']='eipalloc-5887903a'
EIP['ap-northeast-1b']='eipalloc-5987903b'
EIP['ap-northeast-1c']='eipalloc-5e87903c'
# get REGION and setenv
export AWS_DEFAULT_REGION=`m placement/availability-zone | sed 's/.$//'`
# get instanceId
instanceId=`m instance-id`
# firstly disabling src/dst check of myself
aws ec2 modify-instance-attribute --instance-id $instanceId --source-dest-check false
# get network related values
mac=`ifconfig eth0 | grep ^eth0 | awk '{print $5}' | tr '[:upper:]' '[:lower:]'`
vpcId=`m network/interfaces/macs/$mac/vpc-id`
vpcCidr=`m network/interfaces/macs/$mac/vpc-ipv4-cidr-block || echo 0.0.0.0/0`
az=`m placement/availability-zone`
# put following script in /etc/rc.local
cat << EOF >> /etc/rc.local
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 $vpcCidr -j MASQUERADE
EOF
# get route table to modify
routeTableId=`aws ec2 describe-route-tables --filters Name=vpc-id,Values=$vpcId --filters Name=tag:NAT,Values=$az --query RouteTables[0].RouteTableId | tr -d ツ・"`
# set default route to myself
aws ec2 replace-route --route-table-id $routeTableId --destination-cidr-block "0.0.0.0/0" --instance-id $instanceId
# setup health check
yum -y install httpd
service httpd start
chkconfig httpd on
cat << EOF | base64 -d > /var/www/cgi-bin/healthcheck
IyEvYmluL3NoCmNvdW50PTMKdGltZW91dD0yCgpzdWNjZXNzPTAKZm9yIGlwIGluIGBlY2hvICRQ
QVRIX0lORk8gfCBwZXJsIC1wZSAncyNbXlxkXC4vXSMjZztzIy8jXCAjZydgCmRvCglwaW5nICRp
cCAtYyAkY291bnQgLVcgJHRpbWVvdXQgPiAvZGV2L251bGwgICYmIHN1Y2Nlc3M9MQpkb25lCgpp
ZiBbICIkc3VjY2VzcyIgPSAiMCIgXQp0aGVuCglleGl0IC0xCQpmaQoKY2F0IDw8IEVPRgpDb250
ZW50LXR5cGU6IHRleHQvcGxhaW4KCk9LCkVPRgo=
EOF
chmod +x /var/www/cgi-bin/healthcheck
# associate EIP if needed
if [ "${EIP[$az]}" != "" ]
then
aws ec2 associate-address --instance-id $instanceId --allocation-id ${EIP[$az]} --allow-reassociation
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment