1

I have a hosts file including the following contents

[elasticsearch_nodes]
host1 os=linux
host2 os=linux
host3 os=linux

In a .j2 template I want to get the the list of [elasticsearch_nodes]

{{ some_ansible_magic_here }}

# should output "host1","host2","host3"

How do I do this?

I do have this as well to help with the quotes and the commas when I have the list.

{% for host in some_sort_of_ansible_magic_to_get_me_that_list_i_need %}
 "{{ host }}"{% if not loop.last %},{% endif %}
{% endfor %}
1

The magic you need is magic variables, in particular the groups variable, which is

a dictionary/map with all the groups in inventory and each group has the list of hosts that belong to it.

Then you can use template filters to format the list: use map with regex_replace to add the quotes to all list elements and then join them into the final result.

{{ groups['elasticsearch_nodes']|map('regex_replace', '(.*)', '"\\1"')|join(',') }}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.