This is a Nuts & Bolts Article – Tips & Tricks for Developers

Run a remote Rails production console with Capistrano

by Torsten Bühl

We all love to enter the Rails console to try out some stuff. It's just a rails c away in development. But what if you want to view or fetch some specific data on your remote production server (and you're not on Heroku)? If you already deploy your app with Capistrano, why not use it for this task?

There are a lot of different snippets out there. Some try to pass input and output through Capistrano which doesn't work well. Thankfully I found snippets with a different approach: Just use ssh's -t flag. Here you can see the code that eventually worked for me.

# Tested with Capistrano 2
namespace :rails do
  desc "Remote console"
  task :console, roles: :app do
    run_interactively "bundle exec rails console #{rails_env}"

def run_interactively(command, server=nil)
  server ||= find_servers_for_task(current_task).first
  exec %Q(ssh -l #{user} #{server} -t 'su - #{user} -c "cd #{current_path} && #{command}"')

This is a combined version of the solutions showed in this gist. It uses the user specified as :user to open the ssh connection instead of your logged in system user. Additionally, it uses su - #{user} to load the users profile and environment variables – e.g if you set things like RVM in the .bashrc or .profile files.

Now just run cap rails:console and you're fine.

Did this work for you or do you use another approach? Just ping me at @tbuehl

This is a Nuts & Bolts Series post – join the mailing list below to get more tips & tricks.

← Back to Overview

Try our simple and powerful
application error tracking