A collection of task oriented solutions in Puppet

 

Avoid hard coding file paths

Challenge

You don't want absolute hardcoded file paths in your resources.

Solution

class file_module_path {

  file { '/tmp/fakefile':
    content => file('yourmodulename/fakefile')
  }

}

Explanation

Having absolute file paths in your Puppet modules can make reuse harder and tie them to implementation details of your puppet install. While the template function has always provided a way around this, by accepting module based paths, the file type lacked this nicety until Puppet 3.7 and later.

In earlier puppet versions you called file with absolute paths, like this:

class absolute_path {

  file { '/tmp/fakefile':
    content => file('/etc/puppet/modules/yourmodulename/files/fakefile')
  }

}

This assumed the module would be deployed to a certain location and on a *nix alike system. In newer puppets you can call the file function in the same way as you'd use template, while retaining support for matching the first found file. This allows you to specify files relative to the module itself and hide puppet implementation details such as the module path.

class file_module_path {

  file { '/tmp/fakefile':
    content => file('yourmodulename/fakefile'),
  }
  
  # and with fact based file selection
  
  file { '/tmp/fakefile':
    content =>  file(
                      "yourmodulename/fakefile.${::hostname}",
                      'yourmodulename/fakefile'
                    ),
  }

}

See also