Writing custom functions: Introduction
What are functions?
- Related documentation: The Puppet language: Calling functions
Most functions only produce values, but functions can also:
- Cause side effects that modify the catalog. (For example, the
includefunction adds classes to the catalog.)
- Evaluate a provided block of Puppet code, using their other arguments to determine how that code runs.
Most functions take one or more arguments, which determine their return value and the behavior of any side effects.
You can also write your own custom functions.
If you need to manipulate data or talk to third-party services during catalog compilation, and if the built-in functions (or functions from Forge modules) aren’t sufficient, you can write new functions for Puppet.
Custom functions work just like Puppet’s built-in functions: you can call them during catalog compilation to produce a value (and sometimes cause side effects). You can use your custom functions locally, and you can also share them with other users.
Puppet offers three interfaces for writing custom functions:
|The Puppet language||The easiest way to write functions, which you can use without knowing any Ruby. However, it’s less powerful than the Ruby API: pure Puppet functions can only have one signature per function, and can’t take a lambda (block of Puppet code).|
The modern Ruby functions API (
||The most powerful and flexible way to write functions. It requires some knowledge of Ruby.|
The legacy Ruby functions API (
||Avoid unless you must support Puppet 3. This API has major problems, but it is the only way to fully support both Puppet 4.x and Puppet 3.x. (Note that Puppet 3.x can use the modern API when the future parser is enabled.)|
Guidelines for writing custom functions
- Whenever possible, avoid causing side effects. “Side effects” are any effect other than producing a value; in the context of Puppet, it usually means modifying the catalog by adding classes or resources to it.
- In Ruby functions, it’s sometimes possible to change the values of existing variables. Never do this. Everything else in Puppet relies on this never happening.