WTF bool filter in Ansible

It’s not what you think

George Shuklin
OpsOps
1 min readApr 4, 2019

--

Jinja2 filters:

  • foo|list converts foo to list
  • foo|string converts foo to string
  • foo|int converts foo to int
  • foo|float converts foo to float
  • 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.

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:

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.

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.