Chef / ruby / erb files – How does this example code work

chefruby

I am working on a custom bootstrap template, based on a sample template. I am looking at the example of getting the validation key from the workstation to the brand new server, and from what I can tell is the key path is specified in knife.rb in the variable validation_key. And in the bootstrap template it is echoed in with a <%= validation_key %>

Is this magic ruby stuff, is the validation_key path var processed in knife, and the contents are read into a different var when processing the template, and that is how a path is turned into a string containing the contents of the file at that path?

If I declare foo=/tmp/test.txt in knife.rb, can I access the contents of test.txt in my bootstrap template by using <%= foo %>?

FROM: https://github.com/opscode/chef/blob/master/lib/chef/knife/bootstrap/ubuntu12.04-gems.erb

(
cat <<'EOP'
<%= validation_key %>
EOP
) > /tmp/validation.pem

Best Answer

The <% and %> business is part of Ruby's templating system also used by Chef. The reference to validation_key is a local variable passed in by the bootstrap template code.

A more common use of ERB templating within Chef is creating configuration files, for example from the Apache community cookbook:

templates/default/ports.conf.erb

<% @apache_listen_ports.each do |port| %>
Listen <%= port %>
<% end %>

This resource would be created in a recipe somewhere:

recipes/default.rb

template "/etc/apache2/ports.conf" do
  source "ports.conf.erb"
  variables :apache_listen_ports => [80, 443]
end

When you're first starting out the important bit is to note the use of <% for writing code that's executed by ERB, versus <%= which returns the result of an expression, usually just a variable.