Last active
March 24, 2016 17:24
-
-
Save Gabriellpweb/b246dad9eec0eb813a7b to your computer and use it in GitHub Desktop.
Sync a ec2 instance inside a specific load balancer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# SCRIPT REQUIRE NGINX PERMISSIONS ON SYNC_PATH AND SSH ACCESS TO MACHINES. | |
ELB_NAME=MY_ELB_NAME | |
LIST_FILE=/tmp/instance_list_$(date +%Y%m%d%H%M%S).txt | |
LOG_FILE=/tmp/instance_sync_$(date +%Y%m%d%H%M%S).log | |
SYNC_PATH=/var/www | |
SEND_ALERT="aws sns publish --topic-arn MY_SNS_TOPIC --message" | |
ACCESS_KEY=MY-KEY | |
SECRET_KEY=MY-SECRET | |
REGION=THE-REGION | |
# Busca ip publico atual | |
myip4=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4|head -1) | |
SYNC_OK=0 | |
# Busca lista de instancias do load balancer | |
aws elb describe-instance-health --load-balancer-name ${ELB_NAME} | jq ".InstanceStates[] | select(.State == \"InService\").InstanceId" | sed -e 's/"//g' > $LIST_FILE | |
# Para cada instancia | |
for instance_id in $(cat $LIST_FILE) | |
do | |
echo "Tentativa de sync com a instancia $instance_id" > $LOG_FILE | |
# Pega o host | |
host=$(ec2-describe-instances --aws-access-key=${ACCESS_KEY} --aws-secret-key=${SECRET_KEY} --region=${REGION} -F instance-id=${instance_id} | fgrep INSTANCE | awk {'print $14'} | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b") | |
# Se não for a mesma maquina | |
if [ ! -z "$host" ] && [ "$myip4" != "$host" ] | |
then | |
echo "Copiando da instancia $instance_id $host" > $LOG_FILE | |
mv -rf SYNC_PATH SYNC_PATH_old | |
rsync -4phrztgoDvlXe 'ssh -l nginx -o "StrictHostKeyChecking false"' --exclude ".svn/" --exclude ".git/" --exclude-from=/home/scripts/sync_exclude_files_init $host:SYNC_PATH SYNC_PATH | |
SYNC_OK=1 | |
else | |
echo "Falha ao tentar sync com a instancia $instance_id" > $LOG_FILE | |
fi | |
done | |
if [ "$SYNC_OK" -eq 0 ] | |
then | |
$SEND_ALERT "Falha para efetuar o sync da instância de host $myip4" > $LOG_FILE | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment