Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. # Gets host's API key and saves it on the node object.
  2. action :get_apikey do
  3. director_secrets = data_bag_item('secrets', 'icinga-director')
  4. director_username = director_secrets['username']
  5. director_password = director_secrets['password']
  6. director_apikey = director_secrets['api_key']
  7.  
  8. if director_username.nil? || director_password.nil?
  9. raise "Cannot call :get_apikey action without specifying username and password to the Icinga Director API."
  10. end
  11.  
  12. # Generate request URL
  13. base_uri = new_resource.director_url
  14. uri = URI.parse("#{base_uri}host?name=#{node['fqdn']}")
  15. Chef::Log.debug("Retrieving API key for the host from the Icinga Director API. Request URL: #{uri}.")
  16.  
  17. # Create HTTP request
  18. req = Net::HTTP::Get.new(uri)
  19. req.basic_auth director_username, director_password
  20. req['Accept'] = 'application/json'
  21.  
  22. # Create and configure HTTP client
  23. http = Net::HTTP.new(uri.hostname, uri.port)
  24. http.use_ssl = true
  25. http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  26.  
  27. # Execute request
  28. res = http.request(req)
  29. res_status_code = res.code.to_i
  30.  
  31. if res_status_code == 200
  32. # Node object found
  33. res_object = JSON.parse(res.body)
  34. unless res_object['api_key'].nil? || res_object['api_key'].empty?
  35. Chef::Log.info('Retrieved the API key for host.')
  36. # Save key on the node object.
  37. node.normal['icinga2_client']['host_api_key'] = res_object['api_key']
  38. return
  39. end
  40. elsif res_status_code >= 400 && res_status_code < 600
  41. Chef::Log.error("Failed to retrieve host information from the Icinga Director. Code: #{res_status_code}. Body: #{res.body}.")
  42. end
  43.  
  44. # Node doesn't exist. Register
  45. Chef::Log.info("Attempting to register host with Icinga server.")
  46.  
  47. reg_uri = URI.parse("#{base_uri}self-service/register-host?name=#{node['fqdn']}&key=#{director_apikey}")
  48.  
  49. reg_req = Net::HTTP::Post.new(reg_uri)
  50. reg_req['Accept'] = 'application/json'
  51.  
  52. http = Net::HTTP.new(reg_uri.hostname, reg_uri.port)
  53. http.use_ssl = true
  54. http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  55. res = http.request(reg_req)
  56.  
  57. if res.code.to_i == 200
  58. Chef::Log.info('Successfully registered host with Icinga server.')
  59. node.normal['icinga2_client']['host_api_key'] = JSON.parse(res.body)
  60. else
  61. Chef::Log.error("Failed to register host with the Icinga server. Code: #{res.code.to_i}. Body: #{res.body}")
  62. end
  63. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement