Chef: Dynamically Generated Templates

ARTICLE PREREQUISITES: Familiarity with creating Chef cookbook.

Anyone familiar with change configuration tools knows generating configuration files using templates is the bread and butter of these types of tools. Ansible and SaltStack use Jinja, while Chef and Puppet have used ERB (Embedded Ruby).

As a small example, here’s a sample ERB template of a configuration file (JSON) for a small Debian repo management tool called Aptly:

Dynamically Generated

In most cases a simple static ERB is all you want, with most of the defaults statically coded, and few variables that are set outside of the ERB.

But if for some reason you wanted to dynamically create the JSON file from a Ruby hash, you can do this:

The template is just an ERB block containing a single ruby hash and a line of code to convert the ruby hash to JSON. The ruby hash contains defaults for any variables not set.

If the default is not an empty string, some extra attention is needed:

The cookbook recipe now creates the uses the template resource and override variables where the default is not desired:

Use Cases

As said before, most cases you would never want to do this. There may be a few reasons for using this:

  • broad target audience, such as a large organization or public cookbook
  • re-use of output, such as doing RESTful API with JSON picked up from a file.

References

I originally came across this ruby hash as ERB idea from: