|
| 1 | +# |
| 2 | +# params_lookup.rb |
| 3 | +# |
| 4 | +# This function lookups for a variable value in various locations |
| 5 | +# following this order |
| 6 | +# - Hiera backend, if present |
| 7 | +# - ::varname (if option abs_lookup is true) |
| 8 | +# - ::modulename_varname |
| 9 | +# - ::modulename::params::varname |
| 10 | +# - The value set with the "default" option |
| 11 | +# |
| 12 | +# It's based on a suggestion of Dan Bode on how to better manage |
| 13 | +# Example42 NextGen modules params lookups. |
| 14 | +# Code has been written with the decisive help of Brice Figureau, |
| 15 | +# Peter Meier and Ohad Levy during the Fosdem 2012 days (thanks guys) |
| 16 | +# |
| 17 | +# Alessandro Franceschi al@lab42.it |
| 18 | +# |
| 19 | +module Puppet::Parser::Functions |
| 20 | + newfunction(:params_lookup, :type => :rvalue, :doc => <<-EOS |
| 21 | +This fuction looks for the given variable name in a set of different sources: |
| 22 | +- Hiera, if available ('varname' if option abs_lookup is true) |
| 23 | +- Hiera, if available ('modulename_varname') |
| 24 | +- ::varname (if option abs_lookup is true) |
| 25 | +- ::modulename_varname |
| 26 | +- ::modulename::params::varname |
| 27 | +- The value set with the "default" option |
| 28 | + EOS |
| 29 | + ) do |arguments| |
| 30 | + |
| 31 | + raise(Puppet::ParseError, "params_lookup(): Define at least the variable name " + |
| 32 | + "given (#{arguments.size} for 1)") if arguments.size < 1 |
| 33 | + |
| 34 | + value = :undef |
| 35 | + var_name = arguments[0] |
| 36 | + options = { 'default' => :undef, 'abs_lookup' => false }.merge(arguments[1] || {}) |
| 37 | + module_name = parent_module_name |
| 38 | + if Puppet::Parser::Functions.function('hiera') |
| 39 | + value = function_hiera("#{var_name}",:undef) if options["abs_lookup"] |
| 40 | + value = function_hiera("#{module_name}_#{var_name}",:undef) |
| 41 | + end |
| 42 | + if value == :undef |
| 43 | + value = undef_as(:undef, lookupvar("::#{var_name}")) if options["abs_lookup"] |
| 44 | + value = undef_as(:undef, lookupvar("::#{module_name}_#{var_name}")) |
| 45 | + value = undef_as(:undef, lookupvar("::#{module_name}::params::#{var_name}")) if value == :undef |
| 46 | + value = undef_as(:undef, options["default"]) if value == :undef |
| 47 | + end |
| 48 | + |
| 49 | + return value |
| 50 | + end |
| 51 | +end |
| 52 | + |
| 53 | +# vim: set ts=2 sw=2 et : |
0 commit comments