Created
May 15, 2018 12:11
-
-
Save eekfonky/c8d910982b4f5a4f57db96cfda3cc23c to your computer and use it in GitHub Desktop.
Stop/Start EC2
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 | |
# Set variables for tags, region, SSH key location & user | |
# Set these 4 to appropriate values | |
REGION="eu-central-1" | |
TAG="<EC2_TAG>" | |
SSH="~/.ssh/<PATH_TO_FILE>" | |
USER="ubuntu" | |
# Check AWS credentials exist | |
if [[ $(aws configure list | grep "*") && $? -eq 0 ]]; then | |
: | |
else | |
echo "Please configure AWS credentials to continue..." | |
exit 0 | |
fi | |
# Get instance ID | |
ID="$(aws ec2 --region $REGION describe-instances --filters "Name=tag:Name,Values=$TAG" --query Reservations[].Instances[].InstanceId --output=text)" | |
## Functions | |
# State of instance | |
STATE () { | |
aws ec2 --region $REGION describe-instances --filters "Name=tag:Name,Values=$TAG" --query Reservations[].Instances[].State[].Name --output=text | |
} | |
# Get Public IP of instance | |
PUBLIC_IP () { | |
aws ec2 --region $REGION describe-instances --filters "Name=tag:Name,Values=$TAG" --query Reservations[].Instances[].NetworkInterfaces[].Association[].PublicIp --output=text | |
} | |
## | |
# Stop instance if running | |
if [ "$(STATE)" = "running" ]; then | |
read -p "Stop Instance $TAG (y/n)? " answer | |
case ${answer:0:1} in | |
y|Y ) | |
echo "$TAG" "Stopping..." | |
aws ec2 stop-instances --instance-ids "$ID" --region "$REGION" > /dev/null 2>&1 | |
spin='-\|/' | |
i=0 | |
while [ "$(STATE)" != "stopped" ]; do | |
i=$(( (i+1) %4 )) | |
printf "\r${spin:$i:1}" | |
sleep .1 | |
done | |
echo | |
echo "$TAG" "Stopped!" | |
;; | |
* ) | |
exit 0 | |
;; | |
esac | |
# Start instance if stopped | |
else | |
read -p "Start Instance $TAG (y/n)? " answer | |
case ${answer:0:1} in | |
y|Y ) | |
echo "$TAG" "Starting..." | |
aws ec2 start-instances --instance-ids "$ID" --region "$REGION" > /dev/null 2>&1 | |
spin='-\|/' | |
i=0 | |
while [ "$(STATE)" != "running" ]; do | |
i=$(( (i+1) %4 )) | |
printf "\r${spin:$i:1}" | |
sleep .1 | |
done | |
echo | |
echo "$TAG" "Started..." | |
;; | |
* ) | |
exit 0 | |
;; | |
esac | |
echo "Logging into instance" | |
# Get Public IP | |
PUBLIC_IP > /dev/null 2>&1 | |
# SSH into instance | |
until ssh -qi ssh -i "$SSH" "$USER"@"$(PUBLIC_IP)" | |
do | |
sleep .1 | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment