Skip to content

Instantly share code, notes, and snippets.

@troystribling
Created December 30, 2011 16:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save troystribling/1540598 to your computer and use it in GitHub Desktop.
Save troystribling/1540598 to your computer and use it in GitHub Desktop.
Take snaps of EBS volumes with Fog
#!/usr/bin/env ruby
require 'rubygems'
require 'fog'
config = YAML.load(File.read(ARGV[0]))
volumes_to_snap = YAML.load(File.read(ARGV[1]))
time = Time.now
puts "\nCreating snaps #{time.to_s}"
puts "Configuration: #{ARGV[0]}\n#{config.inspect}"
puts "Volumes to Snap: #{ARGV[1]}\n#{volumes_to_snap.inspect}"
aws = Fog::Compute.new(
:provider => 'AWS',
:region => config['region'],
:aws_access_key_id => config['aws_access_key_id'],
:aws_secret_access_key => config['aws_secret_access_key']
)
volumes_to_snap.each do |data|
time_stamp = Time.now.strftime("%Y-%m-%d:%H:%M")
puts "Snapping: #{data[:host]} at #{time_stamp}"
date = Time.now.strftime("%Y-%m-%d")
snapshot = aws.snapshots.new
snapshot.description = "#{data['host']}:#{data['type']}:#{time_stamp}"
snapshot.volume_id = data['volume_id']
snapshot.save
snapshot.reload
aws.tags.create(:resource_id => snapshot.id, :key => "SnapshotLifetime", :value => data['lifetime'])
aws.tags.create(:resource_id => snapshot.id, :key => "SnapshotHost", :value => data['host'])
aws.tags.create(:resource_id => snapshot.id, :key => "SnapshotType", :value => data['type'])
aws.tags.create(:resource_id => snapshot.id, :key => "SnapshotPersistence", :value => 'delete')
aws.tags.create(:resource_id => snapshot.id, :key => "Name", :value => "#{data['host']}:#{data['type']}:#{date}")
end
puts "Delete snaps #{time.to_s}"
persistence_tags = aws.tags.all(:key => 'SnapshotPersistence', :value => 'delete')
persistence_tags.each do |tag|
snapshot = aws.snapshots.get(tag.resource_id)
snapshot_tags = snapshot.tags
puts "Checking snapshot #{snapshot.description}"
lifetime = snapshot_tags['SnapshotLifetime'].to_i
type = snapshot_tags['SnapshotType']
age = if type.eql?('daily')
(time - snapshot.created_at)/(86400.0)
elsif type.eql?('hourly')
(time - snapshot.created_at)/(3600.0)
end
puts " #{type} lifetime: #{lifetime}"
puts " Age: #{age.to_i}"
if age > lifetime.to_i
puts " Deleting"
aws.delete_snapshot(snapshot.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment