+

Search Tips   |   Advanced Search

Python3 in templates

Ansible uses Jinja2 to leverage Python data types and standard functions in templates and variables. For templates there are differences between Python versions. This topic help you design templates that work on both Python2 and Python3.


Dictionary views

In Python2, the dict.keys(), dict.values(), and dict.items() methods return a list. Jinja2 returns that to Ansible via a string representation that Ansible can then turn back into a list.

In Python3, those methods return a dictionary view object. The string representation that Jinja2 returns for dictionary views cannot be parsed back into a list by Ansible. We can make this portable by using the list filter whenever using dict.keys(), dict.values(), or dict.items():


dict.iteritems()

Python2 dictionaries have iterkeys(), itervalues(), and iteritems() methods.

Python3 dictionaries do not have these methods. Use dict.keys(), dict.values(), and dict.items() to make your playbooks and templates compatible with both Python2 and Python3:


See also

Next Previous