According to the release notes of Jinja2 Version 2.11.0 (released on 2020-01-27) there is a new class named “ChainableUndefined” to handle undefined variables on multiple levels in Jinja2 templates. Currently, I use a ansible task using the module “template” to render jinja2 templates. However, I don’t know how to pass this new “ChainableUndefined” class to the parameter “undefined” in the Jinja2 environment via the ansible module.
Does anyone know how to set the parameter “undefined” to ChainableUndefined through the ansible “template” module?
Does the module “template” only support the “StrictUndefined” class, currently?
Thanks for this reply. To simplify tests for existing variables I now use builtin jinja2 filter “default()” such as “{% for person in persons | default(‘’) %}” to do not first have to test if the variable “persons” is defined. If I remove the part " | default(‘’)" from the for-loop and the variable is not defined ansible will raise an error.
This is the expected behavior, and ChainableUndefined doesn’t change that. AnsibleUndefined inherits from StrictUndefined, and in the end, you cannot simply loop over undefined values. Both ChainableUndefined and AnsibleUndefined allow something like this to work:
foo.bar.baz|default(‘qux’)
Where foo is undefined. Prior to this you needed to insert |default at every level, instead of just at the end.