Ansible “when variable == true” not behaving as expected

Question:

I have the following tasks in a playbook I’m writing (results listed next to the debug statement in <>):

And I’m running it with the following command:

The first include runs, but the second skips with this output:

I’m under the impression that the conditional check should pass for all of them as force_install == true evaluates to true which should make the whole when evaluate to true (since it’s a series of ‘OR’s).

How do I get the when to run when the variables are set appropriately?


Edit:

Changing the second when for the Install NRPE include to the following works, but doesn’t explain why the other one, Run the prep runs appropriately:

Working:

Also working:

Not working:


The truncated (duplicates removed) output of that particular section of the play is:

Answer:

You need to convert the variable to a boolean:

I don’t claim I understand the logic behind it. In python any non-empty string should be truthy. But when directly used in a condition it evaluates to false.

The bool filter then again interprets the strings 'yes', 'on', '1', 'true' (case-insensitive) and 1 as true (see source). Any other string is false.

You might want to also set a default value in case force_install is not defined, since it would result in an undefined variable error:

Leave a Reply