Class: PuppetDB::Connection

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

Instance Method Summary collapse

Constructor Details

#initialize(host = 'puppetdb', port = 443, use_ssl = true) ⇒ Connection

Returns a new instance of Connection.

[View source]

9
10
11
12
13
14
# File 'lib/puppetdb/connection.rb', line 9

def initialize(host='puppetdb', port=443, use_ssl=true)
  @host = host
  @port = port
  @use_ssl = use_ssl
  @parser = PuppetDB::Parser.new
end

Instance Method Details

#facts(facts, nodequery, http = nil) ⇒ Hash

Get the listed facts for all nodes matching query return it as a hash of hashes

Parameters:

  • facts (Array)

    the list of facts to fetch

  • nodequery (Array)

    the query to find the nodes to fetch facts for

Returns:

  • (Hash)

    a hash of hashes with facts for each node mathing query

[View source]

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

def facts(facts, nodequery, http=nil)
  if facts.empty?
    q = ['in', 'certname', ['extract', 'certname', ['select-facts', nodequery]]]
  else
    q = ['and', ['in', 'certname', ['extract', 'certname', ['select-facts', nodequery]]], ['or', *facts.collect { |f| ['=', 'name', f]}]]
  end
  facts = {}
  query(:facts, q, http).each do |fact|
    if facts.include? fact['certname'] then
      facts[fact['certname']][fact['name']] = fact['value']
    else
      facts[fact['certname']] = {fact['name'] => fact['value']}
    end
  end
  facts
end

#parse_query(query, endpoint = :nodes) ⇒ Array

Parse a query string into a PuppetDB query

Parameters:

  • query (String)

    the query string to parse

  • endpoint (Symbol) (defaults to: :nodes)

    the endpoint for which the query should be evaluated

Returns:

  • (Array)

    the PuppetDB query

[View source]

21
22
23
# File 'lib/puppetdb/connection.rb', line 21

def parse_query(query, endpoint=:nodes)
  @parser.scan_str(query).optimize.evaluate endpoint
end

#query(endpoint, query = nil, http = nil) ⇒ Array

Execute a PuppetDB query

Parameters:

  • endpoint (Symbol)

    :resources, :facts or :nodes

  • query (Array) (defaults to: nil)

    query to execute

Returns:

  • (Array)

    the results of the query

Raises:

  • (Puppet::Error)
[View source]

53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/puppetdb/connection.rb', line 53

def query(endpoint, query=nil, http=nil)
  unless http then
    require 'puppet/network/http_pool'
    http = Puppet::Network::HttpPool.http_instance(@host, @port, @use_ssl)
  end
  headers = { "Accept" => "application/json" }

  uri = "/v2/#{endpoint.to_s}"
  uri += URI.escape "?query=#{query.to_json}" unless query.nil? or query.empty?

  resp = http.get(uri, headers)
  raise Puppet::Error, "PuppetDB query error: [#{resp.code}] #{resp.msg}, query: #{query.to_json}" unless resp.kind_of?(Net::HTTPSuccess)
  return JSON.parse(resp.body)
end