Skip to content

Instantly share code, notes, and snippets.

@stympy
Created July 24, 2009 20:59
Show Gist options
  • Save stympy/154552 to your computer and use it in GitHub Desktop.
Save stympy/154552 to your computer and use it in GitHub Desktop.
Script for running an ec2 instance based off a custom AMI, attaching an EBS volume, then associating an EIP
#!/usr/bin/env ruby
require 'rubygems'
require 'right_aws'
require 'net/ssh'
require 'open-uri'
# Git rid of ssl verification warning
class Net::HTTP
alias_method :old_initialize, :initialize
def initialize(*args)
old_initialize(*args)
@ssl_context = OpenSSL::SSL::SSLContext.new
@ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
AWS_ACCESS_KEY_ID="access key here"
AWS_SECRET_ACCESS_KEY="secret access key here"
@ec2 = RightAws::Ec2.new(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
@image = @ec2.describe_images_by_owner.detect {|i| i[:aws_location] == 'bucketname/imagename.manifest.xml' }
@volume = @ec2.describe_volumes.first
@instance = @ec2.launch_instances(@image[:aws_id], :key_name => 'your-ssh-key-name', :availability_zone => @volume[:zone]).first
sleep(2) until (@instance = @ec2.describe_instances(@instance[:aws_instance_id]).first)[:aws_state] == 'running'
puts "Attaching volume..."
@ec2.attach_volume(@volume[:aws_id], @instance[:aws_instance_id], '/dev/sdh')
sleep(2) until @ec2.describe_volumes.detect {|v| v[:aws_id] = @volume[:aws_id] }[:aws_attachment_status] == 'attached'
# These commented lines open and close firewall access to the instance from the current IP
# ip = open('http://checkip.dyndns.org').read.match(/(\d+\.?)+/)[0]
# @ec2.authorize_security_group_IP_ingress('default', 22, 22, 'tcp', "#{ip}/32")
sleep(2) # Sleep a bit more to give sshd a chance to wake up
Net::SSH.start(@instance[:dns_name], 'root', :keys => [File.join(File.dirname(__FILE__), 'id_rsa-your-ssh-key-name')]) do |ssh|
ssh.exec!("mount /srv")
ssh.exec("/etc/init.d/postgresql-8.3 start")
end
# @ec2.revoke_security_group_IP_ingress('default', 22, 22, 'tcp', "#{ip}/32")
puts "Assocating IP..."
@address = @ec2.describe_addresses.first
@ec2.associate_address(@instance[:aws_instance_id], @address[:public_ip])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment