Software Developer & Founder Torsten Bühl

Hi, I'm Torsten Bühl. I'm the founder of Foodlane, Company Signal, and Exceptiontrap (acquired by Scout APM). I build simple and straightforward products to help businesses do a better job. Learn more about them here

Run a remote Rails production console with Capistrano

01 May 2014 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}"
  end
end

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}"')
end

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.

Any feedback? Just ping me at @tbuehl.