Managing EC2 Reservations with Ruby

Over the course of past couple of weeks the guys (and gals!) at Amazon have hosted a number of great 'AWS Start-Up' events to evangelize their services and share the stories of some of the startups that have come to fruition based on their platform. I've had a chance to attend the New York event, as well as present in Boston earlier today - kudos to the AWS team for putting together these events, we've met dozens of exciting new startups, entrepreneurs, and a lot of the AWS team itself.Interestingly enough, watching the presentations and even talking to a lot of the developers in the crowd resulted in very similar pain points: server monitoring, management, and automation. Hence, below is a modest contribution (a Ruby script) for terminating an entire reservation of EC2 instances on the fly. Instead of manually specifying each instance id, you can give it a reservation number (r-xxxxxxx) and all the machines will be shut down:

#!/usr/bin/ruby

reservation = ARGV[0]
if reservation.nil?
    puts "No reservation id"
    exit
end

instances = []
collect = false
`ec2-describe-instances`.each_line { |l|
    l = l.chomp.split("\t")
    if l[1] == reservation
        collect = true
        next
    end

    collect = false if collect and l.first == "RESERVATION"

    instances << l[1] if collect
}

puts "Terminating #{instances.size} servers: #{instances.join(' ')}"
`$EC2_HOME/bin/ec2-cmd TerminateInstances #{instances.join(' ')}`

To use this as any regular EC2 management command copy the provided file into your $EC2_HOME directory, and you're all ready to go. A sample use case would be:

ilya@tux:~$ ec2-terminate-reservation r-f707e49e
Terminating 5 servers: i-348d635d i-378d635e i-368d635f i-098d6360 i-088d6361

Ilya Grigorik

Ilya Grigorik is a web performance engineer and developer advocate at Google, where his focus is on making the web fast and driving adoption of performance best practices at Google and beyond.