DevOps / Ansible Interview questions
How does Ansible's Jinja2 templating work in playbooks?
Jinja2 is the templating engine Ansible uses to evaluate expressions like {{ variable }}, conditionals, and loops, both directly inside playbook YAML values and inside .j2 template files processed by the template module.
# Inline in a playbook - name: Show a computed value ansible.builtin.debug: msg: "{{ ansible_facts['memtotal_mb'] // 1024 }} GB of RAM" # Inside a .j2 template file server_name {{ inventory_hostname }}; {% if enable_ssl %} listen 443 ssl; {% endif %}
Inside {{ }} expressions, Ansible supports the full range of Jinja2 features: arithmetic, string manipulation, and filters (like {{ my_list | length }} or {{ name | upper }}) that transform a value inline. Template files use the block-style {% %} syntax for control flow such as if/else and for loops, letting a single template generate different output per host based on that host's variables and facts, which is what makes the template module powerful for generating per-host configuration files from one shared source file.
More Related questions...