Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cleanup old EBS snapshots
#!/usr/bin/env ruby
#
#
# Cleanup EC2 EBS snapshots.
#
# Originally from: http://www.elastdream.com/2009/04/snapshots.html
#
require 'rubygems'
require 'right_aws'
require 'net/http'
require 'date'
require 'optparse'
$options = {
:key => ENV['AMAZON_ACCESS_KEY_ID'],
:secret => ENV['AMAZON_SECRET_ACCESS_KEY'],
:days => 15,
:minkeep => 5,
:verbose => false
}
optparse = OptionParser.new do|opts|
opts.banner = "Usage: cleanup_snapshots [options] <volume>\n"
# help
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
opts.on('--key KEY', 'Amazon access key') do |key|
$options[:key] = key
end
opts.on('--secret KEY', 'Amazon secret key') do |secret|
$options[:secret] = secret
end
opts.on('--days DAYS', "How many days back to keep (default: #{$options[:days]})") do |days|
$options[:days] = days.to_i
end
opts.on('--min KEEP', "Minimum number of snapshots to keep (default: #{$options[:minkeep]})") do |keep|
$options[:minkeep] = keep.to_i
end
opts.on('--verbose', "Enable verbose output") do
$options[:verbose] = true
end
opts.on('--uri URI', "Use this EC2 URI instead of default (e.g. EU-West)") do |uri|
$options[:uri] = uri
end
end
optparse.parse!
if !$options[:key] || !$options[:secret]
puts "Must set Amazon key and secret"
exit 1
end
if ARGV.length != 1
puts "Usage: cleanup_snapshots [options] <vol-id>"
exit 1
end
ec2_vol = ARGV[0]
if $options[:verbose]
logger = Logger.new(STDOUT)
else
logger = Logger.new(File.open("/dev/null", "w"))
end
params = {
:logger => logger
}
params.merge(:endpoint_url => $options[:uri]) if $options.key?(:uri)
ec2 = RightAws::Ec2.new($options[:key], $options[:secret], params)
sa = ec2.describe_snapshots()
sa.delete_if { |x| x[:aws_volume_id] != ec2_vol }
sa.sort! { |a, b| b[:aws_started_at] <=> a[:aws_started_at] }
while sa.length > $options[:minkeep]
# Pop from the end
s = sa.pop
days_old = Integer((Time.now - Time.parse(s[:aws_started_at].to_s)) / (60*60*24))
if days_old > $options[:days] then
ec2.delete_snapshot(s[:aws_id])
print "snapshot ",s[:aws_id]," ",days_old," days old for vol ",s[:aws_volume_id]," deleted \n" if $options[:verbose]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment