Skip to content

Instantly share code, notes, and snippets.

@toamitkumar
Created April 5, 2012 03:38
Show Gist options
  • Save toamitkumar/2307763 to your computer and use it in GitHub Desktop.
Save toamitkumar/2307763 to your computer and use it in GitHub Desktop.
Capistrano Extension

What is Capistrano?

Tool to deploy code to remote machine(s) from SCM.
It helps manage deployments and rollbacks

How does it work?

Deployment recipe for Rails apps
Directory structure

/test
|- shared
|- releases
|- current
|- pids
|- logs

Password-less deployments

Why was extension required?

Caches the password for the session
Assumes the same password will be applied to all remote servers
What if you have another server and you want to automate all in a single command
Asset Server

Extension

How does extension work?

Pass additional server settings from your Capfile
role :asset, "remote.sever.name", :user => "server_user"
set :server_auth, '[email protected]'
Alias the connect method
alias :original_connect :connect
Check for additional server settings
add_server_settings = options[:server_auth] ? options[:server_auth] =~ /#{server.to_s}/ : nil
Nuke the old password, capistrano forces to enter the password
password_value = nil
begin
  connection_options = ssh_options.merge(:password => password_value, :auth_methods => ssh_options[:auth_methods] || methods.shift)
  connection = Net::SSH.start(server.host, server.user, connection_options, &block)
  Server.apply_to(connection, server)
end
Use the after deploy hook to invoke the asset server deployment task
after "deploy:restart", "deploy:minify_and_upload_assets"
The deployment hook

task :minify_and_upload_assets, :roles => :asset do
   if(minify_assets)
     started_at = Time.now
     server_temp_copy = "#{assets_path}-#{Time.now.strftime('%Y%m%d%H%M%S')}"
     local_temp_copy = "./public/minified/#{server_temp_copy}"
     begin
       system "svn export --revision #{revision} #{asset_repository} #{local_temp_copy} --force"
       # minify the assets
       top.upload(local_temp_copy, "#{asset_server_root}", :via => :scp, :recursive => true) do |channel, name, sent, total|
         print "."
       end
     rescue => e
       puts e.message
     ensure
       FileUtils.rm_rf(local_temp_copy)
       puts "Completed deployment to asset servers in #{(Time.now - started_at)}"
     end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment