CoursesPuppetIntermediate

Classes & defined types

Group and parameterize resources.

Intermediate14 min · lesson 5 of 12

A class groups related resources under a name so you can include them as a unit — the nginx class contains the package, config, and service. Classes are declared once and included wherever needed (include nginx), and Puppet ensures a class is only applied once per node no matter how many times it is included. Parameterized classes take inputs, so the same class configures differently per node.

modules/nginx/manifests/init.pp
class nginx (
Integer $workers = 4,
Integer $port = 80,
) {
package { 'nginx': ensure => installed }
file { '/etc/nginx/nginx.conf':
ensure => file,
content => epp('nginx/nginx.conf.epp', { 'workers' => $workers, 'port' => $port }),
notify => Service['nginx'],
}
service { 'nginx': ensure => running, enable => true }
}

Defined types repeat a pattern

Where a class is a singleton (applied once per node), a defined type is a reusable pattern you can instantiate many times with different titles — a vhost defined type to create ten virtual hosts, a user-with-dotfiles type per developer. It looks like a class but uses define, and each instance is distinct. Classes for “the node has nginx,” defined types for “the node has these N of something.”

defined type
define nginx::vhost (String $server_name, Integer $port = 80) {
file { "/etc/nginx/sites/${title}.conf":
ensure => file,
content => epp('nginx/vhost.epp', { 'name' => $server_name, 'port' => $port }),
notify => Service['nginx'],
}
}
# instantiate many:
nginx::vhost { 'app': server_name => 'app.acme.internal' }
nginx::vhost { 'api': server_name => 'api.acme.internal', port => 8080 }
Classes are singletons — do not include with params twice
A parameterized class can only be declared with explicit parameters once per node; declaring class { ‘nginx’: workers => 4 } in two places causes a duplicate-declaration error. Prefer include (and drive parameters from Hiera data) so classes compose cleanly, and reserve resource-like class { } declarations for a single, deliberate place. This is a top source of confusing compile errors.