Friday, July 1, 2016

AWS EC2 Start/Stop Scripts using Tagging

So my first version of this just used a list of ec2 ids and stopped and started.  I need it to make it more "cloud like".  So what is more cloud like? Tagging!  I now have it building a list based on an explicit tag, then comparing it to another list that is dynamic based on a tag called shutdown with the value of Exclude.  Anything with the exclude value, I don't want it shut down.  As always, anyone has ways of making this better, post below.

Shutdown
#!/bin/bash

instance_list=$(aws ec2 describe-instances --filters Name=tag-value,Values="Enter-tag-value-here-no-quotes"| cut -f 8 | grep ^i-)

exclude_list=$(aws ec2 describe-instances --filters Name=tag-value,Values="Enter-tag-value-here-no-quotes"| cut -f 8 | grep ^i-)

while IFS= read -r instance_id
do
        echo "Shutting down: $instance_id";
        if [[ ${exclude_list[*]} =~ $instance_id ]]; then
   echo "The instance must stay powered on";
        else
            status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3 | grep 'stopped\|stopping\|running\|pending')

            if [ $status != "stopped" ];
            then
                aws ec2 stop-instances --instance-ids $instance_id
                sleep 10
                status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3 | grep 'stopped\|stopping\|running\|pending')
                echo "The $instance_id is $status";
             fi
        fi
done <<< "$instance_list"


Startup
#!/bin/bash

instance_list=$(aws ec2 describe-instances --filters Name=tag-value,Values="Enter-tag-value-here-no-quotes" | cut -f 8 | grep ^i-)

while IFS= read -r instance_id
do
        status=$(aws ec2 describe-instances --instance-ids $instance_id | cut -f 3 | grep 'stopped\|stopping\|running\|pending')
        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 'stopped\|stopping\|running\|pending')
                echo "The instance $instance_id is $status"

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

ShareThis