Search code examples
sshcapistranocapistrano3

Initializing an ssh session from cap 3?


I used to use cap-ssh for a shortcut to initiate an ssh connection to the server, but it doesn't look like it works in capistrano 3 anymore.

Does anyone have any suggestions for starting an ssh connection from capistrano in cap 3?


Solution

  • You can define ssh task like this:

    desc 'Start an ssh session to your servers.'
    task :ssh do
      role = (ENV['ROLE'] || :app).to_sym
      on roles(role) do
        hosts = env.instance_variable_get(:@servers).instance_variable_get(:@servers)
        hosts = hosts.select { |h| h.roles.include? role } if role
        if hosts.size > 1
          $stdout.puts "Pick a server to connect to:"
          hosts.each.with_index do |host, i|
            $stdout.puts "\t#{i + 1}: #{host.user}@#{host.hostname} role: #{host.roles.to_a}"
          end
          selected = $stdin.gets
          selected = 1 if selected.empty?
          host = hosts[selected.to_i - 1]
        else
          host = hosts.first
        end
        fail "No server defined!" unless host
    
        port = host.netssh_options[:port] || fetch(:ssh_options) && fetch(:ssh_options)[:port] || 22
        system "ssh -t -p #{port} #{host.user}@#{host.hostname} #{host.netssh_options[:forward_agent] ? '-a' : ''} 'cd #{current_path}; bash --login'"
      end
    end