Skip to content

Instantly share code, notes, and snippets.

@oelbrenner
Created July 18, 2012 19:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oelbrenner/3138282 to your computer and use it in GitHub Desktop.
Save oelbrenner/3138282 to your computer and use it in GitHub Desktop.
Snapshot and manage AWS EBS volumes
require 'fog'
puts "Starting.."
today = Time.now.strftime("%Y%m%d")
puts "Today is #{today}"
@fog = Fog::Compute.new(:provider => 'AWS', :aws_access_key_id => 'YOUR_ACCESS_KEY', :aws_secret_access_key => 'YOUR_SEKRET_ACCESS_KEY')
volumes = @fog.volumes.all
volumes.each do |vol|
puts "---------------------------------"
puts "volume not attached to running instance.. skipping this volume" if vol.server_id.nil?
next if vol.server_id.nil?
puts "Creating snapshot for volume #{vol.id}"
snapshot = @fog.snapshots.new
snapshot.description = "Daily Snapshot - created: #{Time.now.strftime(" %m/%d/%Y")} "
snapshot.volume_id = vol.id
puts "Saving snapshot for volume #{vol.id}"
snapshot.save
puts "Reloading snapshot to get ID"
snapshot.reload
puts "Snapshot ID = #{snapshot.id}"
puts "Tagging snapshot #{snapshot.id} for volume #{vol.id}"
@fog.tags.create(:resource_id => snapshot.id, :key => "SnapshotDate", :value => today)
@fog.tags.create(:resource_id => snapshot.id, :key => "SnapshotType", :value => 'daily')
end
puts "Fetching tags for daily snapshots"
tags = @fog.tags.all(:key => "SnapshotType", :value => "daily")
days_to_keep = 8
tags.each do |tag|
snapshot = @fog.snapshots.get(tag.resource_id)
puts "Checking snapshot: #{snapshot.id}"
snapshot_age = today.to_i - snapshot.created_at.strftime("%Y%m%d").to_i
if snapshot_age > days_to_keep
puts "snapshot #{snapshot.id} is older then #{days_to_keep} days, deleting"
@fog.delete_snapshot(snapshot.id)
puts "Complete."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment