class Ey::Core::Cli::Ssh

Public Instance Methods

handle() click to toggle source
# File lib/ey-core/cli/ssh.rb, line 74
def handle
  operator, environment = core_operator_and_environment_for(options)
  abort "Unable to find matching environment".red unless environment

  cmd      = option(:command)
  ssh_opts = []
  ssh_cmd  = ["ssh"]
  exits    = []
  user     = environment.username
  servers  = []

  if option(:command)
    if shell = option(:shell)
      cmd = Escape.shell_command([shell,'-lc',cmd])
    end

    if switch_active?(:tty)
      ssh_opts << "-t"
    elsif cmd.match(/sudo/)
      puts "sudo commands often need a tty to run correctly. Use -t option to spawn a tty.".yellow
    end

    servers += Ey::Core::Cli::Helpers::ServerSieve.filter(
      environment.servers,
      all: switch_active?(:all),
      app_servers: switch_active?(:app_servers),
      db_servers: switch_active?(:db_servers),
      db_master: switch_active?(:db_master),
      utilities: option(:utilities)
    )
  else
    if option(:bind_address)
      ssh_opts += ["-L", option(:bind_address)]
    end

    if option(:server)
      servers += [core_server_for(server: option(:server), operator: environment)]
    else
      servers += Ey::Core::Cli::Helpers::ServerSieve.filter(
        environment.servers,
        all: switch_active?(:all),
        app_servers: switch_active?(:app_servers),
        db_servers: switch_active?(:db_servers),
        db_master: switch_active?(:db_master),
        utilities: option(:utilities)
      )

      # Reinstate default behavior: If no command is passed and no
      # roles are passed, open a connection to the app master
      if servers.empty?
        servers += (environment.servers.all(role: "app_master") + environment.servers.all(role: "solo")).to_a
      end
    end
  end

  if servers.empty?
    abort "Unable to find any matching servers. Aborting.".red
  end

  servers.uniq!

  servers.each do |server|
    host = server.public_hostname
    name = server.name ? "#{server.role} (#{server.name})" : server.role
    puts "\nConnecting to #{name} #{host}".green
    sshcmd = Escape.shell_command((ssh_cmd + ["#{user}@#{host}"] + [cmd]).compact)
    puts "Running command: #{sshcmd}".green
    system sshcmd
    exits << $?.exitstatus
  end

  exit exits.detect {|status| status != 0 } || 0
end