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.

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
@hior@sudoers_users. These come from thevariablesproperty in the recipe. If a variable is not passed, it isniland 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 / action | Purpose |
|---|---|
source | Template file name in the cookbook. Defaults to the basename of the path plus .erb. |
variables | Hash of values exposed as @name inside the template. |
owner, group, mode | File ownership and permissions. Quote the mode as a string, for example '0644'. |
cookbook | Load the template from a different cookbook. |
local | Set to true to treat source as an absolute path on the node instead of a cookbook file. |
verify | Command that must succeed on the rendered file before it is put in place. %{path} is the temporary file. |
sensitive | Hides the diff and contents in logs. Use this for passwords and keys. |
helpers | Adds helper methods (from a block or module) that the template can call. |
action :create | Default. Creates or updates the file. |
action :create_if_missing | Writes the file only if it does not exist yet. |
action :delete, :touch, :nothing | Remove 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
| Tag | Meaning |
|---|---|
<% 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
| Error | Cause | Fix |
|---|---|---|
Chef::Exceptions::FileNotFound … does not contain a template | The 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 nil | The 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 nil | An @variable was not passed in variables. | Add it to variables, or guard with Array(@var).each. |
| Verification failure on converge | The 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.erblooped overnode['learn_chef_httpd']['default'], but the attribute file definesnode['elasticsearch']['default']. Both now useelasticsearch.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
Tesinghas been changed toTesting. - Sudoers group lines lacked the
%prefix, so sudo would readwheelandadminas user names. The prefix has been added, and the duplicated hardcoded%sysadminline has been removed. @passwordlesswas used insudoers.erbbut never passed, soNOPASSWD:could never be rendered. It is now passed throughvariables.- 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-applystatement has been clarified: local templates work withlocal 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
- More Chef tutorials
- What is Chef and use cases of Chef?
- Chef Tutorials: knife command line reference
- Top 50 Chef interview questions and answers
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals