MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Chef Tutorials: template Resource with example

The Chef template resource renders an Embedded Ruby (ERB) file from a cookbook's templates/ directory and writes the result to a path on the node. This page explains how rendering, variables and node attributes fit together. It also gives a corrected, runnable version of the index.html and sudoers examples above, plus the properties, ERB tags and errors you will run into most often.


What is cookbook template (.erb)

A cookbook template is an Embedded Ruby (ERB) template that is used to dynamically generate static text files. Templates may contain Ruby expressions and statements, and are a great way to manage configuration files.

Use the template resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template file in a cookbookโ€™s /templates directory. template resource would not work with chef-apply but can be used with chef-solo.

Use the template resource to manage the contents of a file using an Embedded Ruby (ERB) template by transferring files from a sub-directory of COOKBOOK_NAME/templates/ to a specified path located on a host that is running Chef Infra Client.

ERB Specification

Chef uses Erubis as its template language. It allows embedding pure Ruby code inside special symbols in the templates.

ERB tags explained: <%= %> prints a value, <%- %> embeds Ruby logic in Chef templates

Reference

  • https://docs.chef.io/templates/
  • https://github.com/scmgalaxy/chef-repo
  • https://docs.chef.io/resources/template/
  • https://docs.aws.amazon.com/opsworks/latest/userguide/cookbooks-101-basics-attributes.html

How the template resource works

When Chef Infra Client converges a template resource, it finds the .erb file named in source inside the cookbook, renders it, and compares the result with the file already on disk. It only writes the file, and only reports the resource as updated, when the content, owner, group or mode differs. That comparison makes templates idempotent, and it is the reason notifies can safely restart a service only when the configuration really changed.

A template can read data in two ways:

  • Instance variables such as @hi or @sudoers_users. These come from the variables property in the recipe. If a variable is not passed, it is nil and no error is raised.
  • Node attributes such as node['platform']. These come from Ohai, from cookbook attribute files, or from roles and environments. They are available in every template without being passed in.

Prefer variables for anything the template depends on. Then the recipe shows exactly what the template uses, and the same template can be reused with different data.

Note: Older Chef releases rendered templates with the Erubis library. Current Chef Infra Client releases use Erubi. The template syntax is standard ERB either way, so templates written for either engine work unchanged.

Cookbook layout and template lookup

Chef Workstation can generate the cookbook and empty templates for you:

mkdir -p ~/chef-repo/cookbooks && cd ~/chef-repo/cookbooks
chef generate cookbook devopsschool
chef generate template devopsschool index.html
chef generate template devopsschool sudoers
chef generate attribute devopsschool defaultCode language: JavaScript (javascript)
devopsschool/
โ”œโ”€โ”€ attributes/
โ”‚   โ””โ”€โ”€ default.rb
โ”œโ”€โ”€ recipes/
โ”‚   โ””โ”€โ”€ default.rb
โ”œโ”€โ”€ templates/
โ”‚   โ”œโ”€โ”€ index.html.erb
โ”‚   โ””โ”€โ”€ sudoers.erb
โ””โ”€โ”€ metadata.rbCode language: JavaScript (javascript)

Both templates/index.html.erb and the older templates/default/sudoers.erb layout used in the example above work. Chef also searches host-specific and platform-specific subfolders such as templates/host-web01/ and templates/ubuntu-22.04/, and it falls back to templates/default/ and then templates/. New cookbooks normally place files directly in templates/.

Complete working example (corrected)

The gist above defines elasticsearch attributes but the template loops over learn_chef_httpd, and it reads node['devopsschool']['message'] without defining it. The files below are consistent with each other, so the recipe converges without errors.

# attributes/default.rb
default['devopsschool']['message'] = 'Hello from the devopsschool cookbook'

default['elasticsearch']['default']['ES_USER']           = ''
default['elasticsearch']['default']['MAX_LOCKED_MEMORY'] = 'unlimited'
default['elasticsearch']['default']['LOG_DIR']           = '/var/log/elasticsearch'
default['elasticsearch']['default']['DATA_DIR']          = '/var/lib/elasticsearch'
default['elasticsearch']['default']['CONF_FILE']         = '/etc/elasticsearch/elasticsearch.yml'

default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
default['authorization']['sudo']['users']  = %w(jerry greg)
default['authorization']['sudo']['passwordless'] = falseCode language: PHP (php)
<!-- templates/index.html.erb -->
<!-- Managed by Chef. Local changes will be overwritten. -->
<h1>Platform (Ohai attribute): <%= node['platform'] %></h1>
<h1>Message (cookbook attribute): <%= node['devopsschool']['message'] %></h1>

