Simple script for creating snapshots of an EBS volume and keeping a certain number of those
#!/usr/local/bin/ruby | |
require 'AWS' | |
require 'yaml' | |
class SnapshotManagement | |
# initalize class, optional override path to yml file | |
# * options [String] :path ('') | |
# | |
def initialize(params = {}) | |
path = params[:path] || File.join(RAILS_ROOT,'config','s3.yml' ) | |
s3 = YAML.load_file(path) | |
@access_key_id = s3['access_key_id'] | |
@secret_access_key = s3['secret_access_key'] | |
@ec2 = AWS::EC2::Base.new(:access_key_id => @access_key_id, :secret_access_key => @secret_access_key) | |
end | |
# | |
# The CreateSnapshot operation creates a snapshot of an Amazon EBS volume and stores it in Amazon S3. You can use snapshots for backups, to launch instances from identical snapshots, and to save data before shutting down an instance. | |
# | |
# * options [String] :volume_id ('') | |
# * options [optional,String] :description ('') Description of the Amazon EBS snapshot. | |
# | |
def create_snapshot(params) | |
@ec2.create_snapshot(:volume_id =>params[:volume_id], :description => params[:description] ) | |
end | |
# Clean up snapshots of volume, keep specific number of snapshots | |
# | |
# * options [String] :volume_id ('') | |
# * options [Integer] :keep_num (10) Number of snapshots to retain, defaults to 10. | |
# * options [Integer] :owner Id of owner of snapshots | |
# | |
def cleanup_snapshots(params) | |
keep_num = params["keep_num"] || 10 | |
snapshots = @ec2.describe_snapshots(:owner => params[:owner])['snapshotSet']['item'] | |
entries = snapshots.select {|s| s['volumeId'] == params[:volume_id]} | |
remove = entries.size-keep_num-1 | |
entries[0..remove].each do |entry| | |
#puts entry | |
response = @ec2.delete_snapshot( :snapshot_id => entry['snapshotId']) | |
successful = response['return'] | |
puts "Deleting snapshot '#{entry['description']}' of volume #{entry['volumeId']}, Successful? #{successful}" | |
end unless remove < 0 | |
end | |
end | |
volume_id = VOLUME_ID | |
owner = OWNER | |
config_path = PATH | |
desc = DESCRIPTION | |
time_str = Time.now.strftime('%Y-%m-%d_%H:%M') | |
s = SnapshotManagement.new(:path => config_path) | |
s.create_snapshot(:volume_id => volume_id, :description => "#{desc} - #{time_str}") | |
s.cleanup_snapshots(:volume_id => volume_id, :owner => owner) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment