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.
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.
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.
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!")