Interview Infrastructure as Code (Terraform, Ansible)

What is a Jinja2 template, and how is it used in Ansible?

Infrastructure as Code (Terraform, Ansible) · Advanced level

Answer

A Jinja2 template is a text file with variables, loops, and conditionals that Ansible renders for each host. It is commonly used for application config files, systemd units, Nginx configs, and Kubernetes manifests where values vary by host or environment.

Technical explanation

Templates use host variables and facts to produce host-specific files.

Validate rendered configs before replacing critical files when modules support validate.

A template change often notifies a handler to reload or restart a service.

Prefer idempotent modules over shell so repeated runs are safe and change reporting is meaningful.

Separate reusable role logic from inventory-specific variables so the same automation works across environments.

Run lint, syntax checks, check mode where useful, and staged rollouts before production-wide changes.

Hands-on example

1. Create templates/app.conf.j2:

port={{ app_port }}

environment={{ env }}

{% for upstream in upstreams %}

upstream={{ upstream }}

{% endfor %}

2. Render it safely:

- name: Render app config

ansible.builtin.template:

src: app.conf.j2

dest: /etc/app/app.conf

owner: root

group: root

mode: '0644'

validate: '/usr/local/bin/app --check-config %s'

notify: Restart app

3. Run with --diff to show exactly what changed before the handler restarts the service.

4. Add defaults for app_port and upstreams so the role works predictably.

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Infrastructure as Code (Terraform, Ansible) interview questions

← All Infrastructure as Code (Terraform, Ansible) questions