Skip to content
Advertisement

Ansible seems to be ignoring variable in when conditional when it is overridden with “-e” from the command line

I’m working on an Ansible playbook that uses a when condition, and I was trying to test the scenario where there is a default value specified as a play variable, which can then be selectively overridden from the command line using the -e argument to ansible-playbook. But this is not working as I would expect, and I’m not seeing any obvious reason(s) why.

Here’s the setup (this is a super stripped-down sample, just to show the point, not my real playbook).

conditional_task.yml

JavaScript

If I run this with the ansible-playbook command with no arguments, I get exactly the expected output.

JavaScript

And if I edit the playbook to change the value of the doomed var to False, and re-run this, I get the other message.

JavaScript

Now, given all that, I would expect to be able to do something like this:

JavaScript

and get the “not doomed” message. What I get instead is this:

JavaScript

As you can see, neither when condition fires in this case. It’s almost like the variable isn’t there at all, or has some unexpected value, or something. But as the debug output shows, the variable is defined, and does have value “false” as expected. And yet the “when” conditionals ignore this.

It also doesn’t matter if I change the command line to

JavaScript

In that case I still get neither conditional task executing. But again, the debug statement shows that doomed is present and has value of “true”.

I also tried re-writing my conditions as “doomed is true” and “doomed is false” respectively, instead of using the == operator and that didn’t make any difference. At this point I’m stuck. If anybody can explain this, it would be greatly appreciated.

Here’s my Ansible version information:

JavaScript

This is all running on Pop! OS:

JavaScript

Advertisement

Answer

The problem is caused by the fact that the type of the extra variables passed to Ansible from the command line is always string. For example, the playbook below

JavaScript

works as expected. The type of the variable doomed is Boolean. Then, simply use the variable in the condition. No comparison is needed. The debug task will be skipped

JavaScript

The thing will change when you pass the variable from the command line. Now, the type of the variable doomed is a string. A non-empty string will evaluate to True in the condition and the debug task will be executed

JavaScript

There is a simple universal solution. Always cast such variables to bool. In addition to this, to simplify the code, default to false or true, depending on the use-case, instead of an explicit declaration. This way you write the code fast and the condition will always do what you want

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement