class Upman::Utils::Api

Public Instance Methods

_url() click to toggle source
# File lib/upman/utils/api.rb, line 64
def _url
  config = ::Upman::Core::Config.foreman_api
  protocol = config[:ssl] ? 'https://' : 'http://'
  "#{protocol}#{config[:host]}:#{config[:port]}/api/v#{config[:api_version]}/"
end
check_connection() click to toggle source
# File lib/upman/utils/api.rb, line 10
def check_connection
  response = self.get "status"
  if response.nil?
    return false
  end

  unless response.code == 200
    fail "Could not connect to API endpoint"
    return false
  end
  success "API Endpoint connected to Forman #{JSON.parse(response.body)["version"]} using API v#{JSON.parse(response.body)["api_version"]}."
  true
end
get(api_endoint) click to toggle source
# File lib/upman/utils/api.rb, line 47
def get(api_endoint)
  begin
    info "Send GET request to #{_url}#{api_endoint}"
    RestClient::Request.execute method: :get, url: _url + api_endoint, content_type: :json, accept: :json, user: Upman::Core::Config.foreman_api[:username], password: Upman::Core::Config.foreman_api[:password]
  rescue RestClient::Unauthorized
    fail "API Endpoint could not validate your credentials. Please check username or password"
  rescue OpenSSL::SSL::SSLError
    fail "Could not establish a secure connection to our API Endpoint"
  rescue RestClient::NotFound
    fail "API Endpoint route could not found"
  rescue RestClient::InternalServerError
    fail "API Endpoint reports error, ignore request"
  rescue Errno::ECONNREFUSED
    fail "Can not connect to your Foreman instance on #{_url}"
  end
end
post(api_endoint, data) click to toggle source
# File lib/upman/utils/api.rb, line 24
def post(api_endoint, data)
  begin
    info "Send POST request to #{_url}#{api_endoint}"
    RestClient::Request.execute method: :post,
                                url: _url + api_endoint,
                                payload: data,
                                headers: {:accept => :json, content_type: :json},
                                user: Upman::Core::Config.foreman_api[:username],
                                password: Upman::Core::Config.foreman_api[:password]
  rescue RestClient::Unauthorized
    fail "API Endpoint could not validate your credentials. Please check username or password"
  rescue OpenSSL::SSL::SSLError
    fail "Could not establish a secure connection to our API Endpoint"
  rescue RestClient::NotFound
    fail "API Endpoint route could not found"
  rescue RestClient::InternalServerError
    fail "API Endpoint reports error, ignore request"
  rescue Errno::ECONNREFUSED
    fail "Can not connect to Foreman instance on #{_url}"
  end

end