What Jinja2 patterns slow a run down, and how do you avoid them?
AdvancedProductionPerformance and Scale
Answer
Templating cost grows with data size, since variables are re-evaluated lazily every time they are used. Patterns that hurt:
- Looping over
hostvarsorgroups['all']for every host (O(hosts²)), such as building a full cluster config on each of 2,000 hosts. - Large dictionaries defined as variables that reference other variables, re-rendered on each access.
- Heavy filters (
json_query,regex) inside loops.
Mitigations: compute once with run_once: true and set_fact (or delegate_to: localhost and a template), keep big data in files and load it with include_vars or lookup('file'), restrict hostvars to what you need with map('extract', hostvars, 'key'), and reduce group_vars bloat.
More on Performance and Scale
Why can Ansible be slower than a shell script for 100 servers, and what dominates the time?BeginnerHow do you choose the `forks` value?BeginnerWhat is SSH pipelining and why does it help?BeginnerWhich SSH settings matter for performance and stability?IntermediateHow do you find out which tasks are slow?BeginnerHow do you reduce the cost of fact gathering?Intermediate