Image for post
Image for post

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:

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:

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.

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

Written by

Linux NinjaPants Automation Engineering Mutant — exploring DevOps, Kubernetes, CNI, IAC

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store