def register(name=Chef::Config[:node_name], destination=Chef::Config[:client_key])
if (File.exists?(destination) && !File.writable?(destination))
raise Chef::Exceptions::CannotWritePrivateKey, "I cannot write your private key to #{destination} - check permissions?"
end
nc = Chef::ApiClient.new
nc.name(name)
catch(:done) do
retries = config[:client_registration_retries] || 5
0.upto(retries) do |n|
begin
response = nc.save(true, true)
Chef::Log.debug("Registration response: #{response.inspect}")
private_key = if response.respond_to?(:[])
response["private_key"]
else
response.private_key
end
unless private_key
raise Chef::Exceptions::CannotWritePrivateKey, "The response from the server did not include a private key!"
end
::File.open(destination, "w") {|f|
f.chmod(0600)
f.print(private_key)
}
throw :done
rescue IOError
raise Chef::Exceptions::CannotWritePrivateKey, "I cannot write your private key to #{destination}"
rescue Net::HTTPFatalError => e
Chef::Log.warn("Failed attempt #{n} of #{retries+1} on client creation")
raise unless e.response.code == "500"
end
end
end
true
end