# For loop in template with every host in group except the current one

**URL:** <https://forum.ansible.com/t/for-loop-in-template-with-every-host-in-group-except-the-current-one/12780>\
**Category:** Ansible Project\
**Created:** [May 8, 2013, 5:04pm UTC](https://forum.ansible.com/t/for-loop-in-template-with-every-host-in-group-except-the-current-one/12780 "2013-05-08T17:04:16Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Steve\_Irvine](https://avatars.discourse-cdn.com/v4/letter/s/9fc348/32.png) [@Steve\_Irvine](https://forum.ansible.com/u/Steve_Irvine)\
**Post date:** [May 8, 2013, 5:04pm UTC](https://forum.ansible.com/t/for-loop-in-template-with-every-host-in-group-except-the-current-one/12780/1 "2013-05-08T17:04:16Z")

</div>

Hi Everyone,

I’m trying to work out if something is possible. Imagine a playbook to configure a vpn mesh between a group of servers. If I created a group called ‘vpn’, then on each server I’d need to build template configs for each vpn tunnel with the server we’re writing the file one at one end and then all the other servers in the group at the other.

Therefore; is there a way to make a for loop either in the playbook or template that says:

(Excuse my pseudocode)

{% for host in groups[‘vpn’] except [‘thishost’] %}

vpn left side = {{ hostvars[thishost].ansible\_hostname }}

vpn right side = {{ hostvars[host].ansible\_hostname }}

{% endfor %}

Hope that makes sense…

Steve

---

<div class="post-metadata">

**Author:** ![Brian\_Coca1](https://avatars.discourse-cdn.com/v4/letter/b/278dde/32.png) [@Brian\_Coca1](https://forum.ansible.com/u/Brian_Coca1)\
**Post date:** [May 8, 2013, 5:07pm UTC](https://forum.ansible.com/t/for-loop-in-template-with-every-host-in-group-except-the-current-one/12780/2 "2013-05-08T17:07:28Z")

</div>

iirc you need the loopcontrol extensions, which you can load, then just add indside the for loop:

if host = inventory\_hostname  
continue  
endif

---

<div class="post-metadata">

**Author:** ![Oleg](https://avatars.discourse-cdn.com/v4/letter/o/ebca7d/32.png) [@Oleg](https://forum.ansible.com/u/Oleg)\
**Post date:** [May 8, 2013, 5:28pm UTC](https://forum.ansible.com/t/for-loop-in-template-with-every-host-in-group-except-the-current-one/12780/3 "2013-05-08T17:28:51Z")

</div>

> {% for host in groups[‘vpn’] if host != thishost %}
> 
> vpn left side = {{ hostvars[thishost].ansible\_hostname }}  
> vpn right side = {{ hostvars[host].ansible\_hostname }}
> 
> {% endfor %}

should work also

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan2](https://avatars.discourse-cdn.com/v4/letter/m/da6949/32.png) [@Michael\_DeHaan2](https://forum.ansible.com/u/Michael_DeHaan2)\
**Post date:** [May 8, 2013, 8:00pm UTC](https://forum.ansible.com/t/for-loop-in-template-with-every-host-in-group-except-the-current-one/12780/4 "2013-05-08T20:00:10Z")

</div>

It would be cleaner to just put the if statement inside the for loop.
