A collection of task oriented solutions in Puppet

 

Select a template based on a fact

Challenge

You want to deploy a specific template based on the value of a fact.

Solution

# install the external multitemplate module
$ sudo /opt/puppetlabs/bin/puppet module install deanwilson-multitemplate

Notice: Installing -- do not interrupt ...
/etc/puppetlabs/code/environments/production/site
|-- deanwilson-multitemplate (v1.0.2)
# replace template with multitemplate and specify multiple files
class ssh::config {

  file { '/etc/ssh/sshd_config' :
    ensure  => present,
    mode    => '0600',
    content => multitemplate(
                              "ssh/${::fqdn}.erb",
                              "ssh/${::domain}.erb",
                              'ssh/default_sshdconfig.erb'
                            ),
  }

}

Explanation

Sometimes you want to have specific versions of a template for a given host, location or operating system while having a default fallback for the standard cases. Unfortunately while this is easy to do with file resources there is no equivalent in core puppet for templates. Instead you'll need to Install a module from the forge, in this case multitemplate to add this functionality.

# install the external multitemplate module
$ sudo /opt/puppetlabs/bin/puppet module install deanwilson-multitemplate

Notice: Installing -- do not interrupt ...
/etc/puppetlabs/code/environments/production/site
|-- deanwilson-multitemplate (v1.0.2)

Once you've installed the module you replace template with multitemplate in your resources and you can specify multiple sources, with the value of a fact as part of the on-disk file name, in the same way you would select from multiple normal files.

In the module directory you would have file names like these:

templates/
    tuning.host1.cnf.erb
    tuning.host2.cnf.erb
    tuning.example.org.cnf.erb
    tuning.cnf.erb

When using multiple sources in this way puppet will use the first template file that exists, and cause an error if none match, so you should nearly always have a default file.

See also