# for and if in template

**URL:** <https://forum.ansible.com/t/for-and-if-in-template/15352>\
**Category:** Ansible Project\
**Created:** [May 28, 2014, 12:12pm UTC](https://forum.ansible.com/t/for-and-if-in-template/15352 "2014-05-28T12:12:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Joachim\_Friberg](https://avatars.discourse-cdn.com/v4/letter/j/6a8cbe/32.png) [@Joachim\_Friberg](https://forum.ansible.com/u/Joachim_Friberg)\
**Post date:** [May 28, 2014, 12:12pm UTC](https://forum.ansible.com/t/for-and-if-in-template/15352/1 "2014-05-28T12:12:46Z")

</div>

Hi,

I’m trying to get this:

`define hostgroup{ hostgroup_name TableswitchesSweden members dlg-prd-office-tbs01,dlg-prd-office-tbs02,dlg-prd-office-tbs03,dlg-prd-office-tbs04,dlg-prd-office-tbs05,dlg-prd-office-tbs07,dlg-prd-office-tbs08,dlg-prd-office-tbs10,dlg-prd-office-tbs11,dlg-prd-office-tbs12,dlg-prd-office-tbs13,dlg-prd-office-tbs14,dlg-prd-office-tbs15,dlg-prd-office-tbs16,dlg-prd-office-tbs17,dlg-prd-office-tbs18,dlg-prd-office-tbs19,dlg-prd-office-tbs20 }`

From this:

`

extra\_hosts:

- file\_name: dlg-prd-office-tbs22  
host\_check\_name: tbs22  
host\_checks: ‘http,generic-host,base-notify’  
host\_check\_ip: 10.0.49.71  
icon\_set: network\_service  
type: switches
- file\_name: dlg-prd-office-tbs23  
host\_check\_name: tbs23  
host\_checks: ‘http,generic-host,base-notify’  
host\_check\_ip: 10.0.49.72  
icon\_set: network\_service  
type: switches
- file\_name: dlg-prd-office-tbs24  
host\_check\_name: tbs24  
host\_checks: ‘http,generic-host,base-notify’  
host\_check\_ip: 10.0.49.73  
icon\_set: network\_service  
type: switches
- file\_name: dlg-prd-office-tbs25  
host\_check\_name: tbs25  
host\_checks: ‘http,generic-host,base-notify’  
host\_check\_ip: 10.0.49.74  
icon\_set: network\_service  
type: switches

`

I was thinking about something similar to

`... memebers {% for unit in extra_hosts[0:] %}{% if "tbs" in unit.host_check_name %}{{ extra_hosts.file_name }}, {% endif %} {% endfor %} ...`

How wrong might I be?

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan1](https://avatars.discourse-cdn.com/v4/letter/m/5e9695/32.png) [@Michael\_DeHaan1](https://forum.ansible.com/u/Michael_DeHaan1)\
**Post date:** [May 28, 2014, 12:39pm UTC](https://forum.ansible.com/t/for-and-if-in-template/15352/2 "2014-05-28T12:39:54Z")

</div>

It’s probably fine.

Jinja2 has some filters like “map” and “reject” but it seems difficult to do something like an “in” query and does not allow Python list comprehensions.

It would be cleaner in most people’s templates if it could be done on more than one line, but it seems you cannot.

Others may leverage templates more and may have some other suggestions.
