Custom functions overview
Puppet includes many built-in functions, and more are available in modules on the Forge. You can also write your own custom functions.
Functions are plugins used during catalog compilation. When a Puppet manifest calls a function, that function runs and returns a value. Most functions only produce values, but functions can also:
- Cause side effects that modify a catalog. For example, the
include
function adds classes to a catalog. - Evaluate a provided block of Puppet code, using arguments to determine how that code runs.
Functions usually take one or more arguments, which determine the return value and the behavior of any side effects.
If you need to manipulate data or communicate with third-party services during catalog compilation, and if the built-in functions, or functions from Forge modules, aren’t sufficient, you can write custom functions for Puppet.
Custom functions work just like Puppet’s built-in functions: you can call them during catalog compilation to produce a value or cause side effects. You can use your custom functions locally, and you can share them with other users.
To make a custom function available to Puppet, you must put it in a module or an environment, in the specific locations where Puppet expects to find functions.
Puppet offers two interfaces for writing custom functions:
Interface | Description |
---|---|
The Puppet language | To write functions in the Puppet language, you don't need to know any Ruby. However, it’s less powerful than the Ruby API. Puppet functions can have only one signature per function, and can’t take a lambda (a block of Puppet code) as an argument. |
The Ruby functions API | The more powerful and flexible way to write functions. This method requires some knowledge of Ruby. You can use Ruby to write iterative functions. |
Guidelines for writing custom functions
Whenever possible, avoid causing side effects. Side effects are any change other than producing a value, such as modifying the catalog by adding classes or resources to it.
In Ruby functions, it’s possible to change the values of existing variables. Never do this, because Puppet relies on those variables staying the same.
Documenting functions
For information about documenting your functions, see Puppet Strings .
Related topics: Function calls, Catalog compilation, Environments, Modules, Puppet Forge, Iterative functions.