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 Infrastructure as Code, and what problems does it solve over click-ops?
- What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?
- What is the difference between configuration management and provisioning?
- What is Terraform, and what is the core plan/apply workflow?
- What does terraform init do?
- What is the Terraform state file, and why is it critical?
- Why should state be stored remotely, and what backend would you use on AWS?
- What is state locking, and why does it matter for teams?