# trouble looping through host list with conditional check and loop.last check to supress seperator on last output

**URL:** <https://forum.ansible.com/t/trouble-looping-through-host-list-with-conditional-check-and-loop-last-check-to-supress-seperator-on-last-output/21895>\
**Category:** Ansible Project\
**Created:** [June 29, 2016, 8:26pm UTC](https://forum.ansible.com/t/trouble-looping-through-host-list-with-conditional-check-and-loop-last-check-to-supress-seperator-on-last-output/21895 "2016-06-29T20:26:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rory\_Schramm](https://avatars.discourse-cdn.com/v4/letter/r/c89c15/32.png) [@Rory\_Schramm](https://forum.ansible.com/u/Rory_Schramm)\
**Post date:** [June 29, 2016, 8:26pm UTC](https://forum.ansible.com/t/trouble-looping-through-host-list-with-conditional-check-and-loop-last-check-to-supress-seperator-on-last-output/21895/1 "2016-06-29T20:26:56Z")

</div>

I have a jinja template file that’s iterating through the play hosts and checking which site each hosts belongs to that should output like this:

192.168.1.1, 192.168.1.2, 192.168.1.3,

{%- for host in play\_hosts %}{% if hostvars[host][‘site’] == site %}{{ host }}{% if not loop.last %}, {% endif %}{% endif %}{% endfor -%}

However, I’m getting this jinja output instead. It’s not suppressing the separator on the last loop item iteration…

192.168.1.1, 192.168.1.2, 192.168.1.3, 192.168.1.4,

If I remove the if check for the site variable it correctly removes the seperator from the last loop iterate. However, now I have both sites in my output which I don’t want.

{%- for host in play\_hosts %}{% if hostvars[host][‘site’] == site %}{{ host }}{% endif %}{% endfor -%}  
192.168.1.1, 192.168.1.2, 192.168.1.3, 192.168.1.4, 192.168.2.1, 192.168.2.2, 192.168.2.3, 192.168.2.4

Any Idea’s on how to fix this?

---

<div class="post-metadata">

**Author:** ![Kai\_Stian\_Olstad](https://avatars.discourse-cdn.com/v4/letter/k/e19adc/32.png) [@Kai\_Stian\_Olstad](https://forum.ansible.com/u/Kai_Stian_Olstad)\
**Post date:** [June 30, 2016, 4:47pm UTC](https://forum.ansible.com/t/trouble-looping-through-host-list-with-conditional-check-and-loop-last-check-to-supress-seperator-on-last-output/21895/2 "2016-06-30T16:47:15Z")

</div>

Not tested, but something like this should work

{% set div = joiner(", ") %}  
{% for host in play\_hosts %}  
{%- if hostvars[host]['site'] == site %}  
{{ div }}{{ host }}  
{%- endif %}  
{% endfor %}
