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.


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

  - name: john
  - name: jane
  - name: fred
    password: 123!abc


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 %}
{{ }},
  {% raw %}{% endif %}
{% endfor %}

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

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


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, 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