class ForemanAP::ForemanAPI
Convenience methods for accessing the REST API of Foreman.
Attributes
log[RW]
Public Class Methods
new(uri, user, password)
click to toggle source
Create an object.
uri
-
The URI of the Foreman server.
user
-
The username to login with.
password
-
The password to login with.
# File lib/foreman_vm/foreman_api.rb, line 16 def initialize(uri, user, password) @uri = uri @user = user @password = password @log = Logger.new(STDERR) end
Public Instance Methods
get_id(path, name, key='name')
click to toggle source
Get the ID of a resource in Foreman.
path
-
The path to the resource, underneath of /api/v2
name
-
The name to lookup
key
-
Either ‘name’ or ‘title’. Don’t ask why there is a difference.
# File lib/foreman_vm/foreman_api.rb, line 70 def get_id(path, name, key='name') raise 'name is required' if name.nil? res = request(:get, "/#{path}?search=#{key}%20=%20\"#{URI.escape(name)}\"", {}) id = JSON.parse(res.body)['results'][0]['id'] raise 'Unable to get the ID for #{path}/#{key}=#{name}' if id.nil? id end
request(method, path, payload)
click to toggle source
Send a request to the Foreman API.
method
-
The HTTP method; can be :post, :put, :get, or :delete
path
-
The path to the resource, underneath of /api/v2.
payload
-
The data to provide along with the request.
# File lib/foreman_vm/foreman_api.rb, line 27 def request(method, path, payload) uri = URI.parse(@uri) path = '/api/v2/' + path @log.debug "getting #{path}" # Build the request case method when :post req = Net::HTTP::Post.new(path, initheader = {'Content-Type' =>'application/json'}) when :put req = Net::HTTP::Put.new(path, initheader = {'Content-Type' =>'application/json'}) when :get req = Net::HTTP::Get.new(path, initheader = {'Content-Type' =>'application/json'}) when :delete req = Net::HTTP::Delete.new(path, initheader = {'Content-Type' =>'application/json'}) else raise 'Unsuported method' end req.basic_auth @user, @password req.body = payload.to_json # Submit the request http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE #XXX-FIXME insecure response = http.start { |h| http.request(req) } @log.debug "Response #{response.code} #{response.message}: #{response.body}" if response.code != '200' @log.error "Error #{response.code} calling the Foreman API: #{response.body}" raise 'Error calling the Foreman API' end return response end