Skip to content

Instantly share code, notes, and snippets.

@miyamoto-daisuke
Last active December 14, 2015 12:29
Show Gist options
  • Save miyamoto-daisuke/5087085 to your computer and use it in GitHub Desktop.
Save miyamoto-daisuke/5087085 to your computer and use it in GitHub Desktop.
#! /bin/bash
SELF_INSTANCE_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
ELB_NAME=elbfailover
SLEEPTIME=2
while :; do
TIMESTAMP=`date -u +"%Y-%m-%dT%H:%M:%SZ"`
ELB_STATUS=`aws elb describe-instance-health --load-balancer-name $ELB_NAME`
HEALTHY_HOST_COUNT=`echo $ELB_STATUS | jq "[ .InstanceStates[] | select(.InstanceId != \"$SELF_INSTANCE_ID\" and .State == \"InService\") ] | length"`
SORRY_HOST_COUNT=`echo $ELB_STATUS | jq "[ .InstanceStates[] | select(.InstanceId == \"$SELF_INSTANCE_ID\") ] | length"`
if [ $HEALTHY_HOST_COUNT -gt 0 ]; then
echo $TIMESTAMP : $HEALTHY_HOST_COUNT healty host\(s\) found on $ELB_NAME
if [ $SORRY_HOST_COUNT -gt 0 ]; then
echo deregistering sorry host: $SELF_INSTANCE_ID from $ELB_NAME
RESULT=`aws elb deregister-instances-from-load-balancer \
--instances "{\"instance_id\": \"$SELF_INSTANCE_ID\"}" --load-balancer-name $ELB_NAME`
if [ $? -eq 0 ]; then
echo sorry host was deregistered successfully
else
echo "ERROR: fail to deregister sorry host"
echo $RESULT | jq "."
fi
fi
else
echo $TIMESTAMP : healthy host not found on $ELB_NAME
if [ $SORRY_HOST_COUNT -eq 0 ]; then
echo registering sorry host: $SELF_INSTANCE_ID to $ELB_NAME
RESULT=`aws elb register-instances-with-load-balancer \
--instances "{\"instance_id\": \"$SELF_INSTANCE_ID\"}" --load-balancer-name $ELB_NAME`
if [ $? -eq 0 ]; then
echo sorry host was registered successfully
else
echo "ERROR: fail to register sorry host"
echo $RESULT | jq "."
fi
fi
fi
sleep $SLEEPTIME
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment