Search code examples
puppet

Collect the basic instace details from puppetdb like the hostname and IP based on some facts value


How can i develop a script which automatically runs and fetches the details from puppetdb ? I am a newbie to puppet .Basically I would like to collect the inventory from puppetdb based on factor values like "web server" ,"app server" etc. I use opensource puppet.


Solution

  • querying puppetdb is as easy as running curl.

    For example, if you have a fact named $role and some nodes have the role "web server" you can get an inventory dump of all nodes with that role running:

     curl -G -H  "Accept: application/json" 'http://localhost:8080/pdb/query/v4/inventory' --data-urlencode 'query=["=",["fact","role"], "web server"]' |jq '.'
    

    Now, maybe you only want to know the hostname of servers and send each inventory to another application, that would be something like this:

    #!/bin/bash
    # Iterate over nodes if $role 'web server'
    curl -s -G -H  "Accept: application/json" 'http://localhost:8080/pdb/query/v4/nodes' --data-urlencode 'query=["=",["fact","role"], "web server"]' | jq -r '.[]|[ .certname ]| @tsv' |
    while IFS=$'\t' read -r host; do
      echo "Do something with $host"
      # Save one dump per host
      curl -s -G -H  "Accept: application/json" 'http://localhost:8080/pdb/query/v4/inventory' --data-urlencode 'query=["=","certname","'${host}'"]' > "node-${host}.inventory.log"
    done
    

    This are very basic examples, their api is very powerful and very simple to use, you can query anything (facts, resources, catalogs, inventories) and doing even complex queries like speaking to a MySQL server, check their tutorial here: https://puppet.com/docs/puppetdb/5.1/api/query/tutorial.html .