Three Ways to Provide File Content
| Method | Attribute | Use when |
|---|---|---|
| Static file from a module | source => 'puppet:///modules/mod/file.conf' | The same content on every node |
| Text in code | content => "text\n" | Very small files |
| Template | content => epp('mod/file.epp', {...}) | Content depends on data or facts |
Heredocs
A heredoc is a convenient way to write multi-line text in code.
EPP: Embedded Puppet Templates (Preferred)
EPP templates use the Puppet language inside <% %> tags and take explicit parameters, which makes them easy to read and test. Store them in templates/ of a module with the extension .epp.
| EPP tag | Meaning |
|---|---|
<%= expression %> | Insert the value |
<% code %> | Run code (if, each) without printing |
<%# comment %> | Comment, not printed |
<%- ... -%> | A leading - removes spaces before the tag, a trailing - removes the newline after it. Use them to avoid blank lines |
<%% %%> | Literal tag characters |
ERB: The Older Ruby-Based Templates
ERB templates use Ruby inside the tags and read variables from the surrounding class as @variable. You will meet them in older modules.
| EPP | ERB | |
|---|---|---|
| Language | Puppet | Ruby |
| Variables | Explicit parameters, $name | Implicit scope, @name |
| Facts | Pass in or use $facts[...] | @fqdn or scope['facts'] |
| Recommendation | Use for new code | Keep for existing code |
Inline Templates for Quick Checks
Useful Patterns
Config files with hashes
validate_cmd: For files that can break a service when wrong (sshd, sudoers, nginx), use validate_cmd. Puppet writes a temporary file, runs your command on it (% is the temp path) and only installs the file if it passes.
Managing Part of a File
When you only need one line, the stdlib module provides file_line and concat helps to assemble a file from fragments. Fully managing a file with a template is usually cleaner.
Best Practices
- Add a header
# Managed by Puppet. Manual changes will be overwrittento every managed file - Keep logic out of templates. Compute values in the class, pass simple data to the template
- Always give EPP parameters types, with defaults where sensible
- Validate and render templates in unit tests (later lesson)
- Use
Sensitivedata incontentfor files that contain secrets, so diffs hide it - Set permissions explicitly on every file you manage
Practice Tasks
- Write an EPP template for an
/etc/hosts-style file from an array of hashes - Generate an nginx virtual host from a template and preview it with
puppet epp render - Use
validate_cmdfor asudoers.dfile withvisudo -cf % - Convert a small ERB template to EPP
- Use
file_lineto set one value in/etc/ssh/sshd_configand compare with managing the full file
Conclusion
Templates generate configuration from data. Use EPP with typed parameters for new code, keep logic in classes, and protect risky files with validate_cmd and clear headers.

