Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[AWS] インスタンスをスケールアップするときに ELB 配下だったら、一度外して再参加させるやつ
#!/bin/sh
INSTANCE_ID="${1}"
INSTANCE_TYPE="${2}"
# 指定されたインスタンスタイプが現在のものと同じだったら何もしない
CURRENT_INSTANCE_TYPE=`aws ec2 describe-instances --instance-ids ${INSTANCE_ID} | jq -r '.Reservations[].Instances[].InstanceType'`
if [ "${CURRENT_INSTANCE_TYPE}" = "${INSTANCE_TYPE}" ]; then
echo "current instance type : ${CURRENT_INSTANCE_TYPE}"
exit 0
fi
# ELB 配下かどうか確認
ELB_NAME=''
ELBS=`aws elb describe-load-balancers | jq -r ".LoadBalancerDescriptions[].LoadBalancerName"`
for ELB in ${ELBS}; do
ELB_INSTANCE_IDS=`aws elb describe-instance-health --load-balancer-name ${ELB} | jq -r ".InstanceStates[].InstanceId"`
for ELB_INSTANCE_ID in ${ELB_INSTANCE_IDS}; do
if [ "${ELB_INSTANCE_ID}" = "${INSTANCE_ID}" ]; then
ELB_NAME="${ELB}"
break
fi
done
ELB_INSTANCE_IDS=''
if [ "${ELB_NAME}" != "" ]; then
break;
fi
done
# ELB 配下だったら取り外す
if [ "${ELB_NAME}" != "" ]; then
echo " Remove ELB: ${INSTANCE_ID} from ${ELB_NAME}"
aws elb deregister-instances-from-load-balancer --load-balancer-name=${ELB_NAME} --instances=${INSTANCE_ID}
fi
# インスタンス停止して、stopped になるまで待つ
while :
do
EC2_STATE=`aws ec2 describe-instances --instance-ids ${INSTANCE_ID} | jq -r '.Reservations[].Instances[].State | .Name'`
echo "${INSTANCE_ID} : ${EC2_STATE}"
if [ "${EC2_STATE}" = "running" ]; then
aws ec2 stop-instances --instance-ids ${INSTANCE_ID}
fi
if [ "${EC2_STATE}" = "stopped" ]; then
break
fi
sleep 10
done
# インスタンスタイプを変更する
aws ec2 modify-instance-attribute --instance-id ${INSTANCE_ID} --instance-type ${INSTANCE_TYPE}
# インスタンス開始して、running になるまで待つ
aws ec2 start-instances --instance-ids ${INSTANCE_ID}
while :
do
EC2_STATE=`aws ec2 describe-instances --instance-ids ${INSTANCE_ID} | jq -r '.Reservations[].Instances[].State | .Name'`
echo "${INSTANCE_ID} : ${EC2_STATE}"
if [ "${EC2_STATE}" = "running" ]; then
break
fi
sleep 10
done
# ELB に参加させる
if [ "${ELB_NAME}" != "" ]; then
echo " Add ELB: ${INSTANCE_ID} to ${ELB_NAME}"
aws elb register-instances-with-load-balancer --load-balancer-name=${ELB_NAME} --instances=${INSTANCE_ID}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.