<pre>
<% node['elasticsearch']['default'].each do |key, value| -%>
<% next if value.to_s.empty? -%>
<%= key %>=<%= value %>
<% end -%>
</pre>

<% 4.times do -%>
<p><%= @hi %>, <%= @world %> from <%= @from %>!</p>
<% end -%>Code language: HTML, XML (xml)
# recipes/default.rb
directory '/var/www/html' do
  recursive true
end

template '/var/www/html/index.html' do
  source 'index.html.erb'
  owner  'root'
  group  'root'
  mode   '0644'            # web content does not need the execute bit
  variables(
    hi:    'Testing',
    world: 'Welt',
    from:  node['fqdn']
  )
  action :create
endCode language: PHP (php)

Run it in local mode from the repository root. The cookbooks/ directory must be under the current directory or one of its parents:

cd ~/chef-repo
sudo chef-client --local-mode --chef-license accept --runlist 'recipe[devopsschool]'
cat /var/www/html/index.htmlCode language: PHP (php)

On the first run the client reports the template as created and prints a diff. On a second run with no changes it reports (up to date). The rendered <pre> block lists only the non-empty attributes: MAX_LOCKED_MEMORY=unlimited, LOG_DIR=/var/log/elasticsearch, DATA_DIR=/var/lib/elasticsearch and CONF_FILE=/etc/elasticsearch/elasticsearch.yml.

Safer sudoers template

A broken /etc/sudoers can lock every user out of sudo. The version below fixes three problems in the original. Group lines now have the % prefix, which sudo requires to tell a group from a user. @passwordless is actually passed to the template. The verify property makes Chef check the rendered file with visudo before it replaces the live one.

# templates/sudoers.erb
# Generated by Chef for <%= node['fqdn'] %>. Do not edit by hand.
Defaults        !lecture,tty_tickets,!fqdn

root          ALL=(ALL) ALL

<% @sudoers_users.each do |user| -%>
<%= user %>   ALL=(ALL) <%= 'NOPASSWD:' if @passwordless %>ALL
<% end -%>

<% @sudoers_groups.each do |group| -%>
# Members of the group '<%= group %>' may gain root privileges
%<%= group %>   ALL=(ALL) <%= 'NOPASSWD:' if @passwordless %>ALL
<% end -%>Code language: HTML, XML (xml)
template '/etc/sudoers' do
  source 'sudoers.erb'
  owner  'root'
  group  'root'
  mode   '0440'
  verify 'visudo -c -f %{path}'   # reject the file if the syntax is invalid
  variables(
    sudoers_users:  node['authorization']['sudo']['users'],
    sudoers_groups: node['authorization']['sudo']['groups'],
    passwordless:   node['authorization']['sudo']['passwordless']
  )
endCode language: PHP (php)

Note: For real systems, the built-in sudo resource is usually the better choice. It writes separate files into /etc/sudoers.d and does not replace the whole sudoers file.

Key properties and actions

Property / actionPurpose
sourceTemplate file name in the cookbook. Defaults to the basename of the path plus .erb.
variablesHash of values exposed as @name inside the template.
owner, group, modeFile ownership and permissions. Quote the mode as a string, for example '0644'.
cookbookLoad the template from a different cookbook.
localSet to true to treat source as an absolute path on the node instead of a cookbook file.
verifyCommand that must succeed on the rendered file before it is put in place. %{path} is the temporary file.
sensitiveHides the diff and contents in logs. Use this for passwords and keys.
helpersAdds helper methods (from a block or module) that the template can call.
action :createDefault. Creates or updates the file.
action :create_if_missingWrites the file only if it does not exist yet.
action :delete, :touch, :nothingRemove the file, update its timestamp, or do nothing unless notified.

Templates are often paired with a service restart that runs only when the file changes:

template '/etc/httpd/conf.d/app.conf' do
  source 'app.conf.erb'
  notifies :restart, 'service[httpd]', :delayed
end

service 'httpd' do
  action [:enable, :start]
endCode language: JavaScript (javascript)

ERB tag reference

TagMeaning
<% code %>Runs Ruby code without printing anything (loops, conditionals).
<%= expr %>Prints the result of the expression.
<% code -%>Removes the newline after the tag. Without it, loops leave blank lines.
<%- code %>Removes leading whitespace before the tag.
<%# comment %>ERB comment. It does not appear in the output.
<%% ... %%>Prints a literal <% and %>, which is useful when the target file is itself a template.

