Development

Starting a Remote Rails Console With Capistrano

By August 19, 2014 No Comments

For developers that deploy Rails with Capistrano, here are a few tasks to quickly open an interactive rails console or rails dbconsole on a remote server.

If you’re like me, you’ll occasionally want to open a console to run a quick query, set an admin flag on a user or just verify that a migration worked correctly. This usually means finding the right ssh credentials to log into the remote server, finding the deploy directory on the server, typing in the command wrapped in bundle exec, and then staring at an error before realizing you forgot to specify the Rails environment. Luckily, your Capistrano deploy.rb probably has all the information it needs to start a console for you.

Without further ado, if you’d like to give it a try, add the version-appropriate snippet from below to your deploy.rb file and run cap [stage] rails:console or cap [stage] rails:dbconsole.

Capistrano 2

namespace :rails do
  desc "Remote console"
  task :console, :roles => :app do |server|
    run_interactively "bundle exec rails console #{rails_env}"
  end

  desc "Remote dbconsole"
  task :dbconsole, :roles => :app do |server|
    run_interactively "bundle exec rails dbconsole #{rails_env}"
  end

  def run_interactively(command)
    server ||= find_servers_for_task(current_task).first
    puts "    running `#{command}` as #{user}@#{server}"
    exec %Q(ssh #{user}@#{server} -t "bash --login -c 'cd #{deploy_to}/current && #{command}'")
  end
end

Capistrano 3

namespace :rails do
  desc "Remote console"
  task :console do
    on roles(:app) do |h|
      run_interactively "bundle exec rails console #{fetch(:rails_env)}", h.user
    end
  end

  desc "Remote dbconsole"
  task :dbconsole do
    on roles(:app) do |h|
      run_interactively "bundle exec rails dbconsole #{fetch(:rails_env)}", h.user
    end
  end

  def run_interactively(command, user)
    info "Running `#{command}` as #{user}@#{host}"
    exec %Q(ssh #{user}@#{host} -t "bash --login -c 'cd #{fetch(:deploy_to)}/current && #{command}'")
  end
end

Much credit goes to this StackOverflow question. I’ve borrowed from the answers there and made a few modifications to ensure that RVM/Rbenv is loaded first. If you run into any issues or have any improvements, let us know in the comments below.

Web Application Startup Guide

A 30-page ebook that covers positioning, marketing, pricing, and building your startup product, plus more.