# Substituting lists in playbook

**URL:** <https://forum.ansible.com/t/substituting-lists-in-playbook/18576>\
**Category:** Ansible Project\
**Created:** [June 23, 2015, 12:10pm UTC](https://forum.ansible.com/t/substituting-lists-in-playbook/18576 "2015-06-23T12:10:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Krzysztof\_Zarzycki](https://avatars.discourse-cdn.com/v4/letter/k/94ad74/32.png) [@Krzysztof\_Zarzycki](https://forum.ansible.com/u/Krzysztof_Zarzycki)\
**Post date:** [June 23, 2015, 12:10pm UTC](https://forum.ansible.com/t/substituting-lists-in-playbook/18576/1 "2015-06-23T12:10:16Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [June 26, 2015, 4:28am UTC](https://forum.ansible.com/t/substituting-lists-in-playbook/18576/2 "2015-06-26T04:28:00Z")

</div>

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 %}
