UPDATE: The information below is out of date and the functionality has been implemented in their git repo.
For configuration management, many of you may be familiar with Puppet. Others may be familiar with deployment tools such as Capistrano. One such tool that is a bit lighter than Puppet and more conducive to configuration management than Capistrano is a tool called Ansible. Ansible doesn’t require remote agents like you may be used to with Puppet, as it runs commands over SSH, and is idempotent, allowing you to know all your systems will be in the state you expect. It’s a growing tool, and I did have some issues because my tasks quickly outgrew the functionality built-in to-date, however, it is also easily extendable.
One such task that wasn’t available was simple validation of the template variables to ensure someone defined them somewhere before it tried to do replacement on them. Luckily, I was able to add such a feature with a few lines of code added to the Ansible lib/ansible/utils/template.py file’s template_from_file function. The same could be done for the template_from_string function as well. Now, if a variable isn’t defined, Ansible will complain, preventing the template from being silently written without data for missing variables. In a build system or unit tests, the –check and –diff options for ansible-playbook are especially helpful with this validation.
from jinja2 import meta # Ensure all template variables are defined template_vars=list(jinja2.meta.find_undeclared_variables(jinja2.Environment().parse(unicode(open(realpath).read(), "utf8")))) undeclared_vars = [] for varname in template_vars: if varname not in vars and varname not in t.globals: undeclared_vars.append(varname) if undeclared_vars: raise KeyError("undeclared variable(s) in template: %s" % ', '.join(undeclared_vars)) |
Leave a Reply