Skip to content

Instantly share code, notes, and snippets.

@morimori
Created April 8, 2013 06:13
Show Gist options
  • Save morimori/5334602 to your computer and use it in GitHub Desktop.
Save morimori/5334602 to your computer and use it in GitHub Desktop.
実行中のインスタンスにアタッチされている EBS ボリュームのスナップショットを取って、古いスナップショットを削除する
ACCESS_KEY = 'YOUR ACCESS KEY'
SECRET_KEY = 'YOUR SECRET KEY'
MAX_SNAPSHOTS = 5
require 'rubygems'
require 'aws-sdk'
require 'json'
require 'open-uri'
config = JSON.parse open('http://169.254.169.254/latest/dynamic/instance-identity/document').read
AWS.config access_key_id: ACCESS_KEY, secret_access_key: SECRET_KEY
ec2 = AWS::EC2.new
ec2 = AWS::EC2.new :ec2_endpoint => ec2.regions[config['region']].endpoint
volumes = ec2.volumes.filter('attachment.instance-id', config['instanceId'])
volumes.each do |vol|
device = vol.attachments.first.device
vol.create_snapshot("[#{config['instanceId']}:#{device}] #{Time.now.utc.iso8601} snapshot")
ec2.snapshots.with_owner('self').filter('volume-id', vol.id).filter('status', 'completed').to_a.sort{ |a, b| b.start_time <=> a.start_time }[MAX_SNAPSHOTS..-1].each do |ss|
ss.delete
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment