Skip to content

Instantly share code, notes, and snippets.

@thomaswitt
Last active April 25, 2016 02:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaswitt/8669020 to your computer and use it in GitHub Desktop.
Save thomaswitt/8669020 to your computer and use it in GitHub Desktop.
Deploy to opsworks via rake
# Put this into lib/tasks
require 'rubygems'
require 'bundler'
require 'aws-sdk'
require 'socket'
require 'os'
if Rails.env.development?
namespace :opsworks do
# Authenticate to AWS, region must be us-east-1, it's the only endpoint for OpsWorks right now.
# aws_secrets.yml must contain the keys access_key_id and secret_access_key
AWS.config(YAML.load_file('config/aws_secrets.yml').merge(region: 'us-east-1'))
# config/opsworks.yml looks like:
# layer_id: 'c8acf-xxxxxxxxxxxxxxxx'
# app_id: '7280-xxxxxx'
opsworks = YAML.load_file('config/opsworks.yml')
client = AWS::OpsWorks.new.client
if OS.mac?
whoami = `osascript -e "long user name of (system info)"`.strip
else
whoami = `whoami`.strip
end
hostname = Socket.gethostname
desc 'Deploy this app to AWS Opsworks'
task :deploy do
deploy_opts = {}
deploy_opts[:command] = {name: 'deploy'}
deploy_opts[:instance_ids] = []
deploy_opts[:app_id] = opsworks['app_id']
deploy_opts[:comment] = "rake deploy from #{whoami} on #{hostname}"
instances = client.describe_instances({layer_id: opsworks['layer_id']})
next if instances.nil? || instances.empty?
# Capture the details for each 'online' instance
instances[:instances].each do |instance|
if 'online' == instance[:status]
deploy_opts[:instance_ids] << instance[:instance_id]
deploy_opts[:stack_id] = instance[:stack_id]
end
end
puts "Deploying to #{deploy_opts[:instance_ids].count} instances"
deploy = client.create_deployment deploy_opts
puts "Deployment ID is: #{deploy[:deployment_id]}"
puts "Check status via:"
puts "rake opsworks:deploy_status[#{deploy[:deployment_id]}]"
end
desc 'Deploy this app to AWS Opsworks'
task :deploy_status, [:d_id] do |t, args|
raise '*** Usage: rake opsworks:deploy_status[a2b45-...opsworks_deployment_id]' if args[:d_id].nil?
r = client.describe_deployments(deployment_ids: [args[:d_id]])[:deployments].first
puts "Deployment #{r[:deployment_id]}:"
puts "- Status: #{r[:status]}"
puts "- Created: #{DateTime.parse(r[:created_at])}"
puts "- Completed: #{DateTime.parse(r[:completed_at])}" if r[:completed_at]
puts "- Duration: #{r[:duration]}" if r[:duration]
puts "- Comment: #{r[:comment]}" if r[:comment]
end
end
end
@till
Copy link

till commented Jan 28, 2014

This looks neat. Instead of a yaml file, I would probably standardize on the environment variables AWS uses for all their cli tools.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment