繁体   English   中英

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

[英]How do I write a custom function in Puppet 3?

我必须在工作中使用一个利用Puppet 3.6的工具(我对建议其他版本的答案不感兴趣,我坚持给出的内容!)。 我受此工具的限制,无法将所有功能都放在一个清单中。 我找不到有关如何创建自定义函数的Puppet 3语法,因为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...
}

但是,当我这样做时,出现错误:

错误:无法为环境生产解析:“ check_string”处的语法错误; 在/path/to/my_manifest.pp的预期')':4

请问正确的语法是什么?

我通过在模块中的以下位置添加一个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 :

在人偶清单中,只需使用keys($hash)调用该函数

希望以此为例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM