Possible to loop over conditional variables?

21 views
Skip to first unread message

Brian Huddleston

unread,
Feb 8, 2016, 12:22:22 AM2/8/16
to Ansible Project
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

Brian Coca

unread,
Feb 8, 2016, 1:22:38 PM2/8/16
to Ansible Project
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([]))}}"




--
Brian Coca

Brian Huddleston

unread,
Feb 11, 2016, 1:09:14 PM2/11/16
to Ansible Project
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)
Reply all
Reply to author
Forward
0 new messages