Code Monkey home page Code Monkey logo

puppet-puppetdbquery's Introduction

Build Status

PuppetDB query tools

This module implements command line tools and Puppet functions that can be used to query puppetdb. There's also a hiera backend that can be used to return query results from puppetdb.

Usage warning

You might not need this puppet module anymore. PuppetDB bundles a simplified query language since version 4.0. So unless you really prefer the syntax in this module you can just use PQL instead. See https://puppet.com/blog/introducing-puppet-query-language-pql for more details.

Requirements

PuppetDB terminus is required for the Puppet functions, but not for the face.

To parse date queries the Ruby gem "chronic" is required.

Required PuppetDB version

This module uses the V4 API, and as such it requires at least PuppetDB 3.0.0. If you are using PuppetDB 2.x please use the 1.x version of this module instead.

Query syntax

Use fact=value to search for nodes where fact equals value. To search for structured facts use dots between each part of the fact path, for example foo.bar=baz.

Resources can be matched using the syntax type[title]{param=value}. The part in brackets is optional. You can also specify ~ before the title to do a regexp match on the title. Type names and class names are case insensitive. A resource can be preceded by @@ to match exported resources, the default is to only match "local" resources.

Strings can contain letters, numbers or the characters :-_ without needing to be quoted. If they contain any other characters they need to be quoted with single or double quotes. Use backslash () to escape quotes within a quoted string or double backslash for backslashes.

An unquoted number or the strings true/false will be interpreted as numbers and boolean values, use quotation marks around them to search for them as strings instead.

A @ sign before a string causes it to be interpreted as a date parsed with chronic. For example @"2 hours ago".

A # sign can be used to do a subquery, against the nodes endpoint for example to query the report_timestamp, catalog_timestamp or facts_timestamp fields. For example #node.report_timestamp < @"2 hours ago".

A subquery using the # sign can have a block of expressions instead of a single expression. For example #node { report_timestamp > @"4 hours ago" and report_timestamp < @"2 hours ago" }

A bare string without comparison operator will be treated as a regexp match against the certname.

Comparison operators

Op Meaning
= Equality
!= Not equal
~ Regexp match
!~ Not equal Regexp match
< Less than
=< Less than or equal
> Greater than
=> Greater than or equal

Logical operators

Op
not (unary op)
and
or

Shown in precedence order from highest to lowest. Use parenthesis to change order in an expression.

Query Examples

Nodes with package mysql-server and amd64 arcitecture

(package["mysql-server"] and architecture=amd64)

Nodes with the class Postgresql::Server and a version set to 9.3

class[postgresql::server]{version=9.3}

Nodes with 4 or 8 processors running Linux

(processorcount=4 or processorcount=8) and kernel=Linux

Nodes that haven't reported in the last 2 hours

#node.report_timestamp<@"2 hours ago"

Usage

To get a list of the supported subcommands for the puppetdbquery face, run:

 $ puppet help puppetdbquery

You can run puppet help on the returned subcommands

$ puppet help puppetdbquery nodes
$ puppet help puppetdbquery facts

CLI

Each of the faces uses the following query syntax to return all objects found on a subset of nodes:

# get all nodes that contain the apache package and are in france, or all nodes in the us
$ puppet puppetdbquery nodes '(Package[httpd] and country=fr) or country=us'

Each of the individual faces returns a different data format:

nodes - a list of nodes identified by a name

 $ puppet puppetdbquery nodes '(Package["mysql-server"] and architecture=amd64)'
   ["db_node_1", "db_node2"]

facts - a hash of facts per node

 $ puppet puppetdbquery facts '(Package["mysql-server"] and architecture=amd64)'
   db_node_1  {"facterversion":"1.6.9","hostname":"controller",...........}
   db_node_2  {"facterversion":"1.6.9","hostname":"controller",...........}

events - a list of events on the matched nodes

 $ puppet puppetdbquery events '(Package["mysql-server"] and architecture=amd64)' --since='1 hour ago' --until=now --status=success
   host.example.com: 2013-06-10T10:58:37.000Z: File[/foo/bar]/content ({md5}5711edf5f5c50bd7845465471d8d39f0 -> {md5}e485e731570b8370f19a2a40489cc24b): content changed '{md5}5711edf5f5c50bd7845465471d8d39f0' to '{md5}e485e731570b8370f19a2a40489cc24b'

Ruby

faces can be called from the ruby in exactly they same way they are called from the command line:

$ irb> require 'puppet/face'
  irb> Puppet.initialize_settings
  irb> Puppet::Face[:puppetdbquery, :current].nodes('(Package["mysql-server"] and architecture=amd64)')

Puppet functions

There's corresponding functions to query PuppetDB directly from Puppet manifests. All the functions accept either the simplified query language or raw PuppetDB API queries.

query_nodes

Accepts two arguments, a query used to discover nodes, and a optional fact that should be returned.

Returns an array of certnames or fact values if a fact is specified.

Examples

$hosts = query_nodes('manufacturer~"Dell.*" and processorcount=24 and Class[Apache]')

$hostips = query_nodes('manufacturer~"Dell.*" and processorcount=24 and Class[Apache]', 'ipaddress')

query_resources

Accepts two arguments or three argument, a query used to discover nodes, and a resource query , and an optional a boolean to whether or not to group the result per host.

Return either a hash (by default) that maps the name of the nodes to a list of resource entries. This is a list because there's no single reliable key for resource operations that's of any use to the end user.

Examples

Returns the parameters and such for the ntp class for all CentOS nodes:

$resources = query_resources('Class["apache"]{ port = 443 }', 'User["apache"]')

Returns the parameters for the apache class for all nodes in a flat array:

query_resources(false, 'Class["apache"]', false)

query_facts

Similar to query_nodes but takes two arguments, the first is a query used to discover nodes, the second is a list of facts to return for those nodes.

Returns a nested hash where the keys are the certnames of the nodes, each containing a hash with facts and fact values.

Example

query_facts('Class[Apache]{port=443}', ['osfamily', 'ipaddress'])

Example return value in JSON format:

{
  "foo.example.com": {
    "ipaddress": "192.168.0.2",
    "osfamily": "Redhat"
  },
  "bar.example.com": {
    "ipaddress": "192.168.0.3",
    "osfamily": "Debian"
  }
}

Querying nested facts

Facter 3 introduced many nested facts, so puppetdbquery provides an easy way to query for a value nested within a fact that's a hash. To query for a nested value, simply join the keys you want to extract together on periods, like so:

Example

$host_eth0_networks = query_nodes('manufacturer~"Dell.*" and Class[Apache]', 'networking.interfaces.eth0.network')

$host_kernels_and_ips = query_facts('manufacturer~"Dell.*" and Class[Apache]', ['kernel', 'networking.interfaces.eth1.ip'])

Hiera backend

The hiera backend can be used to return an array with results from a puppetdb query. It requires another hiera backend to be active at the same time, and that will be used to define the actual puppetdb query to be used. It does not matter which backend that is, there can even be several of them. To enable add the backend puppetdbto the backends list in hiera.yaml.

hiera 3

---
:backends:
  - yaml
  - puppetdb

hiera 5

---
version: 5

hierarchy:
  - name: Puppetdb
    lookup_key: puppetdb_lookup_key

Note: hiera 5 is not backward compatible

You can not use the hiera 3 backed at all in hiera 5. Backwards compatibility is broken. You must switch to hiera 5 config to use this in hiera 5.

Examples

So instead of writing something like this in for example your hiera-data/common.yaml:

ntp::servers:
  - 'ntp1.example.com'
  - 'ntp2.example.com'

You can now instead write:

ntp::servers::_nodequery: 'Class[Ntp::Server]'

It will then find all nodes with the class ntp::server and return an array containing their certname. If you instead want to return the value of a fact, for example the ipaddress, the nodequery can be a tuple, like:

ntp::servers::_nodequery: ['Class[Ntp::Server]', 'ipaddress']

or a hash:

ntp::servers::_nodequery:
  query: 'Class[Ntp::Server]'
  fact: 'ipaddress'

Sometimes puppetdb doesn't return items in the same order every run - hiera 5 only:

ntp::servers::_nodequery: ['Class[Ntp::Server]', 'ipaddress', true]

ntp::servers::_nodequery:
  query: 'Class[Ntp::Server]'
  fact: 'ipaddress'
  sort: true

When returning facts only nodes that actually have the fact are returned, even if more nodes would in fact match the query itself.

Related projects

puppet-puppetdbquery's People

Contributors

adrianlzt avatar andvgal avatar bazilek avatar bodepd avatar dalen avatar dependabot-support avatar edestecd avatar fiddyspence avatar gcmalloc avatar ghoneycutt avatar haiwu avatar halfninja avatar mcasper avatar nanliu avatar nbrownus avatar ripienaar avatar riton avatar rmnwolf avatar stahnma avatar trevor-vaughan avatar unki avatar vzctl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

puppet-puppetdbquery's Issues

query_fact function broken as of 2.0.3

Haven't had a chance to track it down yet, but I just got around to updating from 2.0.3 where the fixes for query_fact function were merged in to 2.1.0 and I get the following error with my code that was working with 2.0.3

Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Evaluation Error: Error while evaluating a Function Call, undefined method `get' for {:extract=>[:certname, :name, :value]}:Hash

I wanted to open a ticket to remember to track this down. For now I'm locking my Puppetfile to 2.0.3.

Problem with ruby 1.9.3

When doing a query in ruby 1.9.3p374, I get the following error:

Error: Could not run: (): could not find expected ':' while scanning a simple key at line 74 column 3

It works when doing the same query on ruby 1.8.7p371.

The query looks like this:

ret = pdbresourcequery(["and",["=",["node","active"],true],["and",["=","type","Class"],["=","title","Monkey"]]], 'certname')

Which I can duplicate with:

curl -G -H 'Accept: application/json' 'http://localhost:8080/resources' --data-urlencode 'query=["and",["=",["node","active"],true],["and",["=",["node","active"],true],["and",["=","type","Class"],["=","title","Monkey"]]]]'

Which returns:

[ {
"parameters" : { },
"sourceline" : null,
"sourcefile" : null,
"exported" : false,
"tags" : [ "im2", "node", "monkey", "class" ],
"title" : "Monkey",
"type" : "Class",
"resource" : "21551460733cce86d2d2d8a533f66fc51f183cb5",
"certname" : "im2"
} ]

Any ideas where to look for this or who to escalate it to? I did a quick scan and can't find that error string. Perhaps this is coming from upstream somewhere in another library.

feature: pdbfactquery

like pdbnodequery but returning an array of facts instead of node names.
ie. returning ip addresses of all workers to be included on load balancers.

$ret = pdbnodequery(
['and',
['=',['node','active'],true],
['=',['fact','projectname'],'puppetmaster']], 'ipaddress_bond0_1234')

New release

Hello,

Could you please release a new version so that I can take advantage of #56, currently on master?

Thanks,
Matt

How can I use puppetdbquery to return fqdn of one node as string?

I've a database server (Class[databaseserver]), now I need the fqdn of this node to configure different clients which use a string to configure the host of the database. Best sample is the puppetlabs puppetdb module which do it in this way.

If I try:

puppetdb::master::config::puppetdb_server::_puppetdbquery: 'Class[daabaseserver]'

puppetdb module write to syslog:

can not connect to [fqdn-of-dbhost]:8081

because fqdn is in an array instead of a string.

A workaround replace string with an array but than I must think at modules level 'Can I use puppetdb query to get this value'. And create 'wrapper' to convert array to string.

query report_timestamp from cli not working

puppet query nodes '#node.report_timestamp < @"2 hours ago"' --debug

gives the following ....

Debug: /File[/etc/puppetlabs/code/environments/production]: Adding autorequire relationship with File[/etc/puppetlabs/code]
Debug: Finishing transaction 37459200
Debug: #PuppetDB::Connection:0x00000002e56e90: PuppetDB query: ["extract",["certname"],["in","certname",["extract","certname",["select_nodes",["<","report_timestamp","2015-12-14T03:43:12+00:00"]]]]]
Debug: Creating new connection for https://puppet.nym1.placeiq.net:8081

so that looks fine but I actually get zero results when I should get 5 nodes returned.

One reason I know I should see 5 nodes returned is because this:

node.report_timestamp<@"now - 2 hours"

via Puppet Explorer, returns 5 nodes, as expected.

I stopped my pupperserver and with just puppetdb running and puppetdb's logging set to debug, I tried this query again and the results of that are attached.

Can you tell by looking at that if something is getting "lost in translation"?

puppetdb.log.txt

Errors with queries with a variable with hypens and variables surrounded with a single quotes

Errors with queries with a variable with hypens and variables surrounded with a single quotes. Should this be supported syntax? Thanks,

Query:
puppet query nodes "datacenter=chicago and environment=chicago-dev and server_group=test1 and load=complete"

Error: can not match: '-dev and environment=chicago-dev and server_group=test1 and load=complete'

Query:
puppet query nodes "datacenter=chicago and environment='chicago-dev' and server_group=test1 and load=complete"

Error: can not match: ''chicago-dev' and server_group=test1 and load=complete'

Query:
puppet query nodes "datacenter=chicago and environment="chicago-dev" and server_group=test1 and load=complete"

GOOD

Support for API v4 with Puppet DB v2.x

At our site we're still using Puppet DB v2.3.x as no Puppet 4 migration is yet possible for us.

When I try to use as this the code from the master branch I get an error with our Puppet DB v2.3.x. This error is due to the fact that all endpoints have been moved in v3.x.

I've created a quick work around that introduces a new parameter --puppetdb_version and now the code is using the good (old style) endpoint /v4/nodes/....

The next problem I got is with that simple query:

$ puppet query nodes 'Package[httpd]' --host puppetdb.example.net --port 8083 --debug --puppetdb_version 2
[...]
Debug: #<PuppetDB::Connection:0x00000001c90568>: PuppetDB query uri: /v4/nodes?query=[..same_information_as_above..]
Debug: #<PuppetDB::Connection:0x00000001c90568>: PuppetDB query: ["extract",["certname"],["in","certname",["extract","certname",["select_resources",["and",["=","type","Package"],["=","title","httpd"],["=","exported",false]]]]]]

Puppet DB just responds with this error

HTTP/1.1 400 Bad Request
[...]
Warning: v4 query API is experimental and may change without warning. For stability use the v3 api.

'path' is not a queryable object for null, known queryable objects are null
'value' is not a queryable object for null, known queryable objects are null

I know that in Puppet DB v2.x, API v4 is experimental but this seems the only way for us (at the moment) to have support for structured facts.

I don't really realize how difficult it would be to have support for both Puppet DB v2.x and Puppet DB v3.x but this would be very handy for us.

query_nodes spec.

Hi, guys.

I'm trying to test a module which there's many query_nodes functions. I wanna know how to test this with rspec, when i run rspec, it returns something like this:

  cannot load such file -- puppet/util/puppetdb

Do i have to install something?

This is Gemfile:

source 'https://rubygems.org'

gem 'rake'
gem 'puppet-lint'
gem 'rspec-puppet'
gem 'rspec-system-puppet'
gem 'puppetlabs_spec_helper'
gem 'travis'
gem 'travis-lint'
gem 'puppet-syntax'
gem 'puppet', ENV['PUPPET_VERSION'] || '~> 3.8.0'
gem 'vagrant-wrapper'
gem 'puppet-blacksmith'
gem 'beaker'
gem 'beaker-rspec'
gem 'ruby-puppetdb'

This is my rspec_helper:

require 'rspec-puppet'
require 'hiera'
require 'puppetlabs_spec_helper/puppetlabs_spec_helper'
require 'puppetlabs_spec_helper/module_spec_helper'

fixture_path = File.expand_path(File.join(__FILE__, '..', 'fixtures'))

RSpec.configure do |c|
  c.module_path = File.join(fixture_path, 'modules')
  c.manifest_dir = File.join(fixture_path, 'manifests')
  c.hiera_config = 'spec/fixtures/hiera/hiera.yaml'
end

Att,

Israel Ribeiro

Stuck getting started

I just installed your module and was trying to do some CLI queries, but I keep getting an error. For example:

$ puppet query nodes '(Package[httpd])'
Error: SSL_connect SYSCALL returned=5 errno=0 state=SSLv3 read finished A
Error: Try 'puppet help query nodes' for usage

I tried the --debug option and can see that this error occurs immediately after creating the connection to my PuppetDB server, but I'm lost otherwise.

How I can parse json answer in my puppet manifest?

Hi!
I am new in Puppet and Ruby, so I don't understand how can I parse json answer from this in my puppet manifest:
$hosts_to_monitoring = query_facts('Package["munin-node"]', ['fqdn', 'hostname', 'ipaddress'])
I want to use variables 'fqdn', 'hostname', 'ipaddress' it in my erb template.
If I print $hosts_to_monitoring in template, I receive string like this: host1fqdnhost1hostnamehost1ipaddress123host2fqdnhost2hostnamehost2ipaddress124
I tried to use function from puppet stdlib parsejson(), but it doesn't work.
Error: Could not retrieve catalog from remote server: Error 400 on SERVER: undefined method `read' for #Hash:0x7fc3b4e747d8

