5

I have to write a function that will, in order, perform the following to read the value of a variable:

  • Check if there is a facter variable defined. If not,
  • Read the value of the variable from Hiera. If not,
  • Use a default value.

I have managed to do it in my Puppet script using this if condition.

  # foo is read from (in order of preference): facter fact, hiera hash, hard coded value
  if $::foo == undef {
     $foo = hiera('foo', 'default_value')
  } else {
     $foo = $::foo
  }

But I want to avoid repeating this if condition for each variable I wish to parse in this manner, and therefore thought of writing a new Puppet function of the format get_args('foo', 'default_value') which will return me the value from

  1. a facter fact if it exists,
  2. a hiera variable, or
  3. just return default_value.

I know that I can use lookupvar to read a facter fact from a ruby function. How do I read a hiera variable from my Puppet ruby function?

Holger Just
  • 52,918
  • 14
  • 115
  • 123
Siddhu
  • 888
  • 3
  • 9
  • 28

1 Answers1

3

You can call defined functions using the function_ prefix.

You have found the lookupvar function already.

Putting it all together:

module Puppet::Parser::Functions
  newfunction(:get_args, :type => :rvalue) do |args|
    # retrieve variable with the name of the first argument
    variable_value = lookupvar(args[0])
    return variable_value if !variable_value.nil?
    # otherwise, defer to the hiera function
    function_hiera(args)
  end
end
Felix Frank
  • 8,125
  • 1
  • 23
  • 30
  • Thanks, Felix, that's very useful. However, when doing this, I get a different error. I have a second argument I need to pass to the function (the default value), and when I do that like so class myclass($foo=get_args('foo', 'monkeypatch')) { } I then get an error saying, "custom functions must be called with a single array that contains the arguments". I am running Puppet 3.6.2 with Ruby 1.8.7. This is probably a separate SO question. – Siddhu Aug 15 '14 at 12:22
  • 1
    Weird. Works For Me: `puppet apply -e '$foo = "bar" $bar = get_args("foobar","default") notify { $bar: }'` - Raises no exception, output is 'default'. – Felix Frank Aug 15 '14 at 12:26
  • Felix, it was because instead of calling ``function_hiera(args)``, I was calling ``function_hiera(args[0], args[1])``. The stacktrace was spectacularly useless; which is whY I couldn't figure out it was my Ruby code that was the problem. Thanks for your help! – Siddhu Aug 15 '14 at 12:34
  • 4
    FWIW, new Puppet 4.x convention is `call_function('hiera', *args)`. ([ref1](http://grokbase.com/t/gg/puppet-users/155pjs9cm3/calling-hiera-functions-from-inside-ruby-templates-broken-in-puppet-4-x), [ref2](http://docs.puppetlabs.com/puppet/4.3/reference/yard/Puppet/Pops/Functions/Function.html#call_function-instance_method)) – Amir Feb 29 '16 at 20:35