Skip to content

Instantly share code, notes, and snippets.

@tsailiming
Last active March 30, 2017 01:23
Show Gist options
  • Save tsailiming/707a7ddd22a58b23d7e2 to your computer and use it in GitHub Desktop.
Save tsailiming/707a7ddd22a58b23d7e2 to your computer and use it in GitHub Desktop.
My sample ruby script to create an EC2 instance
#!/usr/bin/env ruby
# You will need the following enviromnet variables contiang the your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
# $ env AWS_ACCESS_KEY_ID=<ACCESS_ID> AWS_SECRET_ACCESS_KEY=<SECRET_KEY> ruby ec2.rb
# This creates an instance on AWS using the t2.nano and it will perform the following steps:
# 1. *WARNING* It will remove all existing internet gateways, subnets, vpcs and assiocated resources
# 2. Because t2.nano/micro must be created in a VPC, the internet gateway and security group must be configured:
# http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Scenario1.html
# 3. Wait for the instance to be made available
require 'aws-sdk'
# MODIFY THIS!
dry_run = true
# =========================================
Aws.config.update({
region: 'ap-southeast-1'
})
ec2 = Aws::EC2::Resource.new()
# Naive way to check for AWS credentials
begin
ec2.instances().count()
rescue Aws::Errors::MissingCredentialsError
puts "Missing AWS credentials"
exit
end
ec2.vpcs.each do |vpc|
vpc.internet_gateways.each do |gw|
vpc.detach_internet_gateway({internet_gateway_id:gw.id})
end
end
# Delete all gateways
ec2.internet_gateways.map(&:delete)
# Delete all subnets
ec2.subnets.map(&:delete)
# Delete all vpcs
ec2.vpcs.map(&:delete)
# Create a VPC with cidr 192.168.1.0/24
puts "Creating VPC"
begin
vpc = ec2.create_vpc({cidr_block:'192.168.1.0/24'})
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to create VPC. Error: #{error}"
exit
end
vpc.modify_attribute({
enable_dns_hostnames: {
value: true,
},
})
puts "Creating subnet"
begin
subnet = vpc.create_subnet({cidr_block:'192.168.1.0/24'})
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to create Subnet. Error: #{error}"
exit
end
# Allow all
security_group = vpc.security_groups.first()
security_group.authorize_ingress({
ip_protocol: "-1",
from_port: -1,
cidr_ip: "0.0.0.0/0",
})
puts "Creating internet gateway"
begin
gw = ec2.create_internet_gateway()
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to create Internet Gateway. Error: #{error}"
exit
end
begin
vpc.attach_internet_gateway({internet_gateway_id:gw.id})
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to attach Internet Gateway to VPC. Error: #{error}"
exit
end
# Assiocate route with subnet
route_table = ec2.route_tables.first()
begin
route_table.associate_with_subnet({
subnet_id: subnet.id,
})
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to associate subnet with route table. Error: #{error}"
exit
end
# Add route through the internet gateway
begin
route_table.create_route({
destination_cidr_block: "0.0.0.0/0",
gateway_id: gw.id
})
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to create Route. Error: #{error}"
exit
end
# Using Amazon Linux AMI (HVM / 64-bit)
begin
puts "Creating EC2 instance"
instances = ec2.create_instances({dry_run:dry_run, image_id:"ami-c9b572aa", instance_type:"t2.nano",
min_count:1, max_count:1, key_name:"default",
network_interfaces: [
{
subnet_id:subnet.id,
groups:[security_group.id],
device_index: 0,
associate_public_ip_address: true,
private_ip_address: "192.168.1.100"
}
],
})
inst = instances.first()
# Wait until the instance is running using the Ruby waiter.
# http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Client.html#waiter_names-instance_method
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html
# It is not clear to me whether all the previous creations are sync / async.
ec2.client.wait_until(:instance_running, instance_ids:[inst.instance_id]) do |w|
# seconds between each attempt
w.interval = 3
# maximum number of polling attempts before giving up
#w.max_attempts = 240
#w.before_attempt do |n|
# # n - the number of attempts made
#end
w.before_wait do |n, resp|
# # n - the number of attempts made
# # resp -the client response from the previous attempt
puts "Waiting for instance to be running..."
end
end
# Public DNS/IP may not be available yet when instance is running
# I could also wait till :instance-status-ok and it should give me the dns/ip:
# https://gist.github.com/samukasmk/8425826#file-boto_puppet_bootstrap_instances-py-L68
puts "Instance #{inst.instance_id} is ready."
rescue Aws::EC2::Errors::ServiceError => error
puts "Failed to create instance. Error: #{error}"
end
#!/bin/bash
env AWS_ACCESS_KEY_ID=<ACCESS_ID> AWS_SECRET_ACCESS_KEY=<SECRET_KEY> ruby ec2.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment