Last active
August 29, 2015 14:08
-
-
Save masaomoc/cbf77812dd8dac63a92c to your computer and use it in GitHub Desktop.
Launch AmonLinux from cli and terminate automatically
This file contains hidden or 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. | |
# Launched EC2 automatically terminates itself after 1 day. | |
# Required to be set the below environment variables | |
# - AWS_DEFAULT_REGION | |
# - AWS_ACCESS_KEY | |
# - AWS_SECRET_KEY | |
# | |
# Usage : ruby launch.rb | |
require 'aws-sdk-v1' | |
# security group id to be attached to the instance | |
secgroup_id = "sg-xxxxxxxx" | |
# KeyPair name to be used | |
keypair_name = "keypair" | |
# force terminate after minutes(default: 1 day) | |
stop_after = 60 * 24 | |
userdata =<<EOF | |
#!/bin/sh | |
# stop after a day | |
echo "shutdown -h now" | at now + #{stop_after}minutes | |
EOF | |
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], | |
user_data: userdata, | |
instance_initiated_shutdown_behavior: "terminate", | |
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