How do you generate a config section from inventory groups, for example an HAProxy backend?
IntermediateConceptJinja2, Conditionals and Loops
Answer
Loop over groups[...] and read host data through hostvars.
backend app
balance roundrobin
{% for h in groups['app'] | sort %}
server {{ h }} {{ hostvars[h]['ansible_host'] | default(h) }}:8080 check
{% endfor %}
Add a sort so the file does not reorder between runs. Make sure the load balancer play runs after (or gathers) facts for the app hosts when you depend on facts instead of inventory variables.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner