How to enter rails console on production via capistrano? How to enter rails console on production via capistrano? ruby-on-rails ruby-on-rails

How to enter rails console on production via capistrano?


I've added my own tasks for this kind of thing:

namespace :rails do  desc "Remote console"  task :console, :roles => :app do    run_interactively "bundle exec rails console #{rails_env}"  end  desc "Remote dbconsole"  task :dbconsole, :roles => :app do    run_interactively "bundle exec rails dbconsole #{rails_env}"  endenddef run_interactively(command)  server ||= find_servers_for_task(current_task).first  exec %Q(ssh #{user}@#{myproductionhost} -t '#{command}')end

I now say cap rails:console and get a console.


For Capistrano 3 you can add these lines in your config/deploy:

namespace :rails do  desc 'Open a rails console `cap [staging] rails:console [server_index default: 0]`'  task :console do        server = roles(:app)[ARGV[2].to_i]    puts "Opening a console on: #{server.hostname}...."    cmd = "ssh #{server.user}@#{server.hostname} -t 'cd #{fetch(:deploy_to)}/current && RAILS_ENV=#{fetch(:rails_env)} bundle exec rails console'"    puts cmd    exec cmd  endend

To open the first server in the servers list:

cap [staging] rails:console 

To open the second server in the servers list:

cap [staging] rails:console 1 

Reference: Opening a Rails console with Capistrano 3

exec is needed to replace the current process, otherwise you will not be able to interact with the rails console.


A simple Capistrano 3 solution may be:

namespace :rails do  desc "Run the console on a remote server."  task :console do    on roles(:app) do |h|      execute_interactively "RAILS_ENV=#{fetch(:rails_env)} bundle exec rails console", h.user    end  end  def execute_interactively(command, user)    info "Connecting with #{user}@#{host}"    cmd = "ssh #{user}@#{host} -p 22 -t 'cd #{fetch(:deploy_to)}/current && #{command}'"    exec cmd  endend

Then you can call it say, on staging, with: cap staging rails:console. Have fun!