Created
March 31, 2014 05:13
-
-
Save arukoh/9885730 to your computer and use it in GitHub Desktop.
稼働中のインスタンスからnorebootでAMIを作成するスクリプト。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "aws-sdk" | |
REGION = ENV['REGION'] | |
ELB_NAME = ENV['ELB_NAME'] | |
IMAGE_NAME_PREFIX = ENV['IMAGE_NAME_PREFIX'] | |
ec2 = AWS::EC2.new(region: REGION) | |
elb = AWS::ELB.new(region: REGION).load_balancers[ELB_NAME] | |
instance = elb.instances.first | |
puts "Create image of #{instance.id}" | |
(puts "No such instance: #{instance.id}"; exit(1)) unless instance.exists? | |
# Create new image | |
image_name = "#{IMAGE_NAME_PREFIX}-#{Time.now.strftime("%Y%m%d%H%M%S")}" | |
image_desc = "Backup image(#{instance.tags['Name']}) at #{DateTime.now}" | |
new_image = instance.create_image(image_name, {description: image_desc, no_reboot: true}) | |
new_image.tags[:Name] = image_name | |
# wait for complete | |
puts "waiting for new image: #{new_image.name}(#{new_image.id})" | |
while true | |
print('.'); sleep 1 | |
break if new_image.state != :pending | |
end | |
puts | |
(puts "create image failed: #{new_image.state_reason}"; exit(1)) if new_image.state == :failure | |
puts "create image successed" | |
# Add snapshot name | |
match = /Created by CreateImage\(#{instance.id}\) for #{new_image.id}/ | |
snapshot = ec2.snapshots.find{|s| s.description =~ match } | |
snapshot.tag("Name", value: image_name) | |
puts "Added 'Name' tag to snapshot: #{snapshot.id}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment