Class: Opsicle::SSH

Inherits:
Object
  • Object
show all
Defined in:
lib/opsicle/commands/ssh.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(environment) ⇒ SSH

Returns a new instance of SSH.



5
6
7
# File 'lib/opsicle/commands/ssh.rb', line 5

def initialize(environment)
  @client = Client.new(environment)
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



3
4
5
# File 'lib/opsicle/commands/ssh.rb', line 3

def client
  @client
end

Instance Method Details

#execute(options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/opsicle/commands/ssh.rb', line 9

def execute(options={})

  if instances.length == 1
    choice = 1
  else
    Output.say "Choose an Opsworks instance:"
    instances.each_with_index do |instance, index|
      Output.say "#{index+1}) #{instance[:hostname]}"
    end
    choice = Output.ask("? ", Integer) { |q| q.in = 1..instances.length }
  end

  command = ssh_command(instances[choice-1], options)

  Output.say_verbose "Executing shell command: #{command}"
  system(command)
end

#instancesObject



27
28
29
30
31
# File 'lib/opsicle/commands/ssh.rb', line 27

def instances
  @instances ||= client.api_call(:describe_instances, { stack_id: client.config.opsworks_config[:stack_id] })
                       .data[:instances]
                       .select { |instance| instance[:status].to_s == 'online'}
end

#public_ipsObject



33
34
35
# File 'lib/opsicle/commands/ssh.rb', line 33

def public_ips
  instances.map{|instance| instance[:elastic_ip] || instance[:public_ip] }.compact
end

#ssh_command(instance, options = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/opsicle/commands/ssh.rb', line 41

def ssh_command(instance, options={})
  ssh_command = " \"#{options[:"ssh-cmd"].gsub(/'/){ %q(\') }}\"" if options[:"ssh-cmd"] #escape single quotes
  ssh_options = options[:"ssh-opts"] ? "#{options[:"ssh-opts"]} " : ""
  if instance_ip = instance[:elastic_ip] || instance[:public_ip]
    ssh_string = "#{ssh_username}@#{instance_ip}"
  else
    ssh_string = "#{ssh_username}@#{public_ips.sample} ssh #{instance[:private_ip]}"
    ssh_options.concat('-A -t ')
  end

  "ssh #{ssh_options}#{ssh_string}#{ssh_command}"
end

#ssh_usernameObject



37
38
39
# File 'lib/opsicle/commands/ssh.rb', line 37

def ssh_username
  client.api_call(:describe_my_user_profile)[:user_profile][:ssh_username]
end