Thursday, June 30, 2016

AWS EC2 Startup/Shutdown Scripts

Couple assumptions:

1.  You've already installed the aws cli
2.  You've already run aws configure
3.  You are running this from an instance that never gets shutdown

Shutdown

#!/bin/bash

instance_list="instance1
instance2"

while IFS= read -r instance_id
do
        status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3 | grep stopped)
        echo "The instance $instance_id is $status"

        while [ "$status" != 'stopped' ];
        do
                aws ec2 stop-instances --instance-ids $instance_id
                sleep 10
                status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3| grep stopped)
                echo "The instance $instance_id is $status"

                if [ "$status" == 'stopped' ]; then
                        echo "The $instance_id is $status"
                        break
                fi
        done
done <<< "$instance_list"

Startup

#!/bin/bash

instance_list="instance1
instance2"

while IFS= read -r instance_id
do
        status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3 | grep running)
        echo "The instance $instance_id is $status"

        while [ "$status" != 'running' ];
        do
                aws ec2 start-instances --instance-ids $instance_id
                sleep 10
                status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3| grep running)
                echo "The instance $instance_id is $status"

                if [ "$status" == 'running' ]; then
                        echo "The $instance_id is $status"
                        break
                fi
        done
done <<< "$instance_list"


Right now this is doing it based on the list you write.  I did out that if you could grab all instances like this:

instance_list=$(aws ec2 describe-instances | cut -f 8 | grep ^i-)

The problem is that your shutting down the box with the scripts.  Plus I do have a couple of servers I don't want to go down.  Good enough for now but I need to add a way to exclude instances and also save EIPs so I can reattach the same EIP when I bring it back up.  If you know how to do it, please feel free to improve this in the comments!

No comments:

Post a Comment

ShareThis