Puppet 简明教程
Puppet - Custom Functions
正如前一章所述,函数为用户提供了开发自定义函数的权限。Puppet 可以通过使用自定义函数来扩展其解释能力。自定义函数有助于增强和扩展 Puppet 模块和清单文件的能力。
As described in the previous chapter, function provides the user with a privilege of developing custom functions. Puppet can extend its interpretation power by using custom functions. Custom function helps in increasing and extending the power of Puppet modules and manifest files.
Writing Custom Function
在编写函数之前,有一些事项需要牢记。
There are few things which one needs to keep in mind before writing a function.
-
In Puppet, functions are executed by compilers which means all the functions run on Puppet master and they don’t need to deal with any of the Puppet client for the same. Functions can only interact with agents, provided information is in the form of facts.
-
The Puppet master catches custom functions which means that one needs to restart the Puppet master, if one does some changes in Puppet function.
-
Function will be executed on the server which means any file that the function needs should be present on the server, and one can’t do anything if the function requires direct access to the client machine.
-
There are completely two different type of functions available, one is the Rvalue function which returns the value and the statement function which does not return anything.
-
The name of the file containing function should be the same as the name of the function in the file. Otherwise, it will not get loaded automatically.
Location to Put Custom Function
所有自定义函数都作为单独的 .rb 文件实现,并分布在模块中。需要将自定义函数放入 lib/puppet/parser/function 中。可以从以下位置从 .rb 文件加载函数。
All the custom functions are implemented as separate .rb files and are distributed among modules. One needs to put custom functions in lib/puppet/parser/function. Functions can be loaded from .rb file from the following locations.
-
$libdir/puppet/parser/functions
-
puppet/parser/functions sub-directories in your Ruby $LOAD_PATH
Creating a New Function
使用 newfunction 方法在 puppet::parser::Functions 模块中创建或定义新函数。需要将函数名称作为符号传递给 newfunction 方法,并作为块传递要运行的代码。以下示例是一个函数,它用于将一个字符串写入 /user 目录中的文件。
New functions are created or defined using the newfunction method inside the puppet::parser::Functions module. One needs to pass the function name as a symbol to newfunction method and the code to run as a block. The following example is a function, which is used to write a string to the file inside the /user directory.
module Puppet::Parser::Functions
newfunction(:write_line_to_file) do |args|
filename = args[0]
str = args[1]
File.open(filename, 'a') {|fd| fd.puts str }
end
end
一旦用户声明了该函数,就可以在清单文件中使用,如下所示。
Once the user has the function declared, it can be used in the manifest file as shown below.
write_line_to_file('/user/vipin.txt, "Hello vipin!")