Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 29 ยท Variables and Logic

Jinja2 Templates and Filters

Use Jinja2 in Ansible: {{ }} expressions, {% %} blocks, filters like default, join, map and selectattr, the template module, lookups, whitespace control and YAML quoting rules.

Ansible uses the Jinja2 template language in two places. Inside a playbook, {{ variable }} pulls a value into a task argument. In a template file, Jinja2 builds whole configuration files from your variables: an nginx config, an application .env, a hosts file. One template plus per-environment variables replaces a dozen hand-edited copies.

This lesson shows the three kinds of Jinja2 markers, the filters you will use daily, how the template module delivers a rendered file, what a lookup is, how to control whitespace, and the YAML quoting rule that causes the most confusing first errors. It builds on Variables, Facts and Precedence.

Real Ansible renders templates with Jinja2 on the control node, which cannot run here. The playbook and template snippets are read-only. The runnable example is a small Node.js renderer written for this lesson: it supports only a few features, and exists to show how rendering works inside. Real Jinja2 is far richer.

The three markers

Jinja2 has three kinds of delimiters:

Marker Purpose Example
{{ ... }} Print the value of an expression {{ http_port }}
{% ... %} Run a statement: if, for, set {% for h in groups['web'] %}
{# ... #} A comment that never appears in the output {# generated file #}

Everything outside the markers is copied through unchanged. In a playbook you mostly use {{ }}. Statements and comments belong in template files.

YAML
- name: Write a greeting
  ansible.builtin.copy:
    dest: /etc/motd
    content: "Welcome to {{ inventory_hostname }} ({{ ansible_facts['distribution'] }})\n"

You can reach into maps and lists with a dot or brackets (site.name, site['name'], servers[0]). The bracket form is safer when a key could clash with a method name such as items.

Filters

A filter transforms a value. You apply it with a pipe, and filters chain from left to right. Here are the ones to learn first:

Filter What it does Example
default(x) Use x when the variable is undefined {{ port | default(80) }}
join(sep) Join a list into a string {{ pkgs | join(', ') }}
upper, lower Change case {{ env | upper }}
length Count items {{ servers | length }}
map(attribute='x') Pull one field from each item {{ servers | map(attribute='host') | list }}
selectattr('x') Keep items whose field is truthy {{ servers | selectattr('backup') | list }}
to_json, to_nice_json, to_nice_yaml Serialize data {{ config | to_nice_json }}
int, bool, string Convert types {{ port | int }}

Two special cases are worth remembering. An undefined variable is an error in Ansible, which is helpful (a typo does not silently produce an empty value), so default is how you opt in to a fallback. And default(omit) is a special form that means "do not pass this module argument at all if the variable is unset".

YAML
- name: Create a user, with a shell only if one was given
  ansible.builtin.user:
    name: "{{ username }}"
    shell: "{{ user_shell | default(omit) }}"

Note that map and selectattr return a generator, so add | list when you need an actual list. Inside a template, join and to_json consume them directly, which is why the stand-in below does not need it.

The template module

The template module renders a .j2 file on the control node and copies the result to the managed node. It runs every time but only reports changed when the rendered content differs from the destination, so it is idempotent.

YAML
- name: Deploy the nginx site
  ansible.builtin.template:
    src: site.conf.j2          # looked up in the role's templates/ directory
    dest: /etc/nginx/conf.d/shop.conf
    owner: root
    group: root
    mode: "0644"
  notify: Reload nginx

A matching templates/site.conf.j2 might read:

TEXT
# managed by Ansible, do not edit by hand
server {
  listen {{ http_port | default(80) }};
  server_name {{ site_name }};
{% for s in upstreams %}
  # backend {{ s.host }} weight {{ s.weight }}
{% endfor %}
}

Useful options are backup: true (keep a timestamped copy of the old file), validate (run a command on a temporary copy before replacing the real file; %s stands for the temporary path) and mode (always quote it, as in Files, Users and Packages, or YAML may read 0644 as an octal number). Pair the module with a handler so the service reloads only when the file changes (see Handlers, Tags and Task Control).

Stand-in: a minimal template renderer

This renderer handles {{ expr | filter }}, {% if %}...{% else %}...{% endif %}, {% for %} and the - whitespace markers. Press Run, then change a variable or a filter.

Node.js A tiny Jinja-style renderer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The default filter supplied 'www-data' because site.owner does not exist, and kept 8080 because site.port does. Remove port from vars.site and the output shows 80 instead.

Whitespace control

By default, a {% %} line leaves behind its own newline and indentation, so loops can produce blank lines. Adding a minus sign trims neighbouring whitespace: {%- ... %} removes whitespace before the tag and {% ... -%} removes it after. The renderer above implements this: the for line ends in -%}, so no blank line appears between the upstream lines.

