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

Ruby 如何从Puppet函数读取Hiera值?,ruby,puppet,hiera,Ruby,Puppet,Hiera,我必须编写一个函数,以便执行以下操作来读取变量的值: 检查是否定义了因子变量。如果没有, 从Hiera读取变量的值。如果没有, 使用默认值 我已经在我的木偶脚本中使用了这个if条件 # foo is read from (in order of preference): facter fact, hiera hash, hard coded value if $::foo == undef { $foo = hiera('foo', 'default_value') }

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

  • 检查是否定义了因子变量。如果没有,
  • 从Hiera读取变量的值。如果没有,
  • 使用默认值
我已经在我的木偶脚本中使用了这个if条件

  # 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
  }
但我希望避免对每个希望以这种方式解析的变量重复这个if条件,因此考虑编写一个新的Puppet函数,其格式为
get_args('foo','default_value')
,它将从

  • 一个事实,如果它存在
  • hiera变量,或
  • 只需返回
    默认值

  • 我知道我可以使用
    lookupvar
    从ruby函数中读取事实。如何从Puppet ruby函数中读取hiera变量?

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

    您已经找到了
    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
    

    谢谢,菲利克斯,这很有用。但是,在执行此操作时,我得到了一个不同的错误。我还有第二个参数需要传递给函数(默认值),当我像myclass($foo=get_args('foo','monkeypatch')){}这样做时,我会得到一个错误,说“必须使用包含参数的单个数组调用自定义函数”。我正在用Ruby 1.8.7运行Puppet 3.6.2。这可能是一个单独的问题,很奇怪。适用于我:
    puppet apply-e'$foo=“bar”$bar=get_args(“foobar”,“default”)notify{$bar:}'
    -没有引发异常,输出是“default”。Felix,这是因为我没有调用
    函数_hiera(args)
    ,而是调用
    函数_hiera(args[0],args[1])
    。stacktrace毫无用处;这就是为什么我不知道问题出在我的Ruby代码上。谢谢你的帮助!FWIW,新的Puppet 4.x约定是调用函数('hiera',*args)。(, )