Skip to content

Instantly share code, notes, and snippets.

@lukebigum
Last active December 23, 2015 09:41
Show Gist options
  • Save lukebigum/0239484012ef02516b95 to your computer and use it in GitHub Desktop.
Save lukebigum/0239484012ef02516b95 to your computer and use it in GitHub Desktop.
Substitute and Replicate Array
module Puppet::Parser::Functions
newfunction(:subs_repl_array, :type => :rvalue, :doc => <<-'ENDHEREDOC'
Takes an Array of strings and a hash of strings, then for every element in the array,
it goes searching the hash values for the string 'SUBS' and replaces it with the array element.
The value returned is itself an array of hashes, where each hash element is a copy of the input hash
with the relevant substitution made. The number of hashes returned is the same as the input array.
$out_array = subs_repl_array($in_array, $in_hash)
This is only useful in some complex puppet manifests where you need to pass an array of hashes
to configure things. One such defined type is 'collectd::plugin::tail::file', where you pass
in a number of Regex matches. Here is an example:
$in_array = [ 'woof', 'cows', 'dogs' ]
$in_hash = {
regex => "^.*SUBS.*",
dstype => 'CountInc',
type => 'counter',
intance => 'SUBS_count',
}
$out_hash = subs_repl_array($in_array, $in_hash)
The result $out_hash would look like this:
$out_array = [
{
regex => "^.*woof.*",
dstype => 'CountInc',
type => 'counter',
intance => 'woof_count',
},
{
regex => "^.*cows.*",
dstype => 'CountInc',
type => 'counter',
intance => 'cows_count',
},
{
regex => "^.*dogs.*",
dstype => 'CountInc',
type => 'counter',
intance => 'dogs_count',
},
]
ENDHEREDOC
) do |args|
raise Puppet::ParseError, ("subs_repl_array(): Wrong number of arguments (#{args.length}; must be = 2)") unless args.length == 2
in_array = args[0]
in_hash = args[1]
unless in_array.is_a?(Integer) || args[0].is_a?(Array)
raise Puppet::ParseError, ("subs_repl_array(): the first argument must be an Array")
end
unless in_hash.is_a?(Hash)
raise Puppet::ParseError, ("subs_repl_array(): the second argument must be a Hash")
end
result = Array.new
c = 0
in_array.each do |a|
h = Hash.new
in_hash.each do |k,v|
h[k] = v.gsub('SUBS', a)
end
result[c] = h
c = c+1
end
return result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment