Skip to content

Instantly share code, notes, and snippets.

@Maxoos
Forked from mm53bar/Gemfile
Created January 8, 2016 19:57
Show Gist options
  • Save Maxoos/83bcb5af1c0c8442960e to your computer and use it in GitHub Desktop.
Save Maxoos/83bcb5af1c0c8442960e to your computer and use it in GitHub Desktop.
Automagically launch an EC2 image and then provision it using sunzi
source 'http://rubygems.org'
gem 'sunzi'
gem 'rake'
gem 'fog'
# Create, provision and destroy virtual servers at Amazon EC2
# ===========================================================
begin
require 'fog'
rescue LoadError
puts "[!] Please install the 'fog' gem:", "", " $ gem install fog", ""
exit(1)
end
STDOUT.sync = true
ACCESS_KEY_ID = ENV['AWS_ACCESS_KEY_ID']
SECRET_ACCESS_KEY = ENV['AWS_SECRET_ACCESS_KEY']
unless ACCESS_KEY_ID && SECRET_ACCESS_KEY
puts "[!] Error: Please provide your AWS credentials as environment variables for the script to continue...",
"export AWS_ACCESS_KEY_ID=<Your AWS access key>",
"export AWS_SECRET_ACCESS_KEY=<Your AWS secret access key>"
exit(1)
end
# Create connection to EC2
#
EC2 = Fog::Compute.new provider: 'AWS',
region: 'us-east-1',
aws_access_key_id: ACCESS_KEY_ID,
aws_secret_access_key: SECRET_ACCESS_KEY
task :default => ['ec2:launch', 'ec2:provision']
namespace :ec2 do
desc "Launch and provision new micro instance via the Amazon Elastic Computing service"
task :launch do
print "Launching new server instance at EC2..."
# Create new instance...
s = EC2.servers.bootstrap image_id: 'ami-349b495d',
flavor_id: 't1.micro',
private_key_path: '~/.ssh/id_rsa',
public_key_path: '~/.ssh/id_rsa.pub',
tags: { Name: 'AppDeployment' },
username: 'ubuntu'
puts "", "Started instance '#{s.id}' (#{s.flavor_id}) at #{s.dns_name}", '-'*80
puts s.tags
end
desc "Terminate all servers tagged 'AppDeployment'"
task :terminate do
# Select all instances with the proper tag
#
servers = EC2.servers.select { |s| s.tags["Name"] == "AppDeployment" && s.state == "running" }
if servers.size < 1
puts "No servers running for testing deployment, exiting...", '-'*80
exit
end
puts "Terminating #{servers.size} running servers...", '-'*80
servers.each do |s|
puts "* #{s.id} (#{s.flavor.name})"
s.destroy
end
end
desc "Provision new server with Sunzi"
task :provision do
# Select all instances with the proper tag
#
servers = EC2.servers.select { |s| s.tags["Name"] == "AppDeployment" && s.state == "running" }
exec "time bin/sunzi deploy ubuntu@#{servers.first.dns_name}"
end
desc "SSH to the new server"
task :ssh do
servers = EC2.servers.select { |s| s.tags["Name"] == "AppDeployment" && s.state == "running" }
puts "Connecting to #{servers.first.dns_name}"
exec "ssh ubuntu@#{servers.first.dns_name}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment