Last active
February 14, 2021 13:22
-
-
Save weldpua2008/a899229403cb9da7d5458c3f39b9adfa to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env bash | |
set -e | |
SCRIPT_NAME=$(basename $0) | |
USAGE="$SCRIPT_NAME <instance-name> <instance-type>\nFor example: $SCRIPT_NAME myserver t3.2xlarge" | |
if [ -z "$1" ]; then | |
echo -e $USAGE | |
exit 1 | |
elif [ -z "$2" ]; then | |
echo -e $USAGE | |
exit 1 | |
elif [[ $* == *-h* ]]; then | |
echo -e $USAGE | |
exit 0 | |
else | |
INSTANCE_NAME=$1 | |
INSTANCE_TYPE=$2 | |
fi | |
export AWS_PROFILE=${AWS_PROFILE:=production_42} | |
export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:=us-east-1} | |
AWS="aws ec2 --profile ${AWS_PROFILE} --region ${AWS_REGION:=$AWS_DEFAULT_REGION} " | |
report_i(){ | |
echo "[$(date "+%b %d %Y %T")] instance ${INSTANCE_ID} : $@" | |
} | |
stop_ec2(){ | |
report_i "Stopping" \ | |
&& ${AWS} stop-instances --instance-ids ${INSTANCE_ID} \ | |
&& report_i "wait instance-stopped" \ | |
&& ${AWS} wait instance-stopped --instance-ids ${INSTANCE_ID} && return 0 | |
return 1 | |
} | |
start_ec2(){ | |
report_i "Starting" \ | |
&& ${AWS} start-instances --instance-ids ${INSTANCE_ID} \ | |
&& report_i "wait instance-running" \ | |
&& ${AWS} wait instance-running --instance-ids ${INSTANCE_ID} \ | |
&& report_i "wait instance-status-ok" \ | |
&& ${AWS} wait instance-status-ok --instance-ids ${INSTANCE_ID} \ | |
&& return 0 | |
return 1 | |
} | |
modify_instance(){ | |
report_i "Start modify" \ | |
&& ${AWS} modify-instance-attribute \ | |
--instance-id $INSTANCE_ID \ | |
--instance-type $INSTANCE_TYPE && return 0 | |
} | |
INSTANCE_ID=$(${AWS} describe-instances \ | |
--filter "Name=tag:Name,Values=${INSTANCE_NAME}" \ | |
--query "Reservations[].Instances[].InstanceId[]" \ | |
--output text) | |
if [[ -z $INSTANCE_ID ]];then | |
echo "No INSTANCE_ID for ${INSTANCE_NAME}" | |
exit 1 | |
fi | |
INITIAL_INSTANCE_TYPE=$(${AWS} describe-instance-attribute \ | |
--instance-id $INSTANCE_ID \ | |
--attribute instanceType \ | |
--query 'InstanceType.Value' \ | |
--output text) | |
if [ $INITIAL_INSTANCE_TYPE == $INSTANCE_TYPE ]; then | |
echo "$INSTANCE_NAME is already $INSTANCE_TYPE" | |
exit 0 | |
fi | |
stop_ec2 | |
modify_instance | |
start_ec2 | |
FINAL_INSTANCE_TYPE=$(aws ec2 describe-instance-attribute \ | |
--instance-id $INSTANCE_ID \ | |
--attribute instanceType \ | |
--query 'InstanceType.Value' \ | |
--output text) | |
MESSAGE="Switched $INSTANCE_NAME from $INITIAL_INSTANCE_TYPE to $FINAL_INSTANCE_TYPE" | |
echo $MESSAGE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment