- AMI create example
$ bundle exec ruby test.rb -r ap-northeast-1 create -i i-ea4d02e8 -n test -d test
- AMI delete example
$ bundle exec ruby test.rb -r ap-northeast-1 delete -a ami-779f0e76
require 'trollop' | |
require 'aws-sdk' | |
module AMIManagerUtil | |
def self.snapshot_ids(image, options = {}) | |
options = {:retry_count => 30, :retry_time => 5}.merge(options) | |
device_map = image.block_device_mappings | |
count = 0 | |
while device_map.to_hash.empty? | |
sleep options[:retry_time] | |
device_map = image.block_device_mappings | |
count += 1 | |
raise "failed to get ami snapshot" if count >= options[:retry_count] | |
end | |
snapshots = [] | |
device_map.each do |device| | |
snapshots << device_map[device].snapshot_id | |
end | |
return snapshots | |
end | |
end | |
SUB_COMMANDS = %w(create delete) | |
global_opts = Trollop::options do | |
banner "AMI management tool. subcommand[#{SUB_COMMANDS.join(" ")}]" | |
opt :aws_access_key, "aws access key", :type => String | |
opt :aws_secret_key, "aws secret", :type => String | |
opt :region, "EC2 region", | |
:type => String, | |
:default => "us-east-1" | |
stop_on SUB_COMMANDS | |
end | |
cmd = ARGV.shift | |
cmd_opts = case cmd | |
when "create" | |
Trollop::options do | |
opt :instance_id, "target ec2 instance id", | |
:type => String, | |
:required => true | |
opt :name, "AMI name", | |
:type => String, | |
:required => true | |
opt :description, "AMI description", | |
:type => String, | |
:required => true | |
end | |
when "delete" | |
Trollop::options do | |
opt :ami_id, "target AMI id", | |
:type => String, | |
:required => true | |
end | |
else | |
Trollop::die "unknown subcommnad #{cmd.inspect}" | |
end | |
ec2 = AWS::EC2.new(:proxy_uri => ENV['HTTP_PROXY'] || ENV['http_proxy'], | |
:region => global_opts[:region], | |
:access_key_id => global_opts[:aws_access_key], | |
:secret_access_key => global_opts[:aws_secret_key]) | |
case cmd | |
when "create" | |
image = ec2.images.create(:name => cmd_opts[:name], | |
:instance_id => cmd_opts[:instance_id], | |
:description => cmd_opts[:description]) | |
image.tag('Name', :value => cmd_opts[:name]) | |
snapshots = AMIManagerUtil.snapshot_ids(image) | |
snapshots.each do |snapshot_id| | |
ec2.snapshots[snapshot_id].tag('Name', :value => cmd_opts[:name]) | |
end | |
when "delete" | |
image = ec2.images[cmd_opts[:ami_id]] | |
snapshots = AMIManagerUtil.snapshot_ids(image) | |
image.deregister | |
snapshots.each do |snapshot_id| | |
ec2.snapshots[snapshot_id].delete | |
end | |
end |
# A sample Gemfile | |
source "http://rubygems.org" | |
gem "trollop" | |
gem "aws-sdk" |