Module: SSHHelper

Includes:
DebugSupport, KnifePluginSupport
Included in:
MiniTest::Unit::EC2TestCase, MiniTest::Unit::EC2TestCase, MiniTest::Unit::VagrantTestCase, MiniTest::Unit::VagrantTestCase
Defined in:
lib/chef-workflow/helpers/ssh.rb

Overview

Helper for performing SSH on groups of servers. Intended to be mixed into test case classes.

Instance Method Summary collapse

Instance Method Details

#configure_ssh_command(ip, command) ⇒ Object

takes a block which it uses inside of the open_channel block that Net::SSH uses. Intended to provide a consistent way of setting up Net::SSH Makes heavy use of KnifeSupport to determine how to drive the command.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/chef-workflow/helpers/ssh.rb', line 36

def configure_ssh_command(ip, command)
  command = "#{KnifeSupport.singleton.use_sudo ? 'sudo ': ''}#{command}"

  options = { }

  options[:password] = KnifeSupport.singleton.ssh_password          if KnifeSupport.singleton.ssh_password
  options[:keys]     = [KnifeSupport.singleton.ssh_identity_file]   if KnifeSupport.singleton.ssh_identity_file

  Net::SSH.start(ip, KnifeSupport.singleton.ssh_user, options) do |ssh|
    ssh.open_channel do |ch|
      ch.on_open_failed do |ch, code, desc|
        raise "Connection Error to #{ip}: #{desc}"
      end

      ch.exec(command) do |ch, success|
        yield ch, success
      end
    end

    ssh.loop
  end
end

#ssh_capture(ip, command) ⇒ Object

run a command, and instead of capturing the exit status, return the data captured during the command run.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/chef-workflow/helpers/ssh.rb', line 83

def ssh_capture(ip, command)
  retval = ""
  configure_ssh_command(ip, command) do |ch, success|
    return "" unless success

    ch.on_data do |ch, data|
      retval << data
    end

    ch.on_request("exit-status") do |ch, data|
      return retval
    end
  end

  return retval
end

#ssh_command(ip, command) ⇒ Object

Run a command against a single IP. Returns the exit status.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/chef-workflow/helpers/ssh.rb', line 63

def ssh_command(ip, command)
  configure_ssh_command(ip, command) do |ch, success|
    return 1 unless success

    if_debug(2) do
      ch.on_data do |ch, data|
        $stderr.puts data
      end
    end

    ch.on_request("exit-status") do |ch, data|
      return data.read_long
    end
  end
end

#ssh_role_command(role, command) ⇒ Object

run a command against a group of servers. These commands are run in parallel, but the command itself does not complete until all the threads have finished running.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/chef-workflow/helpers/ssh.rb', line 19

def ssh_role_command(role, command)
  t = []
  IPSupport.singleton.get_role_ips(role).each do |ip|
    t.push(
      Thread.new do
        ssh_command(ip, command)
      end
    )
  end
  t.each(&:join)
end