Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a Hiera value from a Puppet function?

Tags:

ruby

puppet

hiera

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?

like image 465
Siddhu Avatar asked Oct 20 '22 03:10

Siddhu


1 Answers

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
like image 111
Felix Frank Avatar answered Oct 23 '22 04:10

Felix Frank