Class: Proxy::Salt::ApiRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_proxy_salt/api_request.rb

Overview

SaltStack’s Rest API

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeApiRequest

Returns a new instance of ApiRequest.



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/smart_proxy_salt/api_request.rb', line 17

def initialize
  @url = Proxy::Salt::Plugin.settings.api_url
  @auth = Proxy::Salt::Plugin.settings.api_auth
  @username = Proxy::Salt::Plugin.settings.api_username
  @password = Proxy::Salt::Plugin.settings.api_password

  begin
    URI.parse(url)
  rescue URI::InvalidURIError => e
    raise ConfigurationError.new("Invalid Salt api_url setting: #{e}")
  end
end

Instance Attribute Details

#authObject (readonly)

Returns the value of attribute auth.



15
16
17
# File 'lib/smart_proxy_salt/api_request.rb', line 15

def auth
  @auth
end

#passwordObject (readonly)

Returns the value of attribute password.



15
16
17
# File 'lib/smart_proxy_salt/api_request.rb', line 15

def password
  @password
end

#urlObject (readonly)

Returns the value of attribute url.



15
16
17
# File 'lib/smart_proxy_salt/api_request.rb', line 15

def url
  @url
end

#usernameObject (readonly)

Returns the value of attribute username.



15
16
17
# File 'lib/smart_proxy_salt/api_request.rb', line 15

def username
  @username
end

Instance Method Details

#post(path, options = {}) ⇒ Object

Raises:



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/smart_proxy_salt/api_request.rb', line 30

def post(path, options = {})
  uri              = URI.parse(url)
  http             = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl     = uri.scheme == 'https'
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  path = [uri.path, path].join unless uri.path.empty?

  request = Net::HTTP::Post.new(URI.join(uri.to_s, path).path)
  request.add_field('Accept', 'application/json')
  request.set_form_data(options.merge(:username => username, :password => password, :eauth => auth))

  response = http.request(request)

  raise NotFound.new("Received 404 from Salt API: #{response.body}") if response.is_a?(Net::HTTPNotFound)
  raise ApiError.new("Failed to query Salt API (#{response.code}): #{response.body}") unless response.is_a?(Net::HTTPOK)

  JSON.parse(response.body)
end