# template with groups as a variable

**URL:** <https://forum.ansible.com/t/template-with-groups-as-a-variable/19742>\
**Category:** Ansible Project\
**Created:** [November 12, 2015, 12:50pm UTC](https://forum.ansible.com/t/template-with-groups-as-a-variable/19742 "2015-11-12T12:50:18Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Edgardo\_Vega](https://avatars.discourse-cdn.com/v4/letter/e/b2d939/32.png) [@Edgardo\_Vega](https://forum.ansible.com/u/Edgardo_Vega)\
**Post date:** [November 12, 2015, 12:50pm UTC](https://forum.ansible.com/t/template-with-groups-as-a-variable/19742/1 "2015-11-12T12:50:18Z")

</div>

I am trying to do the following where I index groups by a variable instead of hardcoding it. Is that possible somehow?

{% for host in groups[‘{{VAR}}’] %}

STUFF

{% endfor %}

Thanks in advance,

Edgardo

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [November 12, 2015, 12:59pm UTC](https://forum.ansible.com/t/template-with-groups-as-a-variable/19742/2 "2015-11-12T12:59:15Z")

</div>

You can’t nest jinja2 delimiters. You just use bare variable names inside such as:

{% for host in groups[VAR] %}

---

<div class="post-metadata">

**Author:** ![Edgardo\_Vega](https://avatars.discourse-cdn.com/v4/letter/e/b2d939/32.png) [@Edgardo\_Vega](https://forum.ansible.com/u/Edgardo_Vega)\
**Post date:** [November 12, 2015, 1:00pm UTC](https://forum.ansible.com/t/template-with-groups-as-a-variable/19742/3 "2015-11-12T13:00:23Z")

</div>

I figured it out. You can just do the following and it will work.

{% for host in groups[VAR] %}

---

<div class="post-metadata">

**Author:** ![Edgardo\_Vega](https://avatars.discourse-cdn.com/v4/letter/e/b2d939/32.png) [@Edgardo\_Vega](https://forum.ansible.com/u/Edgardo_Vega)\
**Post date:** [November 12, 2015, 1:44pm UTC](https://forum.ansible.com/t/template-with-groups-as-a-variable/19742/4 "2015-11-12T13:44:59Z")

</div>

Thanks Matt! is there way to do this in a playbook. The first one works the second one doesn’t.

- debug: msg=“hey {{ item }}”  
with\_items: groups[‘tag\_env\_prod’]

- debug: msg=“hey {{ item }}”  
with\_items: groups[‘{{group\_name}}’]

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [November 12, 2015, 4:08pm UTC](https://forum.ansible.com/t/template-with-groups-as-a-variable/19742/5 "2015-11-12T16:08:09Z")

</div>

- debug: msg="hey {{ item }}"  
&nbsp;&nbsp;&nbsp;&nbsp;with\_items: "{{groups[group\_name]}}"
