Last active
March 16, 2018 11:19
-
-
Save eekfonky/d7643c3e30395d888b196199aeb6baeb to your computer and use it in GitHub Desktop.
Stop or Start (and SSH to) 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 | |
# Set variables for tags, region, SSH key location & user | |
# Set these 4 to appropriate values | |
REGION="eu-central-1" | |
TAG="chris-sandbox" | |
SSH="~/.ssh/frankfurt.pem" | |
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 | |
echo "$TAG" "Stopping..." | |
aws ec2 stop-instances --instance-ids "$ID" --region "$REGION" > /dev/null 2>&1 | |
while [ "$(STATE)" != "stopped" ]; do | |
sleep 5 | |
done | |
echo "$TAG" "Stopped!" | |
else | |
# Start instance if stopped | |
echo "$TAG" "Starting..." | |
aws ec2 start-instances --instance-ids "$ID" --region "$REGION" > /dev/null 2>&1 | |
while [ "$(STATE)" != "running" ]; do | |
sleep 2 | |
done | |
echo "$TAG" "Started..." | |
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