Skip to content

Instantly share code, notes, and snippets.

@YoshihitoAso
Last active December 14, 2015 13:48
Show Gist options
  • Save YoshihitoAso/5095996 to your computer and use it in GitHub Desktop.
Save YoshihitoAso/5095996 to your computer and use it in GitHub Desktop.
ELBフェイルオーバー用のShell
#! /bin/bash
SORRY_INSTANCE=`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 != \"$SORRY_INSTANCE\" and .State == \"InService\") ] | length"`
SORRY_HOST_COUNT=`echo $ELB_STATUS | jq "[ .InstanceStates[] | select(.InstanceId == \"$SORRY_INSTANCE\") ] | 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: $SORRY_INSTANCE from $ELB_NAME
RESULT=`aws elb deregister-instances-from-load-balancer \
--instances "{\"instance_id\": \"$SORRY_INSTANCE\"}" --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: $SORRY_INSTANCE to $ELB_NAME
RESULT=`aws elb register-instances-with-load-balancer \
--instances "{\"instance_id\": \"$SORRY_INSTANCE\"}" --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