This can be done by accessing the “$groups” dictionary in the template, like so:
{% for host in groups['db_servers'] %}
{{ host }}
{% endfor %}
If we need to access facts also we need to make sure that the facts have been populated. For instance, a play that talks to db_servers:
- hosts: db_servers
tasks:
- debug: msg="Something to debug"
Now, this can be used within a template, like so:
{% for host in groups['db_servers'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}.