A collection of task oriented solutions in Puppet

 

Select a file based on a fact

Challenge

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

Solution

class fact_section {

  file { '/etc/mysql/conf.d/tuning.cnf':
    ensure => 'present',
    source => [
        "puppet:///modules/mysql-server/tuning.${::hostname}.cnf",
        "puppet:///modules/mysql-server/tuning.${::domain}.cnf",
        'puppet:///modules/mysql-server/tuning.cnf'
    ],
  }

}

Explanation

Sometimes you want to have specific versions of a file for a given host, location or operating system while having a default fallback for the standard cases. By using an array of sources in a file resource, with the value of a fact as part of the on-disk file name, you can easily make your configs more granular where needed while keeping sensible defaults.

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

files/
    tuning.host1.cnf
    tuning.host2.cnf
    tuning.example.org.cnf
    tuning.cnf

When using multiple sources in this way puppet will use the first file that matches within the source property, and raise an error if none match, so you should nearly always have a default file.

See also