Ansible – Validating Template Variables

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/ 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: 
    if undeclared_vars:
        raise KeyError("undeclared variable(s) in template: %s" % ', '.join(undeclared_vars))

About ipaul

My name is Paul Hassinger, the founder of I have been an avid user of computers since a child. I started when I was about 10 years old working on an Atari computer. Since then, I grew and have had exposure to all types of technologies. I started using FIDONet on a BBS as a child and grew to the Internet. My first graphical world wide web experience was in 1993 using Mosaic. Over time I've worked with both small and large computing systems even maintaining systems serving millions of users on some of the largest social networking sites. I hope to use this blog to capture what I've learned over the years and what I do in my daily life so that others and myself may find the information useful.