Last active
August 29, 2015 13:57
-
-
Save i97506051502/9655969 to your computer and use it in GitHub Desktop.
stop_instances.sh は,引数に渡したサーバーリスト内の EC2 インスタンスを「順番に」停止します。サーバーリストには Name タグの Value を列挙します。
This file contains hidden or 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 | |
# Check number of variables. | |
if [ $# != 1 ] | |
then | |
echo 'Usage:' | |
echo './start_instances.sh servers.list' | |
exit 255 | |
fi | |
# | |
# Variables | |
# | |
NUMBER_OF_SERVERS=`cat ${1} | grep "" -c` | |
# Create variables below | |
# SERVER_0? | |
# ID_SERVER_0? | |
i=1 | |
while read LINE | |
do | |
export SERVER_0${i}=`echo ${LINE}` | |
export SERVER_NAME=`eval echo '$'{SERVER_0"$i"}` | |
export ID_SERVER_0${i}=`aws ec2 describe-instances --filters "Name=tag-value,Values=${SERVER_NAME}" | jq '.Reservations[].Instances[].InstanceId' | cut -c 2-11` | |
let i=i+1 | |
done < ${1} | |
# | |
# functions | |
# | |
function stop_ec2_instance() { | |
IF_STOPPED=`aws ec2 describe-instances --instance-ids ${1} | jq '.Reservations[].Instances[].State[]' | head -1` | |
if [ "${IF_RUNNING}" = \"stopped\" ] | |
then | |
echo ${2} has already stopped. | |
else | |
aws ec2 stop-instances --instance-ids ${1} 1>/dev/null | |
if [ ${?} = 0 ] | |
then | |
echo stop ${2}. | |
else | |
echo Some Error Occured in stopping ${2}. | |
fi | |
fi | |
} | |
function check_if_stopped_ec2_instance() { | |
# if stopped | |
IF_STOPPED=`aws ec2 describe-instances --instance-ids ${1} | jq '.Reservations[].Instances[].State[]' | head -1` | |
if [ "${IF_STOPPED}" = \"stopped\" ] | |
then | |
echo ${2} stopped. | |
break | |
else | |
sleep 5 | |
echo ${2} is stopping... | |
fi | |
} | |
# | |
# main | |
# | |
for i in `seq 1 ${NUMBER_OF_SERVERS}` | |
do | |
export INSTANCE_ID=`eval echo '$'{ID_SERVER_0"$i"}` | |
export SERVER_NAME=`eval echo '$'{SERVER_0"$i"}` | |
stop_ec2_instance ${INSTANCE_ID} ${SERVER_NAME} | |
while true | |
do | |
check_if_stopped_ec2_instance ${INSTANCE_ID} ${SERVER_NAME} | |
done | |
let i=i+1 | |
done | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment