Skip to content

Instantly share code, notes, and snippets.

@mehdi89
Last active February 11, 2023 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdi89/5f3fc412281c4e400a41c12a31867773 to your computer and use it in GitHub Desktop.
Save mehdi89/5f3fc412281c4e400a41c12a31867773 to your computer and use it in GitHub Desktop.
Stop and start a AWS EC2 instance from terminal
#! /bin/bash
INSTANCEID="i-08b39a2442179285a"
INSTANCETYPE=$1
echo "instance id: $INSTANCEID"
echo "instance type: $INSTANCETYPE"
#2>&1 > /dev/null to suppress the cli output
# get instance details to check the current instance type
CURRENTINSTANCETYPE=$(aws ec2 describe-instances --instance-ids $INSTANCEID --query 'Reservations[*].Instances[*].InstanceType' --output text)
echo "current instance type: $CURRENTINSTANCETYPE"
# if the instance type is not the same as the new type, change it
if [ "$CURRENTINSTANCETYPE" != "$INSTANCETYPE" ]; then
echo "stopping instance"
aws ec2 stop-instances --instance-ids $INSTANCEID 2>&1 > /dev/null
echo "waiting for instance to stop"
aws ec2 wait instance-stopped --instance-ids $INSTANCEID
# check if instance type has micro in it name
if [[ $CURRENTINSTANCETYPE == *"micro"* ]]; then
# if it does, change the instance type to t2.micro
echo "changing instance type to t2.large"
aws ec2 modify-instance-attribute --instance-id $INSTANCEID --instance-type t3.large
elif [[ $CURRENTINSTANCETYPE == *"large"* ]]; then
echo "changing instance type to t2.micro"
aws ec2 modify-instance-attribute --instance-id $INSTANCEID --instance-type t3.micro
fi
echo "starting instance"
aws ec2 start-instances --instance-ids $INSTANCEID 2>&1 > /dev/null
echo "waiting for instance to start"
aws ec2 wait instance-running --instance-ids $INSTANCEID
else
echo "instance type is already $INSTANCETYPE"
fi
# echo "changing instance type"
# aws ec2 modify-instance-attribute --instance-id $INSTANCEID --instance-type $2
echo "done"
echo "instance id: $1"
#2>&1 > /dev/null to suppress the cli output
echo "stopping instance"
aws ec2 stop-instances --instance-ids $1 2>&1 > /dev/null
echo "waiting for instance to stop"
aws ec2 wait instance-stopped --instance-ids $1
echo "starting instance"
aws ec2 start-instances --instance-ids $1 2>&1 > /dev/null
echo "waiting for instance to start"
aws ec2 wait instance-running --instance-ids $1
echo "done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment