Evaluation precedence in conditional expressions

23 views
Skip to first unread message

Lucio Guerchi

unread,
Jul 9, 2019, 9:33:22 AM7/9/19
to Ansible Project

I am new to Ansible and have the following questions, if I have the following conditional, what is going to be parsed first, the filter or the not, were foo is a boolean variable True or False?

when: not foo | bool

Are the following expressions the same? 

when: not foo | bool 

is the same as 

when: not (foo | bool)

Shivharsh Singh

unread,
Jul 10, 2019, 7:37:00 AM7/10/19
to Ansible Project
Hi Lucio,

The filter would be evaluated first and then the not. 

Consider below playbook :

---
- name: Parsing
  hosts
: localhost
  gather_facts
: no
  vars
:
   
- v1: hello
  tasks
:
   
- name: first condition
      debug
:
        msg
: First is true
     
when: not v1 | bool

   
- name: Second condition
      debug
:
        msg
: Second is true
     
when: not (v1 | bool)

Both the conditions in above playbook return TRUE as bool of "Hello" is FALSE and negate of FALSE is TRUE.


Now consider another playbook:

---
- name: Parsing2
  hosts
: localhost
  gather_facts
: no
  vars
:
   
- v1: hello
  tasks
:
   
- name: first condition
      debug
:
        msg
: First is true
     
when: not v1

   
- name: Second condition
      debug
:
        msg
: Second is true
      when: not v1 | bool

In this playbook the first condition would return FALSE as presence of any string is TRUE and negate of TRUE is FALSE.  Whereas in the second condition, the string is first parsed and filtered by bool filter for yaml-style ‘yes, on, true, false, False, Off, NO’ and other words and FALSE is returned as no such word is found. The negate of FALSE is TRUE.

Based on above two observations, it can be concluded that bool filter is evaluated first and then the not operator. 

Therefore, to answer your second question:

Are the following expressions the same?  
when: not foo | bool  
is the same as  
when: not (foo | bool) 

Yes, both the expressions are the same. 
 
Hope this is helpful !

Thanks,
Shivharsh

Lucio Guerchi

unread,
Jul 11, 2019, 9:35:58 AM7/11/19
to Ansible Project
Thanks Shivharsh Singh :)
Reply all
Reply to author
Forward
0 new messages