Skip to content

Instantly share code, notes, and snippets.

@johann8384
Created November 5, 2013 18:53
Show Gist options
  • Save johann8384/7324073 to your computer and use it in GitHub Desktop.
Save johann8384/7324073 to your computer and use it in GitHub Desktop.
Exported vars through PuppetDB I find it useful sometimes to be able to share bits of information between nodes. For example, I can have all of the nodes in a cluster register their IP addresses.
::magic::register { 'hadoop_datanode_fqdn':
value => $fqdn,
}
::magic::register { 'hadoop_datanode_ip':
value => $ip,
}
$reg = query_registrations('hadoop_datanode_fqdn')
# Now $reg has an array of all of the FQDN's of the hadoop datanodes
Puppet::Parser::Functions::newfunction(:query_registrations, :type => :rvalue) do |args|
require 'puppet'
require 'puppet/util/puppetdb'
host = Puppet::Util::Puppetdb.server || 'localhost'
port = Puppet::Util::Puppetdb.port || 8080
title = args[0]
tag = args[1]
raise(Puppet::Error, 'Title is a required parameter') unless title
if tag.to_s.empty?
tag = title
end
# https://github.com/ripienaar/ruby-puppetdb
# https://github.com/ripienaar/ruby-puppetdb/blob/master/lib/puppetdb.rb#L196
def query_puppetdb(host, port, query)
require 'puppet/network/http_pool'
http = Puppet::Network::HttpPool.http_instance(host, port)
headers = { "Accept" => "application/json" }
if query == :empty
resp, data = http.get("/nodes", headers)
return PSON.parse(data)
else
type = query.keys.first
case type
when "resources"
query = "/resources?query=%s" % URI.escape(query[type].to_pson)
resp, data = http.get(query, headers)
return PSON.parse(data)
when "nodes"
query = "/nodes?query=%s" % URI.escape(query[type].to_pson)
resp, data = http.get(query, headers)
return PSON.parse(data)
when "facts"
query = "/facts/#{query[type]}"
resp, data = http.get(query, headers)
return PSON.parse(data)
end
end
end
def extract_registrations(nodes)
registrations = Array.new
nodes.each do |resources|
simple_resources = simplify_resource(resources)
registrations.push(simple_resources['parameters']['message'])
end
registrations
end
# converts a resource_hash returned by puppetdb into something
# much simpler
def simplify_resource(resource_hash)
{
'parameters' => resource_hash['parameters'],
'hash' => resource_hash['resource'],
'certname' => resource_hash['certname']
}
end
nodes = query_puppetdb(host, port, {"resources" => ["and", ["=", "type", "Notify"], ["=", "title", title], ["=", "tag", tag]]})
extract_registrations(nodes)
end
define magic::register($value, $customtag=$title) {
@@notify { "${customtag}_${value}":
message => $value,
tag => $customtag,
}
}
@johann8384
Copy link
Author

This is based on some magic I learned from Andrew Gaffney many years ago, I had to write a new function to collect the registrations from PuppetDB though, his implementation used storeconfigs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment