Understanding Conditional Conditional Expressions

I am struggling to understand some dangerous behavior, and although I solved the problem, I wonder if anyone can shed light on why this problem behaves the way it does.

I deleted the extraneous details of the assignment and pushed it back to that point .

The problem occurs when passing variables as booleans, such as:

ansible-playbook -i ./local.hosts ./test.yml -e "x=true y=false z=false" 

I can use these variables in when clauses, and they work as expected:

  - name: do_something_if_x_is_true shell: echo kill all humans when: x 

It seems to me that this demonstrates that x transmitted and parsed as logical. But as soon as x used in the compound condition, (x and y) - everything goes wrong, and the variables stop behaving.

To solve this problem, I can explicitly specify x as a boolean:

  - name: do_something_when_x_and_y_are_true shell: echo finally robotic beings rule the world when: (x|bool and y|bool) 

And great, everything works as I expect.

I would really like to understand this behavior, can anyone explain?

+4
source share
1 answer

Vars passed on the command line do not pass through the YAML parser, which usually makes a type inference. In the absence of this or some other hint (for example, a bool filter) they are simply tied to Jinja. Jinja is a pretty thin shell over Python, and Python says that any non-empty string is True. In the situation below, the YAML parser performs type inference since vars are defined in a string:

 - hosts: all vars: x: false y: false tasks: - name: do_something_if_x_is_true shell: echo kill all humans when: x or y # humans are safe! 

For security reasons, if you don't know where your vars come from, it's probably a good idea to use bool filters.

+4
source

All Articles