Skip to content

Instantly share code, notes, and snippets.

@mmiranda
Last active October 10, 2017 20:35
Show Gist options
  • Save mmiranda/98d2bc6124d9260bd4abf27c84c7823b to your computer and use it in GitHub Desktop.
Save mmiranda/98d2bc6124d9260bd4abf27c84c7823b to your computer and use it in GitHub Desktop.
This snippet creates an instance on AWS EC2.
# How to execute:
# 1. Make sure you have optparse and aws-sdk gem installed
# 2. Run: ruby aws-launch-instance.rb -a YOUR-ACCESS_KEY -s YOUR-SECRET-KEY -r eu-central-1 -t t2.micro
require 'optparse'
require 'aws-sdk'
# Collect parameters
options = {}
optparse = OptionParser.new do |opts|
opts.on('-a', '--aws-access-key INSTANCE-REGION', "Your AWS Access Key") do |option|
options["aws-access-key"] = option
end
opts.on('-s', '--aws-secret-key INSTANCE-REGION', "Your AWS Secret Key") do |option|
options["aws-secret-key"] = option
end
opts.on('-r', '--instance-region INSTANCE-REGION', "Region where Instance should be launched") do |option|
options["instance-region"] = option
end
opts.on('-t', '--instance-type INSTANCE-TYPE', "Instance Type") do |option|
options["instance-type"] = option
end
end
optparse.parse!
if options["aws-access-key"].nil? or options["aws-secret-key"].nil? or options["instance-region"].nil? or options["instance-type"].nil?
puts optparse
exit
end
access_key = options["aws-access-key"]
secret_key = options["aws-secret-key"]
instance_type = options["instance-type"]
instance_region = options["instance-region"]
# Setting credentials - Usually I'd put this on ~/.aws/credentials file, or set env vars through EXPORT for security reasons,
# but I kept it here because as asked before
Aws.config.update({
credentials: Aws::Credentials.new("#{access_key}", "#{secret_key}")
})
# Sets the region
ec2 = Aws::EC2::Resource.new(region: "#{instance_region}")
puts "Creating your instance, please wait..."
# Finally creates the instance
launched_instance = ec2.create_instances({
image_id: 'ami-82be18ed', # AMI Linux
min_count: 1,
max_count: 1,
instance_type: "#{instance_type}"
})
# Wait for the instance to be created
ec2.client.wait_until(:instance_status_ok, {instance_ids: [launched_instance[0].instance_id]})
# Return STDOUT
puts "Your new Instance has the Id " << launched_instance[0].instance_id << " and was launched at " << launched_instance[0].launch_time.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment