CoursesChefIntermediate

Templates & files

ERB templates from node data.

Intermediate12 min · lesson 6 of 12

The template resource renders a file from an ERB (Embedded Ruby) template using node attributes and variables, then places it — the same generate-config-from-data pattern as Ansible’s Jinja2 templates. You keep the template in the cookbook’s templates/ directory, pass it values, and let it produce the per-node config. Files that are static (no substitution) use the cookbook_file resource instead.

templates/nginx.conf.erb
worker_processes <%= node['nginx']['worker_processes'] %>;
http {
server {
listen <%= @port %>;
server_name <%= node['fqdn'] %>;
<% if @enable_tls %>
ssl_certificate <%= @cert_path %>;
<% end %>
}
}
recipe
template '/etc/nginx/nginx.conf' do
source 'nginx.conf.erb'
variables(port: 8080, enable_tls: true, cert_path: '/etc/ssl/site.pem')
notifies :reload, 'service[nginx]'
end

Variables vs node attributes

Two ways to feed a template: read node attributes directly inside the ERB (node[‘nginx’][‘port’]), or pass explicit variables via the variables property and reference them with @. Passing variables is cleaner for values computed in the recipe and keeps the template’s inputs obvious. As with Jinja2, keep ERB logic light — substitute and lightly branch, but compute in the recipe.

A bad template can break the service on reload
A rendered config with an invalid value fails when the service reloads — and Chef, unlike Ansible’s validate, does not test it for you by default. Add a guard or an execute that validates (nginx -t) before the reload, or use the resource’s verify property, so a converge does not push a broken config and take the service down on the next restart.