Shell Script to change Instance Type using AWS CLI

Normally, we use AWS Console to change instance type, say from t2.micro to m4.large, of particular instance which involves:

  1. Stopping the instance
  2. Right click and change the instance type
  3. Start the instance.
    What if this has to be done at a time when you might be asleep or in a meeting, or in a movie theatre. There is no such thing known as “Work From Movie Theatre”.

So I have made a simple shell script which you can schedule it in crontab.

Working of the shell script

This script will:

  • Take 2 arguments, viz., instance ID and instance type
  • Stop the instance
  • Wait for instance to stop, and then change the instance type.
  • Start the instance
    Note: You have to configure AWS CLI with proper permissions in order to run the script.

The script can be copied from below. Don’t forget to modify as per your requirement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/bin/bash

SCRIPT_NAME=$(basename $0)
usage () {
echo '
Usage: '"$SCRIPT_NAME"' "Instance ID" "Instance Type"

E.g.
'"$SCRIPT_NAME"' i-abcd1234 t2.medium

Note:
- Check console if the particular instance type is available to the instance before setting the schedule.
'
}

if [ "$#" -ne 2 ]; then
usage
else
alias aws=''`which aws`' --output text'
shopt -s expand_aliases

# Assigning variables from arguments
INST_ID="$1"
INST_TYPE="$2"

# Stopping Instance
aws ec2 stop-instances --instance-ids "$INST_ID"

# Check if the instance is stopped, then make changes
while true; do
INSTSTATE="$(aws ec2 describe-instances --instance-id "$INST_ID" --query 'Reservations[*].Instances[*].State.Name')"
if [ "$INSTSTATE" == "stopped" ]; then
aws ec2 modify-instance-attribute --instance-id "$INST_ID" --instance-type "$INST_TYPE"
break
fi
sleep 10
done

# Start Instance
aws ec2 start-instances --instance-ids "$INST_ID"

fi

Setting cron

Name the script file name as: changeInstanceType.sh

To set the cron, open crontab console:

1
crontab -l

Add the following line to schedule it for 26th January, 2017 at 10:30 PM (or 2230 hours):

1
30 22 26 01 *   /bin/bash -x /path/to/script/changeInstanceType.sh i-abcd123 t2.medium >> /var/log/changeInstanceType.sh.log

Don’t forget to remove the cron tab, else it will run again, NEXT YEAR !


PS: May be there is a term “Work from Theatre“. (My Colleague :P )

amazon web services aws awscli cloud command linux ubuntu ec2 cron crontab