Last active
February 22, 2019 08:11
-
-
Save vwrs/3b8370b9d566db4cf2d1bc9d43b3d34c to your computer and use it in GitHub Desktop.
Stop an AWS EC2 instance
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/bash -eu | |
DEFAULT_REGION=ap-northeast-1 | |
INSTANCE_ID=`curl -fsSL http://169.254.169.254/latest/meta-data/instance-id/` | |
if [ $? = 0 ]; then | |
echo "instance-id:["$INSTANCE_ID"]" | |
else | |
echo "An unexpected error occurred when trying to get instance-id." | |
exit 1 | |
fi | |
if ! type jq >/dev/null 2>&1; then | |
echo 'jq command is not found. Please install jq.' | |
exit 1 | |
fi | |
INSTANCE_TYPE=`aws ec2 describe-instances --instance-ids $INSTANCE_ID --region $DEFAULT_REGION | jq -r '.Reservations[].Instances[].InstanceType'` | |
if [ $? = 0 ]; then | |
echo "instance-type: [$INSTANCE_TYPE]" | |
else | |
echo "An unexpected error occurred when trying to get instance-type. " | |
echo "DEFAULT_REGION: $DEFAULT_REGION" | |
exit 1 | |
fi | |
INSTANCE_STATUS=`aws ec2 describe-instances --instance-ids $INSTANCE_ID --region $DEFAULT_REGION | jq -r '.Reservations[].Instances[].State.Name'` | |
echo "instance-status:["$INSTANCE_STATUS"]" | |
if [ -n "$INSTANCE_STATUS" ] && [ $INSTANCE_STATUS = 'running' ] ; then | |
echo "ec2-instance stopping..." | |
aws ec2 stop-instances --instance-ids $INSTANCE_ID --region $DEFAULT_REGION | |
else | |
echo "Instance $INSTANCE_ID has already stopped." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment