Last active
April 25, 2016 02:59
-
-
Save thomaswitt/8669020 to your computer and use it in GitHub Desktop.
Deploy to opsworks via rake
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks neat. Instead of a yaml file, I would probably standardize on the environment variables AWS uses for all their cli tools.