Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Templates and Data Bags

Templates and ERB Basics

Learn how the Chef template resource renders ERB files into configuration files, how idempotence works, and try a runnable Ruby stand-in for rendering.

Almost every server needs configuration files whose contents depend on the machine: a web server needs its port and worker count, a database needs its memory settings, an application needs the address of its database. Chef solves this with the template resource. You write a file once, with small holes in it, and Chef fills the holes with values from node attributes every time chef-client runs.

Templates are written in ERB (Embedded Ruby), which ships with Ruby itself. That is good news for learning: ERB is not a Chef invention, so you can try it in any Ruby session. In this lesson you will see the real template resource, learn the ERB tags you need, and then run a stand-in that renders a template and only rewrites the file when the content changed, which is the behavior Chef gives you.

The real Chef Infra Client cannot run on this site. The template snippets below are real Chef code and are read-only. The runnable examples use plain Ruby on the server and say clearly what is real (ERB) and what is a stand-in (the "resource").

The template resource

A template lives in the cookbook, in templates/ (for example templates/default/app.conf.erb). The recipe declares where it should end up:

Ruby
template '/etc/myapp/app.conf' do
  source 'app.conf.erb'
  owner 'root'
  group 'root'
  mode '0644'
  variables(
    port: node['myapp']['port'],
    workers: node['myapp']['workers']
  )
  notifies :restart, 'service[myapp]', :delayed
end

source names the file inside the cookbook. variables passes values into the template. owner, group and mode set the ownership of the result. notifies tells Chef to restart a service, but only when the file actually changed. The default action is :create: render the template, compare it with the file on disk, and write it only if the two differ. That comparison is what makes templates idempotent: running Chef ten times writes the file once.

ERB tags you need

ERB has only a few tags:

Tag Meaning
<%= expression %> Evaluate Ruby and insert the result
<% code %> Run Ruby code, insert nothing (loops, conditions)
<%# comment %> A comment, not printed
<%- code -%> Same as <% %>, but trims the surrounding whitespace and the newline
<%% A literal <%

Chef renders with trim mode -, which is why you see -%> in cookbooks. Without it, every <% end %> line leaves an empty line in your output.

Ruby ERB: output, loops and trim mode

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 gets), it gets the next line from this box.

The loop lines disappear thanks to -%>, and each iteration prints one server line. binding hands the local variables to the template. Chef does something similar, but it exposes only what you pass in variables (and node), which keeps templates explicit.

Idempotence: write only on change

The central idea of a Chef resource is: describe the desired state, and act only if the machine is not already there. Here is a small stand-in, with a hash instead of a real disk, that behaves like action :create:

Ruby Stand-in: a template resource that only writes on change

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 gets), it gets the next line from this box.

Runs 2 and 3 show the point: the second run reports "up to date", the third notices the new value and rewrites the file. The return value plays the role of notifies: only a real change triggers a restart. Real Chef also shows you a diff of the file in the log, and with chef-client --why-run it reports what would change without touching the disk.

Where Chef looks for templates

Chef supports file specificity: inside templates/ you can put host-web01.example.com/, ubuntu-22.04/, ubuntu/, or default/ folders. Chef picks the most specific match for the node. In practice most cookbooks only use templates/default/, and a few use a platform folder when the config differs per OS.

TEXT
cookbooks/myapp/
  recipes/default.rb
  templates/
    default/app.conf.erb
    ubuntu/app.conf.erb       # used on Ubuntu instead of default

Common mistakes

  • Forgetting the trim mode. Without -%> you get blank lines. They are harmless in many files but break formats such as YAML lists or shell scripts with strict layout.
  • Reading node inside the template. It works (node['myapp']['port']), but passing variables makes the template testable and shows what it needs. Prefer variables.
  • Hard-coding values. If a number appears in a template, ask whether it belongs in an attribute with a default.
  • Editing the file on the server. The next run overwrites it. Change the cookbook instead. A header comment such as "Managed by Chef" tells colleagues this.
  • Missing quotes in output. ERB does no escaping. If a value contains a quote or a newline, it lands in the file as is.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the template resource do by default (action :create)?

    The default action renders the template, compares the result with the file on disk, and writes only when they differ. That keeps runs idempotent and avoids needless restarts.
  2. 2. Which tag inserts the value of a Ruby expression?

    The equals sign prints the result. The plain tag runs code without output, and the hash tag is a comment.
  3. 3. Why do cookbooks write -%> at the end of tags?

    Trim mode with a dash removes the whitespace and newline around control tags, which keeps the generated file tidy.
  4. 4. What triggers a notification such as notifies :restart?

    Notifications fire when the resource updated the system. An up-to-date template sends nothing.

Summary

  • The template resource renders an ERB file from templates/ and writes it to a path, with owner, group and mode.
  • ERB tags: <%= %> prints, <% %> runs code, <%# %> comments, and -%> trims whitespace.
  • The default :create action writes only when the content changed, so it is idempotent and notifications fire only on real changes.
  • Pass values with variables, and keep numbers and names in attributes, not in the template.
  • File specificity lets a platform or host folder override default/.

Next: Template Variables, Helpers and Partials