I would really appreciate your help

Enhancement: support structured facts

It seems not possible to query structured facts:

โ˜  puppet query nodes '(os.name=Debian)'
Error: can not match: '.name=Debian)'
Error: Try 'puppet help query nodes' for usage

support for 3.8.1

Since upgrading to pe-puppet 3.8.1 I get the following errors with manifests that include query calls

2015-12-11 11:21:12,918 ERROR [puppet-server] Puppet undefined method server_urls' for #<Puppet::Util::Puppetdb::Config:0x3e3886a> at /etc/puppetlabs/puppe t/environments/prd/current/puppet/application/nagioscore/manifests/params.pp:7 on node apddcungp002.apac.aon.bz 2015-12-11 11:21:12,929 ERROR [puppet-server] Puppet undefined methodserver_urls' for #Puppet::Util::Puppetdb::Config:0x3e3886a at /etc/puppetlabs/puppe
t/environments/prd/current/puppet/application/nagioscore/manifests/params.pp:7 on node apddcungp002.apac.aon.bz
/var/opt/lib/pe-puppet-server/jruby-gems/gems/ruby-puppetdb-2.1.0/lib/puppet/parser/functions/query_nodes.rb:28:in real_function_query_nodes' /opt/puppet/lib/ruby/site_ruby/1.9.1/puppet/parser/functions.rb:164:infunction_query_nodes'
/opt/puppet/lib/ruby/site_ruby/1.9.1/puppet/util/profiler/around_profiler.rb:58:in `profile'

puppetdb-1.1 compatibility

for now pdb emits warnings in puppetdb:

2013-01-31 14:55:07,446 WARN  [qtp361931841-7249] [http.server] Use of unversioned APIs is deprecated; please use /v1/nodes

new api should be probably used with configurable fallback to old api for folks who still stick to puppetdb-1.0.

How to append something to the fact that gets returned via hiera

Sorry to ask but been searching for the past 2-3 hours. Am trying to make my module manifests as generic as possible and store as much in hiera as I can.

How can I manipulate (add/remove text) the facts that get returned as part of a hiera lookup? For example, the mongo profile module I'm using looks for the following when setting up replica sets:

mongodb_replset_members:

  • 'iam-dev-modb01.example.com:27017'
  • 'iam-dev-modb02.example.com:27017'
  • 'iam-dev-modb03.example.com:27017'

So I came up with the following puppetdb hiera query, however I need to be able to add port 27017 to the end of every hostname/fqdn that gets returned from the query:
mongodb_replset_members::_nodequery: ['project=iam and tier=dev and role=modb']

Thanks

query_facts calls non-existent method "facts" of PuppetDB::Connection

The query_facts function makes a connection with the PuppetDB::Connection class, then attempts to call a 'facts' method when it makes its call. The method doesn't exist, which results in the following output:

Error: Evaluation Error: Error while evaluating a Function Call, undefined method `facts' for #PuppetDB::Connection:0x00000003207b98

Support for the v4 api ?

PuppetDB 3.1 no longer supports the v1, v2, and v3 API versions so I was wondering if there are plans to add support for v4.

PuppetDB query error 404 on puppet query events

Hi,

I'm having problems getting 'puppet query events' to work. I want to get all events from 'class[puppet]' in the last day.

puppetmaster  ~ # puppet query events --since='1 day ago' --until now 'class[puppet]'
Error: PuppetDB query error: [404] Not Found, query: ["and",[">","timestamp","2015-01-22T10:42:02.000Z"],["<","timestamp","2015-01-23T10:42:03.000Z"],["or",["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"],["=","certname","i-am-anonymized"]]]
Error: Try 'puppet help query events' for usage
puppetmaster ~ # 

certnames are anonymized

using:
puppetdbquery: 1.5.3 / be650dc
puppet opensource: 3.7.1
puppetdb: puppetdb-2.2.2-1.el6.noarch

I see no nothing related in puppetdb.log during query time.
I think I have the query right, I get partial results, put also an error which I cannot explain.

Any help will be really appreciated!

Martin

Getting 404 errors;

I know this is probably a config issue on my part, but haven't found a solution anywhere else.

I have two puppet servers. Both built from the Puppet Collection repo (puppet 4). One of them I installed puppetdb using the "install from packages" instructions, and the other I built from the "install via Puppet Module" instructions. In the system built from packages, puppetdbquery works from both the command line and from within manifests. On the system build from the puppetdb module, with puppetdbquery then installed, I am getting 404 errors from the command line:

$ puppet query nodes 'Package["puppet-agent"]'

Error: PuppetDB query error: [404] Not Found, query: ["in","name",["extract","certname",["select-resources",["and",["=","exported",false],["=","type","Package"],["=","title","puppet-agent"]]]]]
Error: Try 'puppet help query nodes' for usage

and the same manifests that work on system #1 are failing with this error:

Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Evaluation Error: Error while evaluating a Function Call, undefined method `server' for Puppet::Util::Puppetdb:Module at /etc/puppetlabs/code/environments/production/modules/wwwbayhostingnet/manifests/munin_master.pp:12:17 on node puppet2.bayhosting.net

In the above error, line 12 of the manifest is:

    $munin_nodes = query_nodes('Package["munin-node"]')

I have verified that I am running 1.6.1, and I have not been able to fine any relevant differences in the configuration of the systems. Do you have any pointers for fixing my config, or am I hitting some weird edge-case bug?

Forge

This is a great module. Thank you so much for writing it. Could you possibly put it on the Puppet Forge? This way other modules can have it as a dependency that the puppet module tool can resolve automatically.

Fail more gracefully if rest_client isn't installed

Right now the functions just require 'rest_client' at the top, which can raise an error if the function is present without the rest_client library being installed. The require should move into the functions, so that it will only fail if the function is actually used, rather than simply being loaded.

Even better, a rescue of that NameError with a more relevant Puppet::ParseError message would be nice, but that's just gravy.

The main reason for this is, for example, bootstrapping a master that's installing rest_client with puppet, so that it can successfully compile itself.

Thanks for building this, by the way! :)

Facts interpolation does not work in puppetdb backend

I'd like to discover ntp servers on the particular site. Fact site is the same for client and server.
It wokrs with query_nodes function
$res = query_nodes("Class[Mgmt] and Class[Ntp] and site=${::site}")

but not with puppetdb backend in hiera
json:
"ntp::servers::_nodequery": "Class[Ntp] and Class[Wg::Mgmt] and site=$::site"
Error 400 on SERVER: Error from DataBinding 'hiera' while looking up 'ntp::servers': can not match: '$::site' on node.....

Do you consider this is the issue? Or is there other way to do it?

Ruby example broken?

Unless I've missed a step along the way the Ruby example in the readme file is
broken on Puppet 4.3.0 / PuppetDB 3.2.0.

# rpm -qa | grep -iE ^puppet
puppet-agent-1.2.7-1.el7.x86_64
puppetlabs-release-pc1-1.0.0-1.el7.noarch
puppetdb-3.2.0-1.el7.noarch
puppetdb-termini-3.2.0-1.el7.noarch
puppetserver-2.1.2-1.el7.noarch

# bundle exec gem search --local

*** LOCAL GEMS ***

bundler (1.10.6)
facter (2.4.4)
hiera (3.0.5)
httparty (0.13.7)
json (1.8.3)
json_pure (1.8.3)
multi_xml (0.5.5)
puppet (4.3.0)
# bundle exec irb
irb(main):001:0> require 'puppet/face'
=> true
irb(main):002:0> Puppet.initialize_settings
=> [:debug, :info, :notice, :warning, :err, :alert, :emerg, :crit]
irb(main):003:0> Puppet::Face[:query, :current].nodes('(Package["mysql-server"] and architecture=amd64)')
Puppet::Error: Could not find Puppet Face query
    from /usr/local/share/gems/gems/puppet-4.3.0/lib/puppet/interface.rb:100:in `[]'
    from (irb):3
    from /usr/bin/irb:12:in `<main>'
irb(main):004:0>

Any advice how to proceed?

Cache puppetdb query functions

I think that it is reasonable to add an option to the puppetdb query functions to cache the last returned value by the query.

This is useful in cases where we would like to avoid failures in puppet agent runs during puppetdb temporary unavailability.

For example, I would like to fail the following puppet code only if it didn't return value for the past hour:

$proxy_ip = query_nodes('Class["Proxy::Server"]', 'ec2_public_ipv4')

Otherwise, I would like to receive the last successful entry for this fact.

DB Query with Hiera dictionary lookup

When we have a dictionary in heira like:
varnish_pool:
port: '8080'
servers::_nodequery:
query: 'Class[Varnish]'
fact: 'hostname'

and we do a hiera lookup for "varnish_pool", response i get is:
{"port" => "8080",
"servers::_nodequery"=>
{"query"=>
"Class[Varnish]",
"fact"=>"hostname"}}
The puppet DB query inside a hash does not resolve.

Top scoping a class in a query returns empty

Eg

Works:
$output = query_nodes("bitnet_environment_id="${::bitnet_environment_id}" and Class[bitnet_rabbitmq]", ipaddress)

Doesn't work (empty string):
$output = query_nodes("bitnet_environment_id="${::bitnet_environment_id}" and Class[::bitnet_rabbitmq]", ipaddress)

Query by resource tag

I'd like to do this query

Class[Profile::Elasticsearch] { tag="es_cluster_name_xyz" }

But the resulting query treats it like a parameter, e.g.

["=",["parameter","tag"],"es_cluster_name_xyz"]

It would be great if it could understand tag and do this instead

["=","tag","es_cluster_name_xyz"]

Can't query for nodes that have dashes in the value of a fact

I can't seem to find a way to query the nodes that match a fact query using either 'puppet query nodes' or the puppet function when the fact value I'm searching for has dashes (-) in them.

Eg.

puppet query nodes some_fact=some-value-with-dashes
Error: can not match: '-value-with-dashes'
Error: Try 'puppet help query nodes' for usage

I've tried various ways of escaping and double quoting the entire string with no luck. The puppet function throws a similar error.

Possible incorrect URL encoding of query parameters

When performing a query like "Class['Rabbitmq']{erlang_cookie='jkdgfh+dhj'}" the CURL output from puppetdb shows the cookie value populated correctly, but a puppet query nodes .. command fails to find the nodes. Removing the "+" from the cookie corrects this issue. I suspect a URL encoding problem.

puppet query facts error - error: [400] Unknown Version, query: null

I am using puppetserver v2.1.1 with puppetdb v3.1.0 (with postgresql backend) on a CentOS 7.1 server. Commands puppet query nodes and puppet query events is working fine but somehow puppet query facts throws below error. Not sure, if I am missing something.

I sought some help on IRC channel, and was advised by @kbarber that the URL is being constructed incorrectly. Please see this.

Please see below logs.

# puppet query nodes '(Package["vim"] and architecture=x86_64)'
box28.test.com
box32.test.com
# 
# puppet query events '(fqdn~"test.com" and Package["vim"] and architecture=x86_64)' --since='1 minute ago'
box28.test.com: 2015-10-14T11:17:37.108Z: Notify[Setting up basic OS Configurations]/message (absent -> Setting up basic OS Configurations): defined 'message' as 'Setting up basic OS Configurations'
box32.test.com: 2015-10-14T11:17:43.268Z: Notify[Setting up basic OS Configurations]/message (absent -> Setting up basic OS Configurations): defined 'message' as 'Setting up basic OS Configurations'
#

# puppet query facts '(fqdn~".*")' --facts osfamily,ipaddress,kernel
OR
# puppet query facts '(Package["vim"] and architecture=x86_64)'
Error: PuppetDB query error: [400] Unknown Version, query: null
Error: Try 'puppet help query facts' for usage
#

I have also tried to use it in a manifest as below, the error remains the same.

query_facts('Class[Dns]', ['osfamily', 'ipaddress'])

Database tables are populated well.

puppetdb=> select * from fact_values limit 2;
 id |                 value_hash                 | value_type_id | value_integer | value_float |              value_string               | value_boolean |                   value
----+--------------------------------------------+---------------+---------------+-------------+-----------------------------------------+---------------+-------------------------------------------
  1 | \x9d3ea577cd7f8ee06f6a60dca6d84b477ff2846d |             0 |               |             | 07/31/2013                              |               | "07/31/2013"
  2 | \xb7b08b770b277ec9042c222d2016751899c63805 |             0 |               |             | ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff |               | "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
(2 rows)

puppetdb=>

Allow for a retrieval of all active nodes

Prior to version 0.1.0, you could retrieve the list of all active nodes by doing something like this:

$active_nodes = pdbnodequery(['=',['node','active'],true])

With the changes introduced in 5426aa7, you now have to do this to achive the same thing:

$active_nodes = pdbnodequery_all(['=',['node','active'],true])

However, it would be nice to only have to do this:

$active_nodes = pdbnodequery()

Or, I would be happy with:

$active_nodes = pdbnodequery([])

The last two examples fail with this error message:

err: Could not retrieve catalog from remote server: Error 400 on SERVER: PuppetDB query error: [500] Server Error at /etc/puppet/path/to/some/manifest/init.pp:47 on node server.example.com

There's obviously a working workaround, so I can understand if you don't want to update the code for this edge case. If that's the case, would you accept a pull request to update the documentation with an example for how to retrieve a list of active nodes?

fails on dashes in fact names

$ sudo puppet query nodes 'kernelrelease=3.10.0-229.1.2.el7.x86_64'
Error: can not match: '.0-229.1.2.el7.x86_64'
Error: Try 'puppet help query nodes' for usage

intermittent compile problems with pdbquery

once per few compilations i encounter error:

Jul 31 15:07:29 repo puppet-agent[23137]: Could not retrieve catalog from remote server: Error 400 on SERVER: Cannot find definition Class at /etc/puppet/site/manifests/nodes.pp:45 on node repo

this manifest is simply:

$ cat -n manifests/nodes.pp |grep 45
45 include pki::bundle

i think this is related to pdb functions as it seem to only appear on nodes which use manifest that runs pdb queries.

in particular i have such query:

$repos = pdbresourcequery(['and',
                            ['=',['node','active'],true],
                            ['=','type','Yumrepo'],
                            ['=',['parameter','enabled'],'1'],
                            [ 'not', ['=','tag','dont-sync']]
                          ])

have you encountered anything similiar?

query_facts returns invalid format

So I'm afraid I jumped a bit too soon on the query_facts working correctly. It returns (according to Puppet) a Tuple of Structs. This needs to be converted into a usable hash. I am working on a fix in my fork for this now and will submit over once it's complete.

How to return hash rather than array from hiera

Am trying to make use of this hosts module via hiera: https://forge.puppetlabs.com/ghoneycutt/hosts

Specifically the following method:
hosts::host_entries:
'servicename.example.com':
ip: '10.0.0.5'
host_aliases:
- 'servicename'

Here is my attempt using puppetdbquery:
hosts::host_entries::_nodequery:
query: 'location=corp and tier=dev'
fact: 'ipaddress'

And this is the output I'm getting on a node:
"Could not retrieve catalog from remote server: Error 400 on SERVER: ["10.0.0.28"] is not a Hash. It looks to be a Array at...."

Any suggestions? I'd prefer to set the query via hiera as my role/profile manifests are very generic and hiera dependent.

resource queries always return all resources on a node

Hello,

thanks for this nice module. I would like to use it to query for resources. Maybe I'm doing something wrong, but I can't find what at first sight. Maybe my intepretation is wrong. Anyway, here it goes.

Every resource-query is converted to the following format (from spec-helper):

it 'should parse resource queries for exported resources' do
parser.parse('@@file[foo]').should eq ['in', 'certname', ['extract', 'certname', ['select_resources', ['and', ['=', 'type', 'File'], ['=', 'title', 'foo'], ['=', 'exported', true]]]]]
end

The problem is that it is converted to an "in ... extract ..."-query, where in is always "certname" en extract is always "certname". So, it returns all resources from the node where the resource is located and not only the resource I want, expressed correctly in the subquery (select_resources)-part.

Accordig to my intepretation, the whole "in", "extract" is not needed.

I was also trying to find a way to specify a raw query, which should be possible according to the readme, but I always get an error ...

Kind regards,

Michel

invalid byte sequence in US-ASCII

I submoduled puppetdbquery into my puppet repo, but I don't seem to be able to get it to work:

Submodule 'modules/puppetdbquery' (git://github.com/dalen/puppet-puppetdbquery.git) registered for path 'modules/puppetdbquery'
Cloning into 'modules/puppetdbquery'...
remote: Counting objects: 749, done.
remote: Compressing objects: 100% (357/357), done.
remote: Total 749 (delta 297), reused 720 (delta 275)
Receiving objects: 100% (749/749), 115.00 KiB, done.
Resolving deltas: 100% (297/297), done.
Submodule path 'modules/puppetdbquery': checked out '5b3c94b27f78c59287f86c70f59c56a3097f9ed0'

# echo $RUBYLIB

# export RUBYLIB=modules/puppetdbquery/lib

# puppet help query
Error: invalid byte sequence in US-ASCII
Error: Try 'puppet help help help' for usage

Not quite sure what I'm missing here, and I don't see any other help guide These were ran from the puppetmaster. When running from my puppetdb I get the same thing.

Support new versions of the deprecated functions

I really like using the old deprecated functions that work with the v1 api because it provides a direct interface for querying PuppetDB instead of using the infix query language provided by this module. Is there any chance that this project would accept a PR adding a generic 'pdbquery' function that accepts the endpoint and query? I'd be glad to do the work. It would just be a nice alternative for those of us who like the S-expression query language.

Puppet.initialize_settings call needed in query.rb for face to work from Ruby script

When attempting to use the query face from a simple ruby script, e.g.

require 'puppet/face'
print Puppet::Face[:query, "1"].nodes('(manufacturer="Dell Inc.")').join ", "

... I get an error as follows:

/usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1292:in `convert': Error converting value for param 'localcacert': Error converting value for param 'certdir': Error converting value for param 'ssldir': Could not find value for $confdir (Puppet::Settings::InterpolationError)
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1283:in `gsub'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1283:in `convert'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1264:in `interpolate'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1289:in `convert'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1283:in `gsub'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1283:in `convert'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1264:in `interpolate'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1289:in `convert'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1283:in `gsub'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1283:in `convert'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1264:in `interpolate'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:1029:in `value'
    from /usr/lib/ruby/site_ruby/1.8/puppet/settings.rb:118:in `[]'
    from /usr/lib/ruby/site_ruby/1.8/puppet.rb:70:in `[]'
    from /usr/lib/ruby/site_ruby/1.8/puppet/ssl/validator/default_validator.rb:22:in `initialize'
    from /usr/lib/ruby/site_ruby/1.8/puppet/ssl/validator.rb:27:in `new'
    from /usr/lib/ruby/site_ruby/1.8/puppet/ssl/validator.rb:27:in `default_validator'
    from /usr/lib/ruby/site_ruby/1.8/puppet/network/http_pool.rb:36:in `http_instance'
    from /etc/puppet/modules/puppetdbquery/lib/puppetdb/connection.rb:59:in `query'
    from /etc/puppet/modules/puppetdbquery/lib/puppet/face/query.rb:70:in `nodes implementation, required on Ruby 1.8'
    from /usr/lib/ruby/site_ruby/1.8/puppet/interface/action.rb+eval[wrapper]:242:in `__send__'
    from /usr/lib/ruby/site_ruby/1.8/puppet/interface/action.rb+eval[wrapper]:242:in `nodes'
    from ./test-query.rb:23

I believe this is due to a missing Puppet.initialize_settings call in query.rb.

I'll make a pull request shortly with this minor change included.

Cheers!

Feature: pdbnodequery

  • similar request to add array support found in to #3
  • simple POC to obtain server_class + ip address, and add content to a file
  • which is queried by fwadmin for acls
  • ideally, pass server_role as an array,
  • to generate a file with all required server roles, however
  • pdbnodequery's 2nd arg does not seem to work with an array,
  • for example:
    $server_role = [ 'FreeBSD_Nagios_Server', 'Ubuntu_PuppetMaster_Server' ]
    $servers = pdbnodequery(['=',['fact','server_class'], $server_role])
  • sample class content:

$server_role = 'Ubuntu_PuppetMaster_Server'
$servers = pdbnodequery(['=',['fact','server_class'], $server_role ]) # return fqdn of requested role

$servers_ip = pdbfactquery([$servers], 'ipaddress') # return ipaddress of requested fqdn

notify { $servers_ip: }

file { '/root/fw-srvops-addressbook':
replace => true,
content => inline_template('<% servers_ip.each do |entries| -%><%= server_role -%> : <%= entries.map { |i| "" + i.to_s + "" }.join(" ") %><% end -%>'),
}

  • sample file output without an array:
    Ubuntu_PuppetMaster_Server : 192.168.1.3 192.158.1.4
  • expected output with an array:
  • FreeBSD_Nagios_Server : 192.168.1.13 192.168.1.14 192.168.1.15
  • Ubuntu_PuppetMaster_Server : 192.168.1.3
  • actual output with an array:
    FreeBSD_Nagios_ServerUbuntu_PuppetMaster_Server :

Seems to be broken with puppet 3.0.0-rc5

I am working on troubleshooting why I cant get puppetdbquery working with puppet 3.0.0-rc5. I am getting the following error message.

err: Could not retrieve catalog from remote server: Error 400 on SERVER: undefined method `start' for #Puppet::Network::HTTP::Connection:0x7fa6e25db7c8

I will continue to try and figure this out, but any help or pointers would be very nice.

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.