Rails remote production console with Capistrano

Sometimes, when I deploy my rails app to the production server, I need to fire up a console to make a few tweaks. The latest in line: a new migration added the notion of administrator users, but defaulted all existing users to be non-admin. I needed to intervene manually from the console to set my user to be an administrator.

Capistrano’s default Rails tasks doesn’t provide a remote console task, so I borrowed and adapted DZone’s snippet and placed the following in my config/deploy.rb:

desc "Remote console on the production appserver"
task :console, :roles => :app do
  input = ''
  run "cd #{current_path} && ./script/console production" do
    |channel, stream, data|
    next if data.chomp == input.chomp || data.chomp == ''
    print data
    channel.send_data(input = $stdin.gets) if data =~ /^(>|\?)>/
  end
end

This of course only works nicely if you have a single appserver, otherwise you may get a little repetition!

$ cap console
  * executing `console'
  * executing "cd /srv/www/app/current && ./script/console production"
    servers: ["atlas"]
    [atlas] executing command
>> u = User.find(1)
=> #<User ... login: "dave", ...>
>> u.is_admin = true
=> true
>> u.save
=> true
>> exit
    command finished
$

Capistrano wins.