My (very) personal chef tutorial Part III: Templates

In the last part of this tutorial, we looked at cookbook attributes. In this part we will discover cookbook templates.

In a nutshell templates are used to generate files based on the variables and logic contained within the template. Cookbook templates are to be stored in the templates folder of the cookbook.

Chef uses Embedded Ruby (ERB) templates, which combine plain text with ruby code to produce the final file. Here is a very simple example from the wikipedia page:

The ruby code is surrounded by special tags. In this case the loop. After saving the content to a file named “example2.erb”, it can be run using the command

The output is:

In chef cookbooks templates are usually used to create configuration files on the target node during deployment. The special feature of erb templates in chef is that you can access all the context information supplied by chef. For example attributes of the cookbooks, roles and the environment.

The following example illustrates this by writing some of the predefined attributes to a simple file. The content of the file “simple.txt.erb” looks like this:

The recipe “template-example.rb” that uses this template contains the code for using the template:

The recipe can be run against the local node using the following command:

The result of running this recipe is a file “/tmp/simple.txt” with the following content:

In order to make templates independent of attributes you may also use values instead of attributes:

The corresponding syntax in the template looks like this:

This approach keeps your templates clean and simpler to read.

There is also the possibility to reference other templates from within another template in order to create files by composing these different templates. The syntax to include another template looks like this:

The above code will include the first template before rendering this template. The syntax to use this template in a recipe is the same as in the second example.

This concludes the third part of this tutorial. In the forth part we will cover files.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">