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

17 views
Skip to first unread message

Rory Schramm

unread,
Jun 29, 2016, 4:42:30 PM6/29/16
to Ansible Project
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?



Kai Stian Olstad

unread,
Jun 30, 2016, 12:47:26 PM6/30/16
to ansible...@googlegroups.com
On 29. juni 2016 22:26, Rory Schramm wrote:
> 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,

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

--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages