Class: OpsWorks::Commands::SSH

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

Class Method Summary collapse

Class Method Details



12
13
14
# File 'lib/opsworks/commands/ssh.rb', line 12

def self.banner
  "Generate and update SSH configuration files"
end

.runObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/opsworks/commands/ssh.rb', line 16

def self.run
  options = Trollop::options do
    banner <<-EOS.unindent
      #{SSH.banner}

      Options:
    EOS
    opt :update, "Update ~/.ssh/config directly"
    opt :backup, "Backup old SSH config before updating"
    opt :quiet,  "Use SSH LogLevel quiet", default: true
    opt :key_checking,
        "Check SSH host keys (this can be annoying since dynamic " <<
        "instances often change IP number)", short: 'c', default: false
  end

  config = OpsWorks.config

  client = AWS::OpsWorks::Client.new

  result = client.describe_instances(stack_id: config.stack_id)
  instances = result.instances.select { |i| i[:status] != "stopped" }

  instances.map! do |instance|
    ip = instance[:elastic_ip] || instance[:public_ip]
    parameters = {
      "Host"                  => "#{instance[:hostname]} #{ip}",
      "HostName"              => ip,
      "User"                  => config.ssh_user_name,
    }
    parameters.merge!({
      "StrictHostKeyChecking" => "no",
      "UserKnownHostsFile"    => "/dev/null",
    }) unless options[:host_checking]
    parameters["LogLevel"] = "quiet" if options[:quiet]
    parameters.map{ |param| param.join(" ") }.join("\n  ")
  end

  new_contents = "\n#{SSH_PREFIX}\n#{instances.join("\n")}\n#{SSH_POSTFIX}"

  if options[:update]
    ssh_config = "#{ENV['HOME']}/.ssh/config"
    old_contents = File.read(ssh_config)

    if options[:backup]
      base_name = ssh_config + ".backup"
      if File.exists? base_name
        number = 0
        file_name = "#{base_name}-#{number}"
        while File.exists? file_name
          file_name = "#{base_name}-#{number += 1}"
        end
      else
        file_name = base_name
      end
      File.open(file_name, "w") { |file| file.puts old_contents }
    end

    File.open(ssh_config, "w") do |file|
      file.puts old_contents.gsub(/#{SSH_PREFIX}.*#{SSH_POSTFIX}/m, '')
      file.puts new_contents
    end

    puts "Successfully updated #{ssh_config} with " <<
         "#{instances.length} instances!"
  else
    puts new_contents.strip
  end
end