Skip to content

Instantly share code, notes, and snippets.

Created April 25, 2013 19:18
Show Gist options
  • Save anonymous/521b106c3eeef7994ae1 to your computer and use it in GitHub Desktop.
Save anonymous/521b106c3eeef7994ae1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'aws-sdk'
require 'terminal-table/import'
require 'trollop'
opts = Trollop::options do
opt :days_old, "number of days old to keep", :type => Integer, :default => 15
opt :verbose, "enable verbose output", :default => false
opt :dry_run, "Let's have a look at what you could have won", :default => false
end
AWS.config(
:access_key_id => ENV["AWS_ACCESS_KEY"],
:secret_access_key => ENV["AWS_SECRET_ACCESS_KEY"],
)
def all_regions
ec2 = AWS::EC2.new
ec2.regions.map {|r| Thread.new { yield r } }.each(&:join)
end
time = Time.now.utc
results = []
deleted = []
all_regions do |region|
region.volumes.each do |volume|
begin
uptime = ( time - volume.create_time).div(60*60*24)
volume_stats = [ volume.availability_zone_name, volume.create_time, volume.tags['Name'], volume.id, "#{volume.size} GB", volume.snapshot_id, volume.status ]
if volume.status == :in_use
results << volume_stats + [ volume.attachments.first.instance.id, volume.attachments.first.device ]
else
results << volume_stats
end
if volume.snapshot_id
results << volume.snapshot.description
end
if uptime >= opts[:days_old] && volume.status == :available && volume.tags['prune_me']
volume.delete unless opts[:dry_run]
deleted << volume.id
end
rescue AWS::EC2::Errors::InvalidVolume::NotFound
puts "Apparently volume #{volume.id} no longer exists. Skipping" if opts[:verbose]
rescue AWS::EC2::Errors::InvalidSnapshot::NotFound
puts "The snapshot #{volume.snapshot_id} that volume #{volume.id} was created from no longer exists."
end
end
end
if opts[:verbose]
if results.empty?
puts "WTF?! No volumes found ..."
else
puts table([ 'Zone', 'Created', 'Volume Name', 'Volume ID', 'Size', 'Snapshot', 'Status', 'Instance', 'Device' , 'Snapshot Description' ],
*results.sort)
unless deleted.empty?
puts "#{'Dry run ..... would have' if opts[:dry_run]} deleted Volumes: #{deleted.join(',')}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment