Interview Prep/Ansible/Jinja2, Conditionals and Loops

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.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops