如何从Puppet函数中读取Hiera值?

Sid*_*dhu 5 ruby puppet hiera

我必须编写一个函数,按顺序执行以下操作来读取变量的值:

  • 检查是否定义了一个facter变量.如果不,
  • 从Hiera读取变量的值.如果不,
  • 使用默认值.

我已经设法使用此if条件在我的Puppet脚本中执行此操作.

  # 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
  }
Run Code Online (Sandbox Code Playgroud)

但是我想避免重复这个,如果我希望以这种方式解析的每个变量的条件,因此想到写一个格式的新Puppet函数get_args('foo', 'default_value'),它将返回我的值

  1. 一个事实,如果它存在,
  2. 变量变量,或
  3. 刚刚返回default_value.

我知道我可以用来lookupvar从ruby函数中读取一个因素.如何从我的Puppet ruby​​函数中读取hiera变量?

Fel*_*ank 3

您可以使用function_前缀调用定义的函数。

lookupvar已经找到了该功能。

把它们放在一起:

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
Run Code Online (Sandbox Code Playgroud)

  • FWIW,新的 Puppet 4.x 约定是“call_function('hiera', *args)”。([参考1](http://grokbase.com/t/gg/puppet-users/155pjs9cm3/calling-hiera-functions-from-inside-ruby-templates-broken-in-puppet-4-x),[参考2 ](http://docs.puppetlabs.com/puppet/4.3/reference/yard/Puppet/Pops/Functions/Function.html#call_function-instance_method)) (4认同)