Another frequent mistake in playbooks is to improperly reference a subelement of a complex variable. A complex variable is one that is more than simply a string; it is either a list or a hash. Often, the wrong subelement will be referenced, or the element will be improperly referenced, expecting a different type.
While lists are fairly easy to work with, hashes present some unique challenges. A hash is an unordered key-value set of potentially mixed types, which could also be nested. A hash can have one element that is a single string, while another element can be a list of strings, and a third element can be another hash with further elements inside it. Knowing how to properly access the right subelement is critical to success.
For example, let's modify our previous play a bit more. This time, we'll allow Ansible to gather facts, and then we'll show the value of ansible_python:
--- - name: variable introspection demo hosts: localhost tasks: - name: show a complex hash debug: var: ansible_python
The output is shown in the following screenshot:
Using debug to display the entire complex variable is a great way to learn all the names of the subelements.
This variable has elements that are strings, along with elements that are lists of strings. Let's access the last item in the list of flags, as follows:
--- - name: variable introspection demo hosts: localhost tasks: - name: show a complex hash debug: var: ansible_python.version_info[-1]
The output is shown in the following screenshot:
Because flags is a list, we can use the list index method to select a specific item from the list. In this case, -1 will give us the very last item in the list.