Programmatically Modifying EC2 Instances with AWS-SDK Gem

You often change the size of cloud VMs based on need, and that is often a crap shoot.  You frequently know when you may need more power, but you are often not certain.  On the other hand, it’s very often the case that you know definitively that you don’t need a ton of power.  For example, we have a lot of production business app sites where we know we don’t need a ton of power from 6pm to 8am.  The apps have to be up, but most users have gone home and at most, a few late workers may access the site.  In situations like this, you can save a ton of money by automating the upscale and downscale of EC2 instances.

Note: you’ll have about 1-3 minutes of downtime, depending on how much time your app needs to spin up.

Amazon provides the AWS-SDK in a number of languages, we’ll be using the Ruby version.  Simply install the gem to get started.

gem 'aws-sdk'

First, configure the credentials (you’ll have to make an AWS user with programmatic access, instructions here):

Aws.config.update({
credentials: Aws::Credentials.new('your access key', 'your secret')
})

(reminder, don’t store your credentials in code, please).

Next, initialize an EC2 “resource” in the sdk:

# note this is on a per-region basis
ec2 = Aws::EC2::Resource.new(region: 'us-east-1');

Now, find your instance:

instance = ec2.instances.select{|x| x.id == "your instance id"}.first

Stop it:

instance.stop

Now, you’ll have to keep refreshing the instance to get it’s latest state, here we’ll keep checking until it’s stopped:

while instance.state.code != 80
    sleep 1
    print "."
    STDOUT.flush
    instance = ec2.instances.select{|x| x.id == "your instance id"}.first
end

Now, shrink it:

instance.modify_attribute(attribute:"instanceType",value: "t2.small")

And start it:

instance.start

That’s it.  So now, you can script this so that every week day, say at 6pm, you can shrink the servers, and restore them every week morning at, say 8am.  And on the weekends, bring them down on Friday evening, and bring them back up on Monday morning.

Hope that saves you some expense on your next AWS bill, please share any other tricks in the comments!

Leave a Reply