Created
September 17, 2019 13:59
-
-
Save DWSR/38c85d437cbb655d30da7bb6c8e6d096 to your computer and use it in GitHub Desktop.
Generate an SSH known_hosts file from all nodes on a Chef Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/opt/chef/embedded/bin/ruby | |
require 'chef' | |
require 'logger' | |
config_file = '/etc/chef/client.rb' | |
known_hosts_file = "#{ENV['HOME']}/known_hosts" | |
known_hosts = [] | |
logger = Logger.new(STDOUT) | |
# Change to Logger::DEBUG for debug output | |
logger.sev_threshold = Logger::INFO | |
logger.info("Config file: #{config_file}") | |
logger.debug("Loading config file") | |
# Load Chef Infra Client config. This allows communicating with Chef Server | |
Chef::Config.from_string(File.read(config_file), config_file) | |
logger.debug("Loaded config file successfully") | |
# Output some config | |
logger.info("Chef Server Url: #{Chef::Config[:chef_server_url]}") | |
logger.info("Node Name: #{Chef::Config[:node_name]}") | |
query = Chef::Search::Query.new | |
# We're only interested in specific attributes, so build a filter to reduce the | |
# amount of data returned | |
# https://docs.chef.io/chef_search.html#filter-search-results | |
attrs = { | |
name: ['name'], | |
private_ipv4_address: ['ec2', 'local_ipv4'], | |
public_ipv4_address: ['ec2', 'public_ipv4'], | |
host_rsa_key: ['keys', 'ssh', 'host_rsa_public'] | |
} | |
# Query for all nodes | |
begin | |
results = query.search( | |
:node, | |
'*:*', | |
filter_result: attrs, | |
rows: 1_000_000 | |
) | |
rescue StandardError => e | |
logger.error("Caught #{e} while querying Chef") | |
logger.error(e.backtrace) | |
exit 1 | |
end | |
logger.info("Result count: #{results[0].count}") | |
results[0].each do |r| | |
logger.debug("Processing #{r['name']}") | |
known_hosts << "#{r['private_ipv4_address']} ssh-rsa #{r['host_rsa_key']}" | |
known_hosts << "#{r['public_ipv4_address']} ssh-rsa #{r['host_rsa_key']}" | |
end | |
logger.debug("Finished processing results") | |
logger.debug("Writing known_hosts file") | |
File.write(known_hosts_file, known_hosts.compact.flatten.join("\n")) | |
logger.info("Wrote results to #{known_hosts_file}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment