Skip to content

Instantly share code, notes, and snippets.

@gouf
Last active January 3, 2016 10:59
Show Gist options
  • Save gouf/8453265 to your computer and use it in GitHub Desktop.
Save gouf/8453265 to your computer and use it in GitHub Desktop.
AWS EC2 インスタンスをRuby から立ち上げ。SSH キーを用意させるので、立ち上げたあとにそのまま利用できる。
require 'aws-sdk'
require 'pp'
# if not set region, it will set us-east by default
ec2 = AWS::EC2.new(region: 'ap-northeast-1')
# List up key pairs you have
#pp ec2.key_pairs.map(&:name)
# Available Regions
#pp ec2.regions.map(&:name)
=begin
ami_id = "ami-a25415cb" # RHL
ami_id = "ami-10314d79" # Ubuntu
ami_id = "ami-29d54d28" # AMIMOTO Wordpress AMI
=end
ami_id = "ami-0b13700a" # Amazon Linux (amzn-ami-pv-2013.09.2.i386-ebs)
key_pair_name = 'amazon_linux'
# create a key if not exists
key_pair = proc {|key_pair_name|
file_path = File.expand_path("~/.ssh/#{key_pair_name}.pem")
if ec2.key_pairs[key_pair_name].exists? then
puts "key pair is exist."
else
puts "key pair is not exist."
key_pair = ec2.key_pairs.create(key_pair_name)
private_key = key_pair.private_key
File.open(file_path, 'w', 0400) do |f|
f.write private_key
end
end
ec2.key_pairs[key_pair_name]
}.call(key_pair_name)
# Launch Instance
pp instance = ec2.instances.create(
image_id: ami_id.to_s,
instance_type: 't1.micro',
key_pair: key_pair
)#=> <AWS::EC2::Instance id:i-xxxxxxxx>
# Add Tag to launched instance. (eg. key=name, value=ruby-auto-launch)
pp instance.add_tag('name', value: 'ruby-auto-launch') #=> <AWS::EC2::Tag:instance:i-xxxxxxxx:name>
# List up Instances status
pp ec2.instances.inject({}) {|m, i| m[i.id] = i.status; m }
#=>
=begin
{"i-xxxxxxxx"=>:running,
"i-xxxxxxxx"=>:stopped,
"i-xxxxxxxx"=>:running,
"i-xxxxxxxx"=>:terminated,
"i-xxxxxxxx"=>:pending,
"i-xxxxxxxx"=>:terminated,
"i-xxxxxxxx"=>:stopped}
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment