Did I remember to shut down my EC2 instance?

A small trick that will save you money

I have to admit that I tend to forget my EC2 instances running.
Thats just a waste of money that a simple automation can solve.

Sometimes I launch a new instance to check a feature, work on it for a few hours and then forget its there.

I wrote a small script that checks my running instance count and alerts me when needed. Some parts are specific to OSX, but you can easily change it.

You will need:

  1. Install the boto python library:
    sudo pip install -u boto
  2. Install the terminal notifier:
    sudo gem install terminal-notifier
  3. Grab your AWS Key and the Secret Access Key from the “Security Credentials” page on the AWS console.

Now that we have everything in place, create this python script, filling in your AWS key and secret:

import boto
import commands

# running instances threshold
limit = 4

conn = boto.connect_ec2('KEY','SECRET_KEY')
instances = conn.get_all_instance_status()
if (len(instances) > limit):
      commands.getstatusoutput('terminal-notifier -message "Too many running instances: '+str(len(instances))+'" -title "Ec2 Alert"')

The last thing you need to do is add a scheduled task that will run it every day at 08:00.

Edit the scheduled tasks:

crontab -e

Add the following line with your own path:

0 08 * * * /usr/bin/python /Users/youruser/scripts/awsalert/awsalert.py > /dev/null

You can also get this code on gist: https://gist.github.com/4118268

Drop me an email if you need any help setting it up.

, ,

Powered by WordPress. Designed by Woo Themes