Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Templates and Data Bags

Template Variables, Helpers and Partials

Go deeper with Chef templates: passing variables, conditionals and loops, helper methods, partial templates and keeping logic out of ERB, with runnable examples.

A template with a single value is easy. Real configuration files have optional sections, lists of upstream servers, and repeated blocks. This lesson shows how to pass data into templates cleanly, how to loop and branch without turning the file into a program, and how Chef's partial templates and helper methods keep large files readable.

As before, the real Chef snippets are read-only and the runnable code uses plain Ruby (including the real ERB library) to show the ideas.

Passing data: variables versus node

There are two ways to get data into a template. The first is the variables property:

Ruby
template '/etc/haproxy/haproxy.cfg' do
  source 'haproxy.cfg.erb'
  variables(
    backends: node['haproxy']['backends'],
    stats: node['haproxy']['stats_enabled']
  )
end

Inside the template you use @backends and @stats. Chef turns each key into an instance variable. The second way is to read node['haproxy']['backends'] directly in the ERB. It works, but then the template depends on a global object. Passing variables makes the dependency explicit, lets a recipe reuse one template with different data, and makes unit tests simpler, because a test can see which values the template receives.

Conditionals and loops

Inside ERB you can use any Ruby, but keep it small: an if for an optional block and an each for a list are enough for most files.

Ruby Optional sections and repeated blocks

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.

View is a stand-in for what Chef does: it creates an object whose instance variables come from the variables hash, then renders the template in that object's context. The same template renders two different files depending on the data.

Keep logic out of the template

The more Ruby you put in an ERB file, the harder it is to read, because the file is now two languages interleaved. A good rule is: templates format, recipes decide. If you need to compute something (join a list, pick a default, convert units), do it in the recipe or in a helper and pass the finished value.

Chef supports this in two ways. The first is helper methods defined inline:

Ruby
template '/etc/myapp/app.conf' do
  source 'app.conf.erb'
  helper(:memory_mb) { (node['memory']['total'].to_i / 1024) }
  variables(workers: [node['cpu']['total'], 8].min)
end

Inside the template you call memory_mb. The second way is a helper module in the cookbook's libraries/ folder, included with helpers(MyApp::Helpers), which is better when several templates share the logic and when you want to unit test the helper on its own.

Ruby Stand-in: a helper module tested without Chef

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 helpers are tested on a plain object with no template and no Chef. That is the point of the pattern: the logic is small and separate, and the template only prints.

Partial templates

Big files such as an Nginx server block or a Tomcat config often have identical fragments. Chef offers render inside a template to include another template, called a partial. Partial files are conventionally named with a leading underscore:

TEXT
templates/default/nginx.conf.erb
templates/default/_gzip.erb
ERB
http {
<%= render '_gzip.erb', variables: { level: 5 } %>
}

Use local true if the partial path is a real file path instead of a cookbook file. The partial gets its own variables, which keeps it reusable.

Ruby Stand-in: render a partial from a template

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 stand-in fakes render with a method. In real Chef the partial is a cookbook file and receives variables, but the idea is the same: small reusable pieces assemble the final file.

Checking what you render

  • Whitespace. Count blank lines. Use -%> on every control tag.
  • Dangerous values. A value that is nil prints as an empty string. If <%= @port %> is nil, you silently get listen ;. Fail early in the recipe with raise or Chef::Log.fatal when a required attribute is missing.
  • Validation hooks. template accepts verify 'nginx -t -c %{path}', which runs a command against the rendered file before it is installed. If the command fails, Chef does not replace the working file.
  • Sensitive output. Add sensitive true when the template contains passwords, so the diff is hidden in logs.
Ruby
template '/etc/nginx/nginx.conf' do
  source 'nginx.conf.erb'
  verify 'nginx -t -c %{path}'
  sensitive true
end

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside a template, how do values passed with variables(port: 80) appear?

    Chef sets each key of the variables hash as an instance variable, so the template uses @port.
  2. 2. What is the best place for non-trivial calculations such as picking a pool size?

    Templates should format data. Helpers and recipes can hold the logic and be unit tested.
  3. 3. What does the verify property of the template resource do?

    verify runs a check such as nginx -t on the rendered temporary file, so a broken config never replaces a working one.
  4. 4. How are partial templates usually named?

    By convention partials start with an underscore and are included with render inside another template.
  5. 5. What happens if a nil variable is printed with <%= @port %>?

    ERB prints nil as an empty string. Validate required values in the recipe instead of discovering a broken file later.

Summary

  • Pass data with variables and read it as instance variables; avoid reading node inside templates.
  • Use if and each for optional sections and lists, but keep computing in helpers or recipes.
  • Helper blocks and helper modules make logic reusable and testable; partials (render) split big files.
  • verify checks the rendered file before install, and sensitive true keeps secrets out of logs.
  • Watch for nil values and stray blank lines.

Next: Data Bags: Shared Data for Many Nodes