Ansible's template module also enables Jinja2's trim_blocks option by default (the first newline after a block tag is removed), which makes most hand-written templates look right without any minus signs. The important habit is to check the rendered result with ansible-playbook --check --diff (see Testing, Linting and Debugging) instead of trusting what the template looks like.

Lookups

A lookup fetches data from outside your variables. Lookups always run on the control node, not on the managed host.

YAML
- name: Use values from the controller
  ansible.builtin.debug:
    msg:
      - "Home: {{ lookup('ansible.builtin.env', 'HOME') }}"
      - "Banner: {{ lookup('ansible.builtin.file', 'files/banner.txt') }}"

Common lookups read environment variables (env), file contents (file), and generate values (password). Use query when you want a list back. Because lookups run locally, they are a common source of "works on my laptop" surprises in CI: the file or variable must exist where Ansible runs.

Quoting rules for YAML

YAML treats a value starting with { as the start of a map. So this fails to parse:

YAML
# broken: YAML sees a map, not a string
path: {{ base_dir }}/app

Quote any value that begins with {{:

YAML
path: "{{ base_dir }}/app"      # works
name: app-{{ version }}          # fine: it does not start with a brace

Also quote values containing : (colon and space) or starting with *, &, !, %, @ or a backtick. Inside when you never use braces at all (see Conditionals and Loops).

Stand-in: strict undefined variables

Real Ansible raises an error for an undefined variable unless you give a default. This model shows the behavior.

JS Undefined variables fail, defaults rescue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

flowchart LR
  V["variables<br/>(inventory, facts, vars)"] --> R["Jinja2 rendering<br/>on the control node"]
  T["site.conf.j2"] --> R
  R --> F["rendered file<br/>sent to the host"]
  F --> C{"differs from<br/>destination?"}
  C -- yes --> Ch["changed: write file"]
  C -- no --> Ok["ok: leave as is"]

The template module renders on the control node and only writes the file when the content differs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line is valid YAML for a task argument?

    A value that begins with {{ must be quoted, otherwise YAML reads the braces as the start of a map.
  2. 2. What does {{ user_shell | default(omit) }} do when user_shell is not defined?

    default(omit) is a special value that tells Ansible to drop the argument, so the module uses its own default.
  3. 3. Where does the template module render a .j2 file?

    Rendering happens on the control node. Only the finished file is transferred, and it is written only when the content differs from the destination.
  4. 4. What is the difference between {{ ... }} and {% ... %}?

    Expressions in {{ }} produce output. Statements in {% %} control flow and produce no output themselves. Comments use {# #}.

Summary

  • {{ }} prints, {% %} runs statements, {# #} comments; text outside is copied as-is.
  • Filters chain with pipes: default, join, map, selectattr, to_json, int, bool cover most needs.
  • Undefined variables are errors; use default(...), or default(omit) to drop a module argument.
  • The template module renders on the control node and reports changed only when the file content differs.
  • Lookups run on the control node; quote any YAML value that starts with {{.

Next: Handlers, Tags and Task Control.