Class: Bolt::PuppetDB::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/puppetdb/client.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, cacert, token: nil, cert: nil, key: nil) ⇒ Client

Returns a new instance of Client.



26
27
28
29
30
31
32
# File 'lib/bolt/puppetdb/client.rb', line 26

def initialize(uri, cacert, token: nil, cert: nil, key: nil)
  @uri = uri
  @cacert = cacert
  @token = token
  @cert = cert
  @key = key
end

Class Method Details

.from_config(config) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/bolt/puppetdb/client.rb', line 8

def self.from_config(config)
  uri = if config['server_urls'].is_a? String
          config['server_urls']
        else
          config['server_urls'].first
        end
  uri = URI.parse(uri)
  uri.port ||= 8081

  cacert = File.expand_path(config['cacert'])
  token = config.token

  cert = config['cert']
  key = config['key']

  new(uri, cacert, token: token, cert: cert, key: key)
end

Instance Method Details

#headersObject



61
62
63
64
65
# File 'lib/bolt/puppetdb/client.rb', line 61

def headers
  headers = { 'Content-Type' => 'application/json' }
  headers['X-Authentication'] = @token if @token
  headers
end

#http_clientObject



52
53
54
55
56
57
58
59
# File 'lib/bolt/puppetdb/client.rb', line 52

def http_client
  return @http if @http
  @http = HTTPClient.new
  @http.ssl_config.set_client_cert_file(@cert, @key)
  @http.ssl_config.add_trust_ca(@cacert)

  @http
end

#query_certnames(query) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/bolt/puppetdb/client.rb', line 34

def query_certnames(query)
  return [] unless query

  body = JSON.generate(query: query)

  response = http_client.post("#{@uri}/pdb/query/v4", body: body, header: headers)
  if response.code != 200
    raise Bolt::PuppetDBError, "Failed to query PuppetDB: #{response.body}"
  else
    results = JSON.parse(response.body)
    if results.first && !results.first.key?('certname')
      fields = results.first.keys
      raise Bolt::PuppetDBError, "Query results did not contain a 'certname' field: got #{fields.join(', ')}"
    end
    results.map { |result| result['certname'] }.uniq
  end
end