如何在Puppet 3中编写自定义函数?

时间:2018-01-12 09:00:36

标签: ruby puppet

我必须在工作中使用一个使用Puppet 3.6的工具(我对建议其他版本的答案不感兴趣,我对我给出的内容感到困惑!)。我受此工具的限制,将我的所有功能都放入一个清单中。我无法找到Puppet 3的语法来了解如何创建自定义函数,因为docs for Puppet 3 Functions只有一个重定向到v5.6文档的通用链接。

我必须在检查是否存在非法字符时解析一些输入。

define my_module::my_manifest($param1, $param2) {
    # $param1 & $param2 are passed to this manifest by the tool I'm working with

    function check_for_illegal_chars(String $check_string) {
         $illegal_chars = "[&|;]"
         if $check_string =~ $illegal_chars {
             fail("Illegal char(s) detected in '${check_string}', cannot contain any of '${illegal_chars}'")
         }
    }

    # sample usage
    check_for_illegal_chars($param1)

    # rest of my_manifest...
}

然而,当我这样做时,我收到一个错误:

  

错误:无法解析环境生成:语法错误at   ' check_string&#39 ;;预期')'在/path/to/my_manifest.pp:4

请问正确的语法是什么?

1 个答案:

答案 0 :(得分:1)

我是通过将ruby文件添加到模块中的以下位置来完成此操作的:lib/puppet/parser/functions/keys.rb

在我的情况下,我需要一个函数来获取密钥,因为我使用的是旧版本(与我相信版本相同)。 keys.rb文件如下所示:

#
# keys.rb
#

module Puppet::Parser::Functions
  newfunction(:keys, :type => :rvalue, :doc => <<-EOS
Returns the keys of a hash as an array.
    EOS
  ) do |arguments|

    raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1

    hash = arguments[0]

    unless hash.is_a?(Hash)
      raise(Puppet::ParseError, 'keys(): Requires hash to work with')
    end

    result = hash.keys

    return result
  end
end

# vim: set ts=2 sw=2 et :

在puppet manifest中,只需使用keys($hash)

调用该函数即可

希望这有助于作为一个例子。

相关问题