# Possible to loop over conditional variables?

**URL:** <https://forum.ansible.com/t/possible-to-loop-over-conditional-variables/20480>\
**Category:** Ansible Project\
**Created:** [February 8, 2016, 5:22am UTC](https://forum.ansible.com/t/possible-to-loop-over-conditional-variables/20480 "2016-02-08T05:22:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brian\_Huddleston](https://avatars.discourse-cdn.com/v4/letter/b/2bfe46/32.png) [@Brian\_Huddleston](https://forum.ansible.com/u/Brian_Huddleston)\
**Post date:** [February 8, 2016, 5:22am UTC](https://forum.ansible.com/t/possible-to-loop-over-conditional-variables/20480/1 "2016-02-08T05:22:22Z")

</div>

Hi all, I’m pretty new to Ansible but trying to learn quickly. I was building a role and wanted to perform a check for required variables, and was trying to put them in a loop instead of individually. Here is what I am trying but I keep getting errors:

`

- name: Check for requirement variables  
fail: msg=“Bailing out. This role requires {{ item }}”  
when: {{ item }} is undefined  
with\_items:
- nginx\_domain
- nginx\_port

`

Instead of having declare them individually like this:

`

- name: Check for requirement nginx\_domain  
fail: msg=“Bailing out. This role requires ‘nginx\_domain’”  
when: nginx\_domain is undefined

- name: Check for requirement nginx\_port  
fail: msg=“Bailing out. This role requires ‘nginx\_port’”  
when: nginx\_domain is undefined

`

Is this possible? Or am I trying to fit a square peg in a round hole?

Thanks for any feedback

– BrianH

---

<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:** [February 8, 2016, 6:22pm UTC](https://forum.ansible.com/t/possible-to-loop-over-conditional-variables/20480/2 "2016-02-08T18:22:32Z")

</div>

when executes inside the loop so it cannot prevent undefined errors,  
the following does a union of the lists but makes sure to default each  
to an empty list in case they are undefined:

with\_items:"{{nginx\_domain|default()|union(nginx\_port|default())}}"

---

<div class="post-metadata">

**Author:** ![Brian\_Huddleston](https://avatars.discourse-cdn.com/v4/letter/b/2bfe46/32.png) [@Brian\_Huddleston](https://forum.ansible.com/u/Brian_Huddleston)\
**Post date:** [February 11, 2016, 6:09pm UTC](https://forum.ansible.com/t/possible-to-loop-over-conditional-variables/20480/3 "2016-02-11T18:09:14Z")

</div>

Thanks for the feedback, it took a bit for me to understand. I think I might be better off declare them individually in my example since that is much easier for other to read and add to and I can see possible text errors with all the brackets and parens that have to be used for each additional item. (say I wanted to add 3 more variables to check)
