Configuring Zookeeper from Ansible I'm trying to configure a Zookeeper Cluster with Ansible. As you might know Zookeeper has two important config files.

zookeeper/conf/zoo.cfg

I create this file on each cluster member using this jinja2 template:

{% for host in groups['zookeeper'] %}
server.{{ loop.index }}={{ host }}:2888:3888
{% endfor %}


The result will look like this:

server.1=processing1.srv.mycompany
server.2=processing2.srv.mycompany
server.3=indexing1.srv.mycompany
server.4=indexing2.srv.mycompany
server.5=quorumandmonitoring.srv.mycompany


data/myid

Accordind to the docs this file needs to contain an unique id for each member of the cluster.
To keep everything in sync I would like to have the value after server. in the myid of each host. This means:


myid=1 on processing1
myid=2 on processing2
myid=3 on indexing1
myid=4 on indexing2
myid=5 on quorumandmonitoring


And this is where my problem starts: how can I do this in a clever way? An ideal solution would be to use something like the for host in groups loop. I would rather not add host_vars to my inventory.
In lack of a better idea I chose this rather long approach:

myid.j2

{% for host in groups['zookeeper'] %}
{% if host == inventory_hostname %}
{{ loop.index }}
{% endif %}
{% endfor %}


The idea is to iterate over all hosts and check if the current host being processed matches the host in the list of hosts. If it matches I write the iteration counter to the file.

When I ssh into the boxes I can see their myid files were created according to my need:

[root@quorumandmonitoring data]# cat myid
5