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.