Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Gets host's API key and saves it on the node object.
- action :get_apikey do
- director_secrets = data_bag_item('secrets', 'icinga-director')
- director_username = director_secrets['username']
- director_password = director_secrets['password']
- director_apikey = director_secrets['api_key']
- if director_username.nil? || director_password.nil?
- raise "Cannot call :get_apikey action without specifying username and password to the Icinga Director API."
- end
- # Generate request URL
- base_uri = new_resource.director_url
- uri = URI.parse("#{base_uri}host?name=#{node['fqdn']}")
- Chef::Log.debug("Retrieving API key for the host from the Icinga Director API. Request URL: #{uri}.")
- # Create HTTP request
- req = Net::HTTP::Get.new(uri)
- req.basic_auth director_username, director_password
- req['Accept'] = 'application/json'
- # Create and configure HTTP client
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
- # Execute request
- res = http.request(req)
- res_status_code = res.code.to_i
- if res_status_code == 200
- # Node object found
- res_object = JSON.parse(res.body)
- unless res_object['api_key'].nil? || res_object['api_key'].empty?
- Chef::Log.info('Retrieved the API key for host.')
- # Save key on the node object.
- node.normal['icinga2_client']['host_api_key'] = res_object['api_key']
- return
- end
- elsif res_status_code >= 400 && res_status_code < 600
- Chef::Log.error("Failed to retrieve host information from the Icinga Director. Code: #{res_status_code}. Body: #{res.body}.")
- end
- # Node doesn't exist. Register
- Chef::Log.info("Attempting to register host with Icinga server.")
- reg_uri = URI.parse("#{base_uri}self-service/register-host?name=#{node['fqdn']}&key=#{director_apikey}")
- reg_req = Net::HTTP::Post.new(reg_uri)
- reg_req['Accept'] = 'application/json'
- http = Net::HTTP.new(reg_uri.hostname, reg_uri.port)
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
- res = http.request(reg_req)
- if res.code.to_i == 200
- Chef::Log.info('Successfully registered host with Icinga server.')
- node.normal['icinga2_client']['host_api_key'] = JSON.parse(res.body)
- else
- Chef::Log.error("Failed to register host with the Icinga server. Code: #{res.code.to_i}. Body: #{res.body}")
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement