Substituting lists in playbook

Hi there,
I’m trying to do a pretty simple thing and I can’t make it work, I’ll be grateful for any help.
I’m trying to assign a list of hosts from a group to a variable, which later on, I would like to iterate over in j2 template. Here is an extract:

I have an /etc/ansible/hosts file:

[zookeepers]
node01 id=1
node02 id=2
node03 id=3

part of playbook zookeeper.yml:

  • hosts: zookeepers
    sudo: True
    roles:
  • role: ansible-zookeeper
    version: “3.4.6”
    zookeeper_hosts: “{{ groups.zookeepers }}” # I would like to assign all nodes of zookeepers group to a variable

part of template zoo.cfg.j2:

{% for server in zookeeper_hosts %}

server.{{ hostvars[“{{server}}”][“id”] }} = {{server}}:2888:3888

{% endfor %}

This code does not work, because zookeeper_hosts variable is a string, and iterating over it means iterating over letters of the string. Not what I wanted.

I spent few hours trying weird combinations to do it, but I failed… The things that worked:

  1. Hard coding the list of hosts in playbook, instead of using groups.zookeepers variable
  2. Creating string joined by ‘,’ in playbook ( "{{ groups.zookeepers | join(‘,’) }} " and then using zookeeper_hosts.split(‘,’) in j2 template. I wouldn’t like to modify the template as it is created by someone else. Any way, it doesn’t seem clean.

Please anyone help me with this.
Thank you!
Krzysztof

you can use the groups variable directly in your template, as it is a
list, also you are stacking moustaches and that does not work!!!

no {{ {{ }} }} , you only need one set {{ }}, anything inside you do
not quote is var:

{% for server in groups['zookeepers'] %}

server.{{ hostvars[server]["id"] }} = {{server}}:2888:3888

{% endfor %}