100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Infrastructure as Code — Terraform & Ansible
30 minintermediate

Jinja2 Templating — Filters, Lookups, Conditionals and Loops

Jinja2 is the templating engine that powers Ansible's variable interpolation, conditional logic, and file template rendering. It appears in two contexts: inline within playbook task parameters (when and loop conditions, variable expressions, string manipulations) and in template files rendered by the 'ansible.builtin.template' module. Jinja2 transforms static configuration files into dynamic, environment-aware documents — an Nginx configuration template that renders with different 'worker_processes', 'upstream' addresses, and SSL certificate paths for production and staging environments. Mastering Jinja2 is what allows a single set of playbooks and templates to manage dozens of environments without duplication: the template is written once, and Ansible renders it with the correct variable values for each target.

Jinja2's syntax has three constructs: '{{ expression }}' for output (variable interpolation and function calls that produce a value), '{% statement %}' for control flow (if/elif/else, for loops, set variables, macros), and '{# comment #}' for comments that are stripped from the rendered output. The pipe operator '|' applies filters to transform values — '{{ app_version | upper }}' converts the version string to uppercase, '{{ server_list | length }}' counts the items, '{{ hostname | regex_replace("ip-", "") }}' performs regex substitution. Lookups retrieve data from external sources — 'lookup("file", "/path/to/file")' reads a file's contents, 'lookup("env", "HOME")' reads an environment variable, 'lookup("aws_ssm", "/cricket/prod/db-url")' retrieves a value from SSM Parameter Store. The depth of Jinja2 capabilities available in Ansible is a frequent source of surprise — most string manipulation, list transformation, and data lookup operations that engineers reach for shell scripts for can be expressed directly in Jinja2 within the playbook.

Analogy🏏Cricket
🏏 Think of it like cricket: Terraform Cloud is the ICC's centralised match management platform — instead of each national board (team) maintaining its own scoring system, umpire assignment software and results database (self-managed CI/CD + S3 backend), the ICC platform handles all of this centrally. When a board member proposes a rule change (pull request), the platform automatically simulates the match under the new rules (speculative plan on PR), shows the referees the impact (plan output in PR comment), and requires the match committee to approve (policy gates) before the rule takes effect. The audit log records every change, every approval, and who made each decision — providing the governance and traceability that serious tournament operations require.
Lesson 18 of 33
0% complete