Last active
August 29, 2015 14:05
-
-
Save masaomoc/7dca76fe737f93eecf9f to your computer and use it in GitHub Desktop.
Quick Launch Amazon Linux
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
#!/usr/bin/env ruby | |
# Quickly launch Amazon Linux EC2 instance in Default VPC. | |
# Required to be set the below environment variables | |
# - AWS_DEFAULT_REGION | |
# - AWS_ACCESS_KEY | |
# - AWS_SECRET_KEY | |
# | |
# Usage : ruby launch.rb | |
require 'aws-sdk' | |
# security group id to be attached to the instance | |
secgroup_id = "sg-xxxxxxx" | |
# KeyPair name to be used | |
keypair_name = "keypair" | |
ec2 = AWS::EC2.new | |
image_id = "" | |
AWS.memoize do | |
image_id = ec2.images.with_owner('amazon') | |
.filter("name", "amzn-ami-hvm-*-ebs") | |
.sort{|a, b| b.name <=> a.name } | |
.first.image_id | |
end | |
resp = ec2.instances.create(image_id: image_id, | |
security_group_ids: [secgroup_id], | |
key_pair: ec2.key_pairs[keypair_name], | |
instance_type: "t2.micro", | |
associate_public_ip_address: true) | |
puts "Launched instance : #{resp.id}" | |
puts "waiting for acquiring Public IP Address..." | |
# wait until Public IP Address is assigned to the launched instance. | |
i = 1 | |
while ec2.instances[resp.id].ip_address.nil? | |
if i > 10 | |
raise RuntimeError | |
end | |
sleep 2 ** i | |
i += 1 | |
end | |
puts "Got IP Address. You can connect via 'ssh -i ~/.ssh/#{keypair_name}.pem ec2-user@#{resp.ip_address}' in a few moments." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment