class Chef::Knife::Ec2SshConfigGenerate

Constants

BEGIN_MARKER
END_MARKER
GEN_WARNING
SSH_CONFIG_FILE

Public Instance Methods

run() click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 46
def run
  $stdout.sync = true
  backup_ssh_file
  remove_old_config
  write_config
end

Private Instance Methods

backup_ssh_file() click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 102
def backup_ssh_file
  ssh_backup_file = "#{SSH_CONFIG_FILE}-knife-#{Time.now.to_i}"
  copy_file SSH_CONFIG_FILE, ssh_backup_file
  ui.info "Backed up ssh config file to #{ssh_backup_file}"
end
connection() click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 108
def connection
  @connection ||= begin
                    connection = Fog::Compute.new(
                      :provider => 'AWS',
                      :aws_access_key_id => Chef::Config[:knife][:aws_access_key_id],
                      :aws_secret_access_key => Chef::Config[:knife][:aws_secret_access_key],
                      :region => locate_config_value(:region)
                    )
                  end
end
locate_config_value(key) click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 119
def locate_config_value(key)
  key = key.to_sym
  config[key] || Chef::Config[:knife][key]
end
remove_old_config() click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 81
def remove_old_config
  content = open(SSH_CONFIG_FILE).read
  content.slice! /#{BEGIN_MARKER}\n*.*\n#{END_MARKER}/mi
  open(SSH_CONFIG_FILE, "w").write(content.strip)
end
servers() click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 87
def servers
  unless @servers
    @servers = {}
    connection.servers.all.each do |server|
      #puts server.inspect
      if tag = server.tags['Name']
        unless server.dns_name.nil? || server.dns_name == " " || server.state != "running"
          @servers[tag] = server.dns_name
        end
      end
    end
  end
  @servers
end
write_config() click to toggle source
# File lib/chef/knife/ec2_ssh_config_generate.rb, line 55
def write_config
  open(SSH_CONFIG_FILE, "a") do | f |
    f.puts ""
    f.puts BEGIN_MARKER
    f.puts GEN_WARNING
    f.puts ""
    servers.each do |name, host|
      if namespace = locate_config_value(:ec2_ssh_namespace)
        f.puts "Host #{namespace}-#{name}" 
      else
        f.puts "Host #{name}"
      end
      f.puts "  HostName #{host}"
      if user = locate_config_value(:ssh_user)
        f.puts "  User #{user}"
      end
      if identity = locate_config_value(:identity_file)
        f.puts "  IdentityFile #{File.expand_path(identity)}"
      end
      f.puts ""
    end
    f.puts END_MARKER
    f.puts ""
  end
end