There are two ways in which you can use Jinja templates inside of Ansible are:

This blog post demonstrates both of these techniques being used. The information contained in the post is contained below for convenience.

Data

The following data will be used by the template and filter in the subsequent sections of this page:

---
users:
  - name: john
    email: john@example.com
  - name: jane
    email: jane@example.com
  - name: fred
    email: fred@example.com
    password: 123!abc

Templates

Templates require a template file which contains the smarts of what you’re wanting to do:

# get_emails.j2
[
{% for user in users %}
  {% if user.password is undefined %}
{{ user.email }},
  {% raw %}{% endif %}
{% endfor %}
]

You can then call the template from inside of Ansible using a lookup:

- set_fact:
    emails: "{{ lookup('template', './get_emails.j2' }}"

Filters

In this case, a filter can achieve the same result as the template:

- set_fact:
    emails: "{{ users | selectattr('password', 'undefined') | map(attribute='email') | list }}"

As always, if you have any questions or have a topic that you would like me to discuss, please feel free to post a comment at the bottom of this blog entry, e-mail at will@oznetnerd.com, or drop me a message on Reddit (OzNetNerd).

Note: The opinions expressed in this blog are my own and not those of my employer.

Leave a comment