Ansible: Automate Everything from First Playbook to Production · Variables, Facts and Jinja2 Templates

Jinja2 Templates: Config Files That Adapt to Each Host

Write a single Jinja2 template that produces the right nginx or application config for every environment, using variables, conditionals, loops and filters.

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

What you'll build

An Nginx configuration template that adapts its upstream servers, worker count, TLS settings and logging based on which environment and host it is deployed to — all from one .j2 file.

The idea

The ansible.builtin.template module renders a Jinja2 file (.j2) on the control node and copies the result to the managed host. Inside the template you have access to every Ansible variable: inventory vars, role defaults, facts, registered results.

Jinja2 basics:

Syntax Purpose Example
{{ var }} Output a value listen {{ app_port }};
{% if ... %} Conditional block {% if env == 'production' %}
{% for x in list %} Loop {% for srv in upstreams %}
{# comment #} Comment (not in output) {# managed by Ansible #}
{{ x | filter }} Apply a filter {{ list | join(', ') }}

Useful filters: default('value') (fallback), join(',') (list to string), to_json / to_yaml (serialise), regex_replace(pattern, replacement), upper / lower, int (cast to integer).

The validate parameter lets you test the generated config before Ansible commits it — if validation fails, the task fails and the old config stays in place.

The code

Nginx config from a Jinja2 template
mkdir -p template-demo/templates template-demo/group_vars

cat > template-demo/templates/nginx.conf.j2 <<'TMPL'
{# Managed by Ansible — do not edit manually #}
worker_processes {{ ansible_processor_vcpus | default(2) }};

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

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent';

    access_log {{ access_log_path | default('/var/log/nginx/access.log') }} main;
    error_log  {{ error_log_path | default('/var/log/nginx/error.log') }} {{ log_level | default('warn') }};

    upstream app {
{% for server in upstream_servers %}
        server {{ server.host }}:{{ server.port }} weight={{ server.weight | default(1) }};
{% endfor %}
    }

    server {
        listen {{ listen_port | default(80) }};
        server_name {{ server_name | default('_') }};

{% if enable_tls | default(false) %}
        listen {{ tls_port | default(443) }} ssl;
        ssl_certificate     {{ tls_cert_path }};
        ssl_certificate_key {{ tls_key_path }};
        ssl_protocols       TLSv1.2 TLSv1.3;
{% endif %}

        location / {
            proxy_pass http://app;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
{% if enable_tls | default(false) %}
            proxy_set_header X-Forwarded-Proto https;
{% endif %}
        }

        location /health {
            return 200 'ok';
            add_header Content-Type text/plain;
        }
    }
}
TMPL

cat > template-demo/group_vars/staging.yml <<'EOF'
listen_port: 8080
log_level: info
worker_connections: 512
enable_tls: false
upstream_servers:
  - host: 10.0.1.10
    port: 3000
  - host: 10.0.1.11
    port: 3000
EOF

cat > template-demo/group_vars/production.yml <<'EOF'
listen_port: 80
log_level: warn
worker_connections: 4096
enable_tls: true
tls_port: 443
tls_cert_path: /etc/ssl/certs/app.pem
tls_key_path: /etc/ssl/private/app.key
server_name: app.example.com
upstream_servers:
  - host: 10.0.2.10
    port: 3000
    weight: 3
  - host: 10.0.2.11
    port: 3000
    weight: 3
  - host: 10.0.2.12
    port: 3000
    weight: 2
EOF

cat > template-demo/inventory.ini <<'EOF'
[staging]
localhost ansible_connection=local

[production]
localhost ansible_connection=local
EOF

cat > template-demo/deploy-config.yml <<'EOF'
- name: Deploy nginx config (staging)
  hosts: staging
  gather_facts: true
  tasks:
    - name: Render nginx config
      ansible.builtin.template:
        src: templates/nginx.conf.j2
        dest: /tmp/nginx-staging.conf
        mode: "0644"

    - name: Show rendered config
      ansible.builtin.command: cat /tmp/nginx-staging.conf
      register: rendered
      changed_when: false

    - name: Display
      ansible.builtin.debug:
        msg: "{{ rendered.stdout }}"
EOF

cd template-demo
ansible-playbook -i inventory.ini deploy-config.yml 2>/dev/null

Output

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

The staging config has no TLS block, two upstream servers and port 8080. The production version — using the same template — would include TLS, three weighted upstreams and port 80/443.

Validate a config before deploying:

- name: Deploy nginx config with validation
  ansible.builtin.template:
    src: templates/nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    mode: "0644"
    validate: nginx -t -c %s
  notify: reload nginx

If nginx -t fails, the task fails and the old config stays — the service never loads a broken config.

Common mistakes

Not using | default() for optional variables — if a variable is undefined and you don't provide a default, the template render fails. Always use | default('fallback') for variables that might not exist in every environment.

Forgetting that {% if var %} treats 0, "" and [] as false — if you need to check whether a variable is defined (even if its value is falsy), use {% if var is defined %}.

Editing rendered config files on the server — the next Ansible run overwrites manual changes. All edits must go through the template and variables. Add a comment header (# Managed by Ansible) so operators know.

Key points

  • ansible.builtin.template renders .j2 files with full access to Ansible variables and facts.
  • Use | default() for optional values and {% if %} / {% for %} for conditional and repeated blocks.
  • The validate parameter tests generated config before committing — essential for nginx, sudoers, sshd_config.
  • One template + different variables per environment replaces maintaining separate config files.

Practice questions

How do you prevent Ansible from deploying a broken nginx config?

Answer

Use the validate parameter on the template task: validate: nginx -t -c %s. Ansible tests the rendered file before replacing the live config.

What happens if a Jinja2 template references an undefined variable without a `| default()` filter?

Answer

The template render fails with an 'undefined variable' error and the task fails — the destination file is not changed.

How do you iterate over a list of upstream servers in a Jinja2 template?

Answer

Use {% for server in upstream_servers %} ... {% endfor %} to loop over each server and output its host:port.

Open in the app to mark lessons complete, take notes and track your progress.

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

Was this page helpful?

Report a mistake