Search code examples
jinja2ansible

ansible Jinja2 template loop for hosts with a var defined


hosts

[mesosSandbox]
mesos1-01d.chalybs.net zoo_id=1
mesos1-02d.chalybs.net zoo_id=2
mesos1-03d.chalybs.net zoo_id=3
mesos1-04d.chalybs.net
mesos1-05d.chalybs.net

I have a template that generates the zookeeper zoo.cfg

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

Is there a way to add an if zoo_id is defined to this loop or can I generate a list via a task in the playbook?


Solution

  • Ansible's if var is defined syntax is derived from jinja. You should be able to check for zoo id right in the loop:

    {% for server in groups[cluster] %}
        {% if hostvars[server].zoo_id is defined %}
            server.{{loop.index}}={{server}}:2888:3888
        {% endif %}
    {% endfor %}
    

    I can't say whether this will compile/run without seeing more of your playbook, but assuming the loop in your question works as is, this will allow you to filter on whether zoo_id is defined.