簡體   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