Using templates with chef-apply

The original says templates do not work with chef-apply. That is only true for cookbook templates, because chef-apply runs a single recipe file with no cookbook to search. You can still render a template that sits on disk by setting local true:

# motd.rb  -- run with: sudo chef-apply motd.rb
template '/etc/motd' do
  source '/tmp/motd.erb'   # absolute path on the node
  local  true
  variables(team: 'DevOps')
endCode language: PHP (php)

Common errors and fixes

ErrorCauseFix
Chef::Exceptions::FileNotFound … does not contain a templateThe source name or file location is wrong, or a cookbook template was used with chef-apply.Put the file in templates/, check the .erb name, or use local true.
undefined method '[]' for nilThe template reads an attribute key that is not defined, such as node['learn_chef_httpd'].Define the attribute in attributes/default.rb or fix the key name.
undefined method 'each' for nilAn @variable was not passed in variables.Add it to variables, or guard with Array(@var).each.
Verification failure on convergeThe verify command rejected the rendered file.Run the command manually on the rendered output and fix the template.
Unexpected blank lines in output<% end %> was used instead of <% end -%>.Add -%> to statement tags.

Corrections to the original example

  • index.html.erb looped over node['learn_chef_httpd']['default'], but the attribute file defines node['elasticsearch']['default']. Both now use elasticsearch.
  • node['devopsschool']['message'] was read but never defined. An attribute default has been added.
  • mode '0755' on an HTML file has been changed to '0644'.
  • The typo Tesing has been changed to Testing.
  • Sudoers group lines lacked the % prefix, so sudo would read wheel and admin as user names. The prefix has been added, and the duplicated hardcoded %sysadmin line has been removed.
  • @passwordless was used in sudoers.erb but never passed, so NOPASSWD: could never be rendered. It is now passed through variables.
  • A verify 'visudo -c -f %{path}' check has been added so an invalid sudoers file is never installed.
  • The engine is now described as Erubi, which current Chef Infra Client releases use instead of Erubis.
  • The chef-apply statement has been clarified: local templates work with local true.

Frequently asked questions

Where should I put .erb files in a Chef cookbook?

Put them in the cookbook's templates/ directory, for example templates/index.html.erb. The older templates/default/ subfolder still works, and Chef also searches host-specific and platform-specific subfolders first.

What is the difference between variables and node attributes in a template?

variables are passed by the recipe and appear as @name in the template. Node attributes are global and can be read as node['key'] from any template. Passing data through variables makes templates easier to reuse and test.

Can I use the template resource with chef-apply?

Not with cookbook templates, because chef-apply has no cookbook to search. Set local true and give an absolute source path to render a template file that is already on the node.

How do I restart a service only when a template changes?

Add notifies :restart, 'service[name]', :delayed to the template resource. The template is only marked as updated when the rendered content or the file permissions change, so unchanged runs do not restart the service.

How do I stop secrets in a template from appearing in Chef logs?

Set sensitive true on the template resource. Chef then hides the content diff in its output and logs.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Chef Tutorials: Common Resource Functionality in chef Cookbook recipe

Common resource properties are settings that every Chef Infra resource accepts, whatever the resource type: action, ignore_failure, retries, retry_delay, sensitive, guards such as not_if and only_if, and…

Read More

Chef Tutorials: How to looping and iterative in Chef Cookbook recipe?

Chef recipes are Ruby, so you loop with ordinary Ruby iterators such as each, and each pass declares one Chef resource. This page explains how the loop…

Read More

Chef Tutorials: How to set Conditions in Chef Cookbooks recipe using Guard?

Chef guards are the not_if and only_if properties, which decide during the converge phase whether a resource runs. A guard can be a shell command string or…

Read More

Chef Training Roadmap for DevOps Engineers: Course Tracks, Lab Workflow, and Practical Commands

This guide turns a promotional Chef training post into a practical roadmap for engineers. Compare course levels, understand the learning workflow, and use hands-on commands you can run in a lab.

Read More

Provision an AWS EC2 Instance with Chef (Legacy ChefDK Workflow)

A practical, step-by-step walkthrough for provisioning an AWS EC2 VM using the classic ChefDK and chef-provisioning approach. Includes workflow, commands, recipe examples, and validation checks for legacy environments.

Read More

Chef Command-Line Reference: Essential chef-solo, chef-client, and Knife Workflows

A task-oriented reference for frequently used Chef and Knife commands, from cookbook scaffolding to node bootstrap and run-list management. Includes workflow guidance and copy-ready command examples.

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x