Two improvements to your Capfiles

I have lately started using a pattern that has become quite common among capistrano users: setting the server names and locations in a task. Doing this allows you to have multiple deployment environments, like development, staging, production, and so on.

desc "deploy to development environment"
task :development do
  set :deploy_to, "/var/apps/#{application}"
  role :web, "", :primary => true
  role :app, "", :primary => true
  role :db, "", :primary => true
  set :user, "username"
  set :password, "secr3t"
  set :remote_mysqldump, "/usr/bin/mysqldump"
  set :db_user, "username"
  set :db_password, "secre7"
  set :db_name, "db_name"

This technique has proven itself to be really useful, especially when clients start to ask for deployments on their test servers, and you still want to be able to deploy to your development servers.

While refactoring my Capfiles I also took the time to rewrite the drupal:db namespace, adding the much needed tasks that allow you dump the remote databases and download them to your development box.

  namespace :db do    
    namespace :dump do
      desc "Deletes old database dumps, leaves only the latest on the server"
      task :cleanup, :roles => :db do
        dumps = capture("ls -xt #{shared_path}/dumps").split.reverse
        run "cd #{shared_path}/dumps; rm #{dumps[0..-2].join(" ")}"
      desc "Dumps the local database"
      task :local, :roles => :db do
        raise"failed dump") unless system "#{local_mysqldump} -u #{local_db_user} --password=#{local_db_password} #{local_db_name} > dump.sql"
      namespace :remote do
        desc "Dumps the remote database"
        task :default, :roles => :db do
          filename = "#{}.dump.sql"
          run "cd #{shared_path}/dumps; #{remote_mysqldump} -u #{db_user} --password=#{db_password} #{db_name} > #{filename}"
          run "cd #{shared_path}/dumps; bzip2 #{filename}"
        namespace :download do
          desc "Dumps and downloads the remote database"
          task :default do
          desc "Downloads the latest database dump"
          task :latest, :roles => :db do
            dumps = capture("ls -xt #{shared_path}/dumps").split.reverse
            get("#{shared_path}/dumps/#{dumps.last}", "./#{dumps.last}")

One Response to “Two improvements to your Capfiles”

  1. Due modi per migliorare i tuoi Capfiles | Unconventional Everything Says:

    [...] I dettagli e il codice li potete trovare a questo indirizzo. [...]