Ansible Tutorial · Configuration Management · Lesson 12 of 20

Ansible Templates (Jinja2)

Generate config files that adapt to each host with Jinja2 templates.

Members can save this page, take notes and track progress. See membership · Sign in

The template module

The template module renders a Jinja2 file (.j2) on the control node and copies the result to the managed node. Variables, facts and filters are expanded before the file is written.

- name: Render nginx config
  ansible.builtin.template:
    src: templates/nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: "0644"
  notify: restart nginx

Jinja2 syntax

Variables

server_name {{ ansible_fqdn }};
listen {{ http_port | default(80) }};

Conditionals

{% if enable_ssl %}
listen 443 ssl;
ssl_certificate /etc/ssl/{{ domain }}.crt;
{% endif %}

Loops

{% for server in backend_servers %}
server {{ server.host }}:{{ server.port }};
{% endfor %}

Useful filters

Filter Example Result
default {{ port | default(8080) }} 8080 if unset
join {{ my_list | join(', ') }} "a, b, c"
to_json {{ config | to_json }} JSON string
to_yaml {{ config | to_yaml }} YAML string
upper/lower {{ name | upper }} "MYAPP"
regex_replace {{ path | regex_replace('/+$', '') }} strip trailing /
ipaddr {{ ip | ansible.utils.ipaddr('address') }} filter IPs

Full template example

templates/nginx.conf.j2:

# Managed by Ansible — do not edit manually
worker_processes {{ ansible_processor_vcpus }};

events {
    worker_connections {{ worker_connections | default(1024) }};
}

http {
    upstream app {
{% for server in app_servers %}
        server {{ server }}:{{ app_port }};
{% endfor %}
    }

    server {
        listen {{ http_port | default(80) }};
        server_name {{ server_name }};

{% if enable_ssl | default(false) %}
        listen 443 ssl;
        ssl_certificate /etc/ssl/certs/{{ server_name }}.crt;
        ssl_certificate_key /etc/ssl/private/{{ server_name }}.key;
{% endif %}

        location / {
            proxy_pass http://app;
        }
    }
}

validate — test before deploying

The validate parameter runs a command before replacing the file. If validation fails, the old file is kept:

- name: Deploy nginx config
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    validate: "nginx -t -c %s"
  notify: restart nginx

%s is replaced with the path to the rendered temporary file. If nginx -t fails, the config is not deployed and the task fails.

Render a Jinja2 template
cat > /tmp/greeting.j2 << 'TMPL'
Hello {{ name }}!
Today is {{ ansible_date_time.date }}.
{% if role == "admin" %}
You have admin access.
{% else %}
You have standard access.
{% endif %}
TMPL
cat > /tmp/template_demo.yml << 'EOF'
---
- name: Template demo
  hosts: localhost
  connection: local
  vars:
    name: Alice
    role: admin
  tasks:
    - name: Render template
      ansible.builtin.template:
        src: /tmp/greeting.j2
        dest: /tmp/greeting.txt
    - name: Show result
      ansible.builtin.command: cat /tmp/greeting.txt
      register: out
    - debug:
        var: out.stdout
EOF
ansible-playbook /tmp/template_demo.yml

Output

PLAY [Template demo] **********************************************************

TASK [Gathering Facts] ********************************************************
ok: [localhost]

TASK [Render template] ********************************************************
changed: [localhost]

TASK [Show result] ************************************************************
changed: [localhost]

TASK [debug] ******************************************************************
ok: [localhost] => {
    "out.stdout": "Hello Alice!\nToday is 2026-11-25.\n\nYou have admin access."
}

PLAY RECAP ********************************************************************
localhost                  : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Run this on your computer — see “Get Started” for setup.

Test yourself

What does the 'validate' parameter in the template module do?

  1. Validates the Jinja2 syntax
  2. Runs a command to test the rendered file before deploying it
  3. Checks file permissions
  4. Validates variable types
Show answer

Answer: Runs a command to test the rendered file before deploying it

The validate parameter runs a command (e.g. 'nginx -t -c %s') against the rendered temp file. If the command fails, the old file is kept and the task reports failure.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake