Method: Bfire::Engine#ssh

Defined in:
lib/bfire/engine.rb

#ssh(fqdn, username, options = {}) {|Net::SSH::Connection::Session| ... } ⇒ Object

Setup an SSH connection as username to fqdn. By default, the SSH connection will be retried at most ssh_max_attempts times if the host is unreachable. You can overwrite that default locally by passing a different ssh_max_attempts option. Same for :timeout and :keys options.

If option :multi is given and true, then an instance of Net::SSH::Multi::Session is yielded. See <net-ssh.github.com/multi/v1/api/index.html> for more information.

Parameters:

  • fqdn (String)

    the fully qualified domain name of the host to connect to.

  • username (String)

    the login to use to connect to the host.

  • options (Hash) (defaults to: {})

    a hash of additional options to pass.

Yields:

  • (Net::SSH::Connection::Session)

    ssh a SSH handler.

Raises:

  • (ArgumentError)


470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/bfire/engine.rb', line 470

def ssh(fqdn, username, options = {}, &block)
  raise ArgumentError, "You MUST provide a block when calling #ssh" if block.nil?
  log = !!options.delete(:log)
  options[:timeout] ||= 10
  if options.has_key?(:password)
    options[:auth_methods] ||= ['keyboard-interactive']
  else
    options[:keys] ||= [conf[:key]].compact
  end
  max_attempts = options[:max_attempts] || conf[:ssh_max_attempts]
  logger.info "#{banner}SSHing to #{username}@#{fqdn.inspect}..." if log
  attempts = 0
  begin
    attempts += 1
    if options[:multi]
      Net::SSH::Multi.start(
        :concurrent_connections => (
          options[:concurrent_connections] || 10
        )
      ) do |s|
        s.via conf[:gateway], conf[:user] unless conf[:gateway].nil?
        fqdn.each {|h| s.use "#{username}@#{h}"}
        block.call(s)
      end
    else
      if conf[:gateway]
        gw_handler = Net::SSH::Gateway.new(conf[:gateway], conf[:user], :forward_agent => true)
        gw_handler.ssh(fqdn, username, options, &block)
        gw_handler.shutdown!
      else
        Net::SSH.start(fqdn, username, options, &block)
      end
    end
  rescue Errno::EHOSTUNREACH => e
    if attempts <= max_attempts
      logger.info "#{banner}No route to host #{fqdn}. Retrying in 5 secs..." if log
      sleep 5
      retry
    else
      logger.info "#{banner}No route to host #{fqdn}. Won't retry." if log
      raise e
    end
  end
end