Skip to content

Instantly share code, notes, and snippets.

@pconerly
Forked from Ashex/eip_failover.sh
Last active September 19, 2015 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pconerly/ae5aa95c946e1f0a68e3 to your computer and use it in GitHub Desktop.
Save pconerly/ae5aa95c946e1f0a68e3 to your computer and use it in GitHub Desktop.
EIP failover
#!/bin/sh
# This script will monitor another HA node and take over an Elastic IP (EIP)
# if communication with the other node fails
# High Availability IP variables
# Other node's IP to ping and EIP to swap if other node goes down
HA_Node_IP=10.0.0.11
EIP=10.0.0.10
#Specify the Secondary Private IP for this node
PRIV_IP=10.0.0.12
# Specify the EC2 region that this will be running in
REGION=us-west-1
# Run aws-apitools-common.sh to set up default environment variables and to
# leverage AWS security credentials provided by EC2 roles
. /etc/profile.d/aws-apitools-common.sh
# Determine the instance and ENI IDs so we can reassign the VIP to the
# correct ENI.
# The following EC2 roles policy will authorize these
# commands:
# {
# "Statement": [
# {
# "Action": [
# "ec2:DescribeAddresses",
# "ec2:AssociateAddress"
# "ec2:DescribeInstances"
# ],
# "Effect": "Allow",
# "Resource": "*"
# }
# ]
# }
Instance_ID=`/usr/bin/curl --silent http://169.254.169.254/latest/meta-data/instance-id`
ENI_ID=`/opt/aws/bin/ec2-describe-instances $Instance_ID --region $REGION | grep eni -m 1 | awk '{print $2;}'`
ALLOC_ID=`/opt/aws/bin/ec2-describe-addresses $EIP --region $REGION | awk '{print $5;}'`
echo `date` "-- Starting HA monitor"
while [ . ]; do
pingresult=`ping -c 3 -W 1 $HA_Node_IP | grep time= | wc -l`
if [ "$pingresult" == "0" ]; then
echo `date` "-- HA heartbeat failed, taking over EIP"
/opt/aws/bin/ec2-associate-address -n $ENI_ID --allocation-id $ALLOC_ID --private-ip-address $PRIV_IP --allow-reassociation --region $REGION
pingresult=`ping -c 1 -W 1 $EIP | grep time= | wc -l`
if [ "$pingresult" == "0" ]; then
echo `date` "-- Restarting network"
/sbin/service network restart > /dev/null 2>&1
fi
sleep 60
fi
sleep 2
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment