Class: LisausaKnifePlugins::SetupSsh
- Inherits:
-
Chef::Knife
- Object
- Chef::Knife
- LisausaKnifePlugins::SetupSsh
- Defined in:
- lib/chef/knife/setup_ssh.rb
Instance Method Summary collapse
-
#run ⇒ Object
This method will be executed when you run this knife command.
Instance Method Details
#run ⇒ Object
This method will be executed when you run this knife command.
15 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 |
# File 'lib/chef/knife/setup_ssh.rb', line 15 def run Shef::Extensions.extend_context_object(self) ssh_config = [] ssh_config << "\n\n### BEGIN KNIFE BLOCK ###" ssh_config << "## This was generated by `knife setup ssh`:" STDOUT.sync = true nodes.all do |n| next if /vagrant/.match(n.name) name = n.name name << '.lisausa.net' unless /\.lisausa.net\Z/.match(n.name) begin hostname = n.ipaddress rescue => ex ui.warn("Error (#{ex.inspect}) while getting #ipaddress for #{n.name}") next end ssh_config << [ "Host #{name}", " HostName #{hostname}", " HostKeyAlias #{[name,hostname,n.macaddress].join('-')}" ] end if (c = Chef::Config.knife).keys.grep(/identity_file|ssh_user/).any? ssh_config.push [ "Host *.lisausa.net", " IdentitiesOnly yes", " PasswordAuthentication no", " ForwardAgent yes" ] ssh_config.push " IdentityFile #{c[:identity_file]}" if c[:identity_file] ssh_config.push " User #{c[:ssh_user]}" if c[:ssh_user] end ssh_config << "### END KNIFE BLOCK ###" ssh_config = ssh_config.flatten.join("\n") file_path = File.join(ENV['HOME'], '.ssh', 'config') if config[:write] or ui.ask_question("Write config to #{file_path} (Y/N)?", default: 'N').downcase == 'y' FileUtils.copy_file(file_path, "#{file_path}~") File.open(file_path, File::RDWR|File::CREAT) do |f| f.flock(File::LOCK_EX) contents = f.read.gsub(/\n*### BEGIN KNIFE BLOCK ###.+?(### END KNIFE BLOCK ###|\Z)/m, ssh_config) unless contents.include?('### BEGIN KNIFE BLOCK ###') contents << ssh_config end f.rewind f.truncate(0) f.write contents end ui.msg "Wrote to #{file_path}. Previous contents were backed up to #{file_path}~" else ui.msg "Copy and paste the following into your #{file_path} file:" ui.msg ssh_config end end |