Templates From Hell
From Cfwiki
Templates in cfengine 2
Here is what I've cf-written to handle templates with cfengine version 2. This configuration has three goals:
- Centralize templates in a configuration repository,
- Only fetch a template if it's modified on the repository,
- Keep the final configuration file (made from the template) from direct editing.
A template, in this article, is a configuration file in which we replaced keywords, that are host-specific, with tags. Cfagent will replace automatically tags with the right keyword.
We'll use the following cfagent actions: copy and editfiles. No external script is needed.
The idea
The main idea is to use a "temporary" directory, used by cfagent to store the edited template file, and maintain the destination file. cfagent will follow this procedure:
- Copy the template file from the repository to a "templates" directory by checking the modification time difference,
- If a copy occured, edit the template file in the "templates" directory,
- Locally copy the edited template to the final destination, with checksum check.
The code
First, the control section.
control:
# Copy from repository, edit templates, copy edited templates actionsequence = ( copy editfiles copy.templates )
# Configuration files may be big. EditfileSize = ( 40000 )
# This class will be defined by the first copy AddInstallable = ( copiedTemplates )
# The repository's address reposerver = ( 192.168.1.1 )
The copy action might look like this, path are examples:
copy:
# First copy pass - don't do anything if we locally copy templates !templates::
/repository/postfix.templates dest=/var/cfengine/templates/postfix server=${reposerver} recurse=2 action=fix type=mtime define=copiedTemplates
# Second copy pass - check if the destination conf file has been altered templates::
/var/cfengine/templates/postfix dest=/etc/postfix recurse=2 action=fix type=checksum
The editfiles action:
editfiles:
# Edit only if a new template arrived copiedTemplates:: { /var/cfengine/templates
Recurse "inf" ReplaceAll "_TAG_HOSTNAME_" With "${host}" }
If you have written the tag _TAG_HOSTNAME_ in /repository/postfix.templates/main.cf, cfengine will replace it with the machine's hostname and copy main.cf on the right place, /etc/postfix.
