Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if arrays are defined and not empty in ansible

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

like image 275
kosta Avatar asked Dec 08 '17 07:12

kosta


People also ask

How do you know if a variable is empty in Ansible?

I use | trim != '' to check if a variable has an empty value or not.

How is it possible to check if a variable is defined in Ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. Show activity on this post.


1 Answers

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.

like image 137
Phil M Avatar answered Sep 21 '22 09:09

Phil M