ansible list groups host belongs to in template module
In my #ansible playbook I needed to list the groups the current host belongs in a config file (sensu client.json "subscriptions"). I had the following line in my template file
{% set count = [] %}[{% for gname in groups %}{% for host in groups[gname] %}{% if hostvars[host]["ansible_default_ipv4"]["address"] == ansible_ssh_host %}{% if count|length > 0 %},{% endif %}"{{ gname }}"{% if count.append(1) %}{% endif %}{% endif %}{% endfor %}{% endfor %}]
This would loop over all groups, and for each group it will loop over the hosts and compares the ansible_ssh_host
to hostvars[host]["ansible_default_ipv4"]["address"]
(current host's ip)
the count list is used to determine when i have written one group already and then add a ',' before the group onwards, as i needed to writethem in the form [ group1, group2, group3 ] and the format was not tolerant to extra ','
enjoy
Written by Ramez Hanna
Related protips
2 Responses

This looks like is misformatted in Coderwall.
You can fix this by indenting each line with 4 spaces.
Trivally speaking, this is the way to list group names for the active host:
{% for group in group_names %}
{{ group }}
{% endfor %}
Also this part:
if hostvars[host]["ansible_default_ipv4"]["address"] == ansible_ssh_host
Looks a little strange.
If you just want to join a list, there's also no need for the count:
{{ ",".join(listvar) }}

Thanks michael for your comment, actually i needed to keep it all in oneline because it needs to be all in one line in the template
but that group_names seems to be so trivial that it makes me me ashamed