Skip to content

Instantly share code, notes, and snippets.

@benedikt
Created July 30, 2011 13:16
Show Gist options
  • Save benedikt/1115513 to your computer and use it in GitHub Desktop.
Save benedikt/1115513 to your computer and use it in GitHub Desktop.
Capistrano task to open a rails console on a remote server. Require this file in your deploy.rb and run "cap rails:console"
# encoding: UTF-8
Capistrano::Configuration.instance(:must_exist).load do
namespace :rails do
desc "Open the rails console on one of the remote servers"
task :console, :roles => :app do
hostname = find_servers_for_task(current_task).first
exec "ssh -l #{user} #{hostname} -t 'source ~/.profile && #{current_path}/script/rails c #{rails_env}'"
end
end
end
@mariozaizar
Copy link

Had to change it a bit (rails 3.2 + rvm)

namespace :rails do
  desc "Open the rails console on one of the remote servers"
  task :console, :roles => :app do
    hostname = find_servers_for_task(current_task).first
    exec "ssh -l #{user} #{hostname} -t 'source \"$HOME/.rvm/scripts/rvm\" && cd #{current_path}; bundle exec rails console #{rails_env}'"
  end

  desc "Open the rails dbconsole on one of the remote servers"
  task :dbconsole, :roles => :app do
    hostname = find_servers_for_task(current_task).first
    exec "ssh -l #{user} #{hostname} -t 'source \"$HOME/.rvm/scripts/rvm\" && cd #{current_path}; bundle exec rails dbconsole #{rails_env}'"
  end

  # Short aliases
  task :c, :roles => :app do
    console
  end

  task :dbc, :roles => :app do
    dbconsole
  end
end

@chase439
Copy link

chase439 commented Sep 26, 2019

Similar to @colszowka, I have to switch to the app user after connecting via SSH

Capistrano::Configuration.instance(:must_exist).load do
  namespace :rails do
    desc "Open the rails console on one of the remote servers"
    task :console, :roles => :app do
      server ||= find_servers_for_task(current_task).first
      exec %Q[ssh #{server.host} -t 'sudo -u #{user} -- sh -c "source ~/.profile > /dev/null; cd #{release_path}; bin/rails console"']
    end
  end
end

The idea is to run the command as a different user without typing in a password when policy prohibits sudo su <user> -c

@Yegorov
Copy link

Yegorov commented Aug 18, 2020

Adapted for Capistrano 3

namespace :rails do
  desc "Open the rails console on one of the remote servers"
  task :console do |current_task|
    on roles(:app) do |server|
      exec %Q[ssh -l #{server.user} #{server.hostname} -p #{server.port || 22} -t 'source ~/.bashrc > /dev/null; cd #{release_path}; bin/rails console']
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment