#!/usr/bin/env ruby require 'rubygems' require 'puppetdb/connection' require 'optparse' require 'net/http' require 'net/https' options = { host: 'puppetdb', port: 443, fact: nil, query: nil, ssl: true, print: false } opt = OptionParser.new opt.on('--host [PUPPETDB]', '-H', "Host running PuppetDB (#{options[:host]})") do |v| options[:host] = v end opt.on('--port [PORT]', '-p', Integer, "Port PuppetDB is running on (#{options[:port]})") do |v| options[:port] = v end opt.on('--query [QUERY]', '-q', 'Query String') do |v| options[:query] = v end opt.on('--facts [FACT]', '-f', 'Comma separated list of facts') do |v| options[:facts] = v.split ',' end opt.on('--timeout [SECONDS]', '-t', 'PuppetDB read timeout') do |v| options[:timeout] = v.to_i end opt.on('--nossl', 'Disable SSL') do |v| options[:ssl] = false end opt.on('--print', 'Only print query') do |v| options[:print] = true end opt.parse! options[:query] ||= ARGV[0] abort 'Please specify a query' unless options[:query] puppetdb = PuppetDB::Connection.new(options[:host], options[:port]) parser = PuppetDB::Parser.new http = Net::HTTP.new(options[:host], options[:port]) http.use_ssl = options[:ssl] http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.read_timeout = options[:timeout] if options[:timeout] if options[:print] query = parser.parse(options[:query]) puts query.to_json elsif options[:facts] query = parser.facts_query(options[:query], options[:facts]) parser.facts_hash(puppetdb.query(:facts, query, http)).each_value do |host| print options[:facts].collect { |f| host[f] if host.include? f }.join(',') + "\n" end else query = parser.parse(options[:query]) results = puppetdb.query(:nodes, query, http) hosts = results.collect { |host| host['certname'] } hosts.each { |host| print host + "\n" } end