rrichards
1/30/2013 - 6:40 PM

manage_snapshots.rb

#!/usr/bin/env ruby

# AWS ec2 requires API calls be made against regional endpoints no longer a global default 
# deletes snapshots greater than 2 weeks old, aside from those used by AMI's 
# creates a label for new snapshots with a reference to the .tags["Name'] of the original volume

require 'rubygems'
require 'aws-sdk'

regions = [
  "ec2.us-east-1.amazonaws.com",
  "ec2.us-west-1.amazonaws.com",
  ] 

DEBUG = false

targetDate = Time.now - (60 * 60 * 24 * 14)

ACCESS_KEY_ID="SCRUBBED"
SECRET_ACCESS_KEY="SCRUBBED"

regions.each do |region|
  puts region if DEBUG
  AWS.config({
    :access_key_id => ACCESS_KEY_ID,
    :secret_access_key => SECRET_ACCESS_KEY,
    :ec2_endpoint => "#{region}",
    :max_retries => 2,
  })
  ec2 = AWS::EC2.new
  delshots = ec2.snapshots.with_owner(:self)
  puts delshots.count if DEBUG
  delcounter = delshots.count
  delshots.each do |snap|
    delcounter-=1 
    puts delcounter if DEBUG
    next if not snap.start_time < targetDate
    next if snap.description =~ /created/i
    begin 
      puts "#{snap.id}\t#{snap.start_time}\t#{snap.description}" if DEBUG
      #snap.delete 
    rescue => e
      puts "opps"
      next
    end
  end

  # create snapshots
  ec2.volumes.each do |vol|
    next if not vol.size > 9
    $attempt = 1
    begin
      puts "#{vol.id}\t#{vol.tags['Name']}\t#{vol.size}\t#{vol.status}" if DEBUG
      vol.create_snapshot("Snapshot of #{vol.tags['Name']}")
    rescue => e
      puts e.backtrace if DEBUG
      next
    end
  end
end