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():
vars: hosts: testhost1: 127.0.0.2 testhost2: 127.0.0.3 tasks: - debug: msg: '{{ item }}' # Only works with Python 2 #loop: "{{ hosts.keys() }}" # Works with both Python 2 and Python 3 loop: "{{ hosts.keys() | list }}"
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:
vars: hosts: testhost1: 127.0.0.2 testhost2: 127.0.0.3 tasks: - debug: msg: '{{ item }}' # Only works with Python 2 #loop: "{{ hosts.iteritems() }}" # Works with both Python 2 and Python 3 loop: "{{ hosts.items() | list }}"
See also
- The Dictionary views entry for information on why the list filter is necessary here.
Next Previous