Skip to content

Instantly share code, notes, and snippets.

@pbrit
Created May 19, 2015 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbrit/9e2387e8a2a139706bb9 to your computer and use it in GitHub Desktop.
Save pbrit/9e2387e8a2a139706bb9 to your computer and use it in GitHub Desktop.
Puppet func, lookups array of hashes by key and value
# Put in $module/lib/puppet/parser/functions/hash_detect.rb
module Puppet::Parser::Functions
newfunction(:hash_detect, :type => :rvalue, :doc => <<-EOS
Take array of hashes and key and value for search and optional key whom value should be returned.
EOS
) do |arguments|
haystack = arguments[0]
key = arguments[1]
value = arguments[2]
final_key = arguments[3]
needle = haystack.detect do |hash|
raise Puppet::ParseError, "Provided hash doesn't have key=#{key}" unless hash.has_key?(key)
hash[key] == value
end
raise Puppet::ParseError, "Provided hash doesn't have tupple (#{key},#{value})" unless needle
if final_key
raise Puppet::ParseError, "Provided hash doesn't have key=#{final_key}" unless needle.has_key?(final_key)
needle[final_key]
else
needle
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment