Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Classes, Modules and Hiera

Defined Types

Create reusable multi-instance building blocks with Puppet defined types: define syntax, $title and $name, parameters, avoiding duplicate resources, and when to use a class instead.

A class can be applied only once per node. But some things come in many copies: virtual hosts, user accounts with SSH keys, cron jobs, database schemas. A defined type (often just "define") is a reusable template of resources that you can declare many times, each time with a different title and parameters. It behaves like a custom resource type written in the Puppet language.

Defining one

PUPPET
define nginx::vhost (
  Integer[1, 65535] $port    = 80,
  String            $docroot = "/var/www/${title}",
  Enum['present', 'absent'] $ensure = 'present',
) {
  file { "/etc/nginx/conf.d/${title}.conf":
    ensure  => $ensure ? { 'present' => file, default => absent },
    content => epp('nginx/vhost.conf.epp', {
      'server_name' => $title,
      'port'        => $port,
      'docroot'     => $docroot,
    }),
    notify  => Service['nginx'],
  }

  file { $docroot:
    ensure => $ensure ? { 'present' => directory, default => absent },
    force  => true,
  }
}

Use it as if it were a built-in type:

PUPPET
nginx::vhost { 'blog.example.test':
  port => 8081,
}

nginx::vhost { 'shop.example.test':
  port    => 8082,
  docroot => '/srv/shop',
}

The define lives in modules/nginx/manifests/vhost.pp, named nginx::vhost. The file name must match the last part of the name.

$title and $name

Inside a define two variables exist automatically:

  • $title: the title you gave ('blog.example.test').
  • $name: the namevar, which defaults to the title. You can set it with the name attribute if different.

Use $title to build unique resource names for what the define creates ("/etc/nginx/conf.d/${title}.conf"). Resources declared inside a define must have titles that depend on the define's title, otherwise the second instance would declare a duplicate.

PUPPET
# BAD: same title for every instance, second use fails with a duplicate error
file { '/etc/nginx/conf.d/vhost.conf': ... }

# GOOD: unique per instance
file { "/etc/nginx/conf.d/${title}.conf": ... }

Defined type or class?

Question Class Defined type
How many times per node? Once Many
Declared with include or class {} resource-style name { 'title': }
Gets Hiera automatic lookup Yes No (not automatic; use a class that loops over data)
Typical use Install and configure a service A vhost, user, mount, database, cron job

Defined types do not get automatic parameter lookup. The usual way to drive them from data is a class that loops over a hash from Hiera:

PUPPET
class profile::web (
  Hash[String, Hash] $vhosts = {},
) {
  include nginx
  $vhosts.each |$name, $attrs| {
    nginx::vhost { $name:
      * => $attrs,       # splat: pass a hash as attributes
    }
  }
}

The splat * => passes every key of the hash as an attribute. The matching Hiera data:

YAML
profile::web::vhosts:
  blog.example.test:
    port: 8081
  shop.example.test:
    port: 8082
    docroot: /srv/shop

Adding a site is now an edit to data only.

Relationships and defined types

You can use a define in relationships like any resource, and Nginx::Vhost['blog.example.test'] is its reference (note both parts of the name capitalised):

PUPPET
Nginx::Vhost <| |> ~> Service['nginx']       # every vhost refreshes nginx
service { 'nginx': require => Nginx::Vhost['blog.example.test'] }

A define that creates resources which interact with other classes should make its needs explicit, for example require => Class['nginx'] or include nginx inside the define, so the define works when used in isolation.

Common mistakes

  • Using a static title inside the define (duplicate declarations on the second use).
  • Writing a define for something that exists once per node: use a class.
  • Forgetting that $title can contain characters illegal in file names; validate with a Pattern type or transform with regsubst.
  • Expecting automatic Hiera lookup of define parameters.

Stand-ins: instances and duplicate detection

Python Stand-in: a define declared many times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: why a static title breaks the second instance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When should you use a defined type instead of a class?

    Defined types can be declared many times; classes only once.
  2. 2. What does $title contain inside a define?

    $title is the title of that particular instance.
  3. 3. Why must resources inside a define use titles that include $title?

    Static titles would clash when the define is used twice.
  4. 4. How are defined types usually driven from Hiera data?

    Defines have no automatic lookup; a class feeds them via a hash.

Summary

  • define creates a reusable, multi-instance resource-like construct.
  • Use $title (and $name) to make inner resource titles unique.
  • Reference instances as Nginx::Vhost['x'].
  • No automatic Hiera lookup: loop over a hash with each and splat (*).
  • Class for one-per-node, define for many-per-node.

Next: Module Structure and the Puppet Forge