Q:

Ansible: Condition with "and" and boolean variable not working

I discovered the following problem when executing an ansible-playbook:
I have an include_tasks: command, that is dependent on 2 variables, a string variable and a boolean variable.
I first tried to write my code like this, which I thought should work fine:
- include_tasks: file.yml
  when: string_variable == "string" and bool_variable

Unfortunatelly, that didn't work, the tasks were included even if bool_variable is set to false. The variables are defined in the inventories-file in the hosts-folder:
[group]
server1      bool_variable=false       string_variable=string
server2      bool_variable=false       string_variable=string

In file.yml, I have the lines:
- debug:
    var: bool_variable

which prints false for each server. However, this line should not be reached, when the variable is false.
However, I found 2 ways to make the condition work:
Adding == true, which clearly seems redundant, since the condition than contains false == true:
- include_tasks: file.yml
  when: string_variable == "string" and bool_variable == true

and this (which shows that the bool_variable should be interpreted correctly):
- include_tasks: file.yml
  when: 
    - string_variable == "string" 
    - bool_variable

Why did the first condition not work? As far as I see, the condition should be evaluated correctly. Do I have to add parentesis or something similar?
I am using ansible 2.6.3

A:

Any variable you set either in the INI format inventory or pass from CLI as extravars is a string.
You can verify it with the type_debug filter:
bool_variable | type_debug

The type is unicode when running Ansible with Python 2 and str when running in Python 3.

Use the following to cast it to Boolean in your conditionals:
bool_variable | bool

Some expressions work, because Ansible tries to match the string value to common (those defined in YAML) Boolean values.

