WTF bool filter in Ansible
It’s not what you think
Published in
1 min readApr 4, 2019
Jinja2 filters:
foo|list
convertsfoo
tolist
foo|string
convertsfoo
tostring
foo|int
convertsfoo
toint
foo|float
convertsfoo
tofloat
foo|bool
IS NOT !!!!!!!!!11111one
Instead it parses foo
as string to search for yaml-style ‘yes, on, true, false, False, Off, NO’ and other words and return true if any ‘yes’ word found.
"yes"|bool -> true
"no"|bool -> false
"funking yes"|bool -> false
"http://url"|bool -> false
[1,2,3]|bool -> false
In other words it’s not a usual map to python type constructor, but a separate ‘|guess_yes’
filter, named bool
to cast confusions and wtfs.
Solution
Use round brackets to force the usual pythonic ‘falsable’ behavior:
when: (foo)
It will cast foo to False for:
- null
- None
- False
- Empty string
- empty list, dict, set
It will cast to True for:
- non-empty string, dict, list, set.
- True value
The Solution (updated)
drew1kun pointed out, that there is a (new?) filter in Ansible for this purpose:
foo is truthy
It handles values as Python does, e.g.:
- [] -> False
- {} -> False
- ‘no’ -> True
- ‘yes’ -> True
- [1] -> True
- “a” -> True
- “” -> False
- etc.