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.
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
- What is the difference between Ansible roles and collections?
- How do you run an Ansible playbook in check (dry-run) mode?
- What is delegate_to, and when would you use it?
- What is the difference between state: present and state: latest, and the risk of latest?
- What is max_fail_percentage, and how does it protect a rollout?
- How do you handle host-specific differences across a mixed fleet?
- What is the serial keyword, and how does it enable rolling updates?
- How would you orchestrate a rolling, health-checked upgrade across servers with Ansible?