42

I have the following code

- set_fact:
    MY_HOSTNAME: "SOME VALUE"
    MY_SERVER: "00.00.00.00"
- name: Get MY server
  set_fact:
    MY_SERVER: "{{ groups[MY_HOSTNAME][0] }}"
  when: groups[MY_HOSTNAME] is defined

In the above code, groups[MY_HOSTNAME] is an array. What is the best way to check that groups[MY_HOSTNAME] is defined and also that it is not empty If it is either of that I want the value 00.00.00.00 to be assigned to MY_SERVER

kosta
  • 4,302
  • 10
  • 50
  • 104

4 Answers4

53

I don't know if it's version specific, but I'm currently running ansible-2.3.2 on RHEL6 and I had to put quotes around the group name to get it to work for me:

when: groups["GROUP_NAME"] is defined and (groups["GROUP_NAME"]|length>0)

Edit: I couldn't add this as a comment to techraf's answer because I don't have enough reputation.

Phil M
  • 751
  • 4
  • 6
  • Thank you... but I'm still frustrated that len(foo) (the Python way of checking length) doesn't work. – pedz Apr 12 '19 at 18:44
  • 5
    Be careful with this: `| length` works on a string as well. If the input is a string and not an array it will simply return the length of the string – EM0 Aug 28 '19 at 11:13
32

list | length filter returns the number of elements. If it is zero, the list is empty.

For a conditional value use if or ternary filter (example in this answer).

For a composite conditional (groups[MY_HOSTNAME]| default([])) | length.

techraf
  • 64,883
  • 27
  • 193
  • 198
2

You can first check if it is indeed a list and then check if it has more than one element:

when:
  - groups['MY_GROUP_NAME'] is defined
  - groups['MY_GROUP_NAME'] is not string
  - groups['MY_GROUP_NAME'] is not mapping
  - groups['MY_GROUP_NAME'] is iterable
  - groups['MY_GROUP_NAME'] | length > 0

You can also use type_debug, but it is discouraged by the official docs:

when:
  - groups['MY_GROUP_NAME'] is defined
  - groups['MY_GROUP_NAME'] | type_debug == 'list'
  - groups['MY_GROUP_NAME'] | length > 0

Use 'MY_GROUP_NAME', if you directly provide the name of the group as a string or use MY_GROUP_NAME (without quotes), if it is a variable.

stackprotector
  • 10,498
  • 4
  • 35
  • 64
0

try this one (it checks if variable is defined and if it is a iterable like list)

when: (groups["GROUP_NAME"] is defined) and (groups["GROUP_NAME"] is iterable)
Michal Zmuda
  • 5,381
  • 3
  • 43
  • 39
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Oct 12 '22 at 20:02