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


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:



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.

1 Answer 1


In lack of a better idea I chose this rather long approach:


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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