Conditionals - when: <var1> and <var2> is defined works in a weird way

Hi,

I am not sure whether someone has come across this issue previously - trying to search the group for ‘when’ and ‘is defined’ did not yield me anything useful. So I am posting it as a new topic here.
I have encountered that in case I use ‘when:’ clause where I need to test whether one variable is set to ‘true’ and another one is defined, the following playbook triggers action even if the first variable is ‘false’:

cat > test_playbook.yaml <<EOF

Forgot to mention that I use

ansible-playbook 1.5 (devel 27199dc219) last updated 2013/12/04 20:39:15 (GMT +1100)

"false" != false. You have a string/boolean issue. Aka, the var1 is not the boolean value false, but the string value "false".

Hi Adam,

I do not think so, please see my example above with the

ansible-playbook -i host -v test_playbook.yaml --extra-vars “var1=false var2=‘something’”

being executed as expected (skipped). In case var1 was a string, the

when: var2 is defined
when: var1

conditions would evaluate to true IMHO and the action would be triggered.

I’m not certain but…

According to the documentation when: takes a jinja 2 expression.

I don’t know the order of precedence in jinja 2, but
var1 and var2 is defined
could be read as
(var1 and var2) is defined
or
var1 and (var2 is defined)

I suspect that you are looking for the second one, but you MIGHT be getting the first. have you considered grouping the relevant parts so that you have
(var1) and (var2 is defined)
To me, that seems a lot clearer as to the intent.

Adam

You most certainly have a string to bool comparison issue going on.

You can change this by using the bool filter.

when: var1|bool and var2 is defined

When I use this, var1 being "false" will still cause the task to be skipped as expected.

-jlk

Hi Jesse,

Thanks for getting to the bottom of this and providing a working solution! Works as charm indeed! Jinja framework is crazy IMHO.

Adam: grouping does not help, I tried it before submitting my first request, as well as swapping the order.

The issue is solved, thank you! I wonder what is the process of altering documentation on docs.ansible.com, googling for it provided me a link which does not contain the text that is shown in the search preview.
Does submitting an issue to the Ansible repo sound like a proper idea?

Yeah, the docs are driven from the ansible code base -- so an issue (or better yet a pull request) is appropriate.

-jlk