Chapter 14. Improving the Module

There is a tremendous amount of additional features that can be utilized in a module. This chapter will cover the following features:

  • Validating input data to ensure it conforms to expectations
  • Providing data to modules using Hiera
  • Classes and subclasses within the module
  • Definitions that can be reused for processing multiple items
  • Utilizing other modules within your own
  • Documenting modules

Let’s get started.

Validating Input with Data Types

Puppet 4 introduced a new type system that can validate input parameters. This improves code quality and readability.

In older versions of Puppet, it was common to perform input validation like this:

class puppet(
  # input parameters and default values for the class
  $version = 'latest',
  $status  = 'running',
  $enabled = true,
  $datetime = '',
) {
  validate_string( $version )
  validate_string( $status )
  validate_bool( $enabled )
  # can't validate or convert timestamps
...resources defined below...

While this looks easy with three variables, it could consume pages of code if there are a lot of input variables. In my experience with larger modules, it wasn’t uncommon for the first resource defined in a manifest to be down below line 180.

Puppet 4 allows you to define the type when declaring the parameter now, which both shortens the code and improves its readability. When declaring the parameter, simply add the type before the variable name. This declares the parameter and adds validation for the input on a single ...

Get Learning Puppet 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.