Ansible support complex data type like data structure or collection types like List, Map, etc.
We have covered Ansible Variables, and the Ansible Data Types in our earlier post,
Ansible Data Structure or Collection types supports,
- Lists, are a collection of items and are generally represented using the [] brackets. The items in the list are indexed and can be accessed using index values starting from zero.
- We can define a list in two ways, as shown below.
vars:
var_list: ['db_server', 'web_server', 'app_server']
var_list_2:
- 'db'
- 'web'
- 'app'
- A Map is similar to the python dictionary. In Map, you can have key, and value pairs.
- We can define Map in two ways as shown below.
vars:
var_dict: {'db_server':'mysql', 'web_server':'apache', 'app_server':'php'}
var_dict_2:
'db': 'mysql'
'web': 'apache'
'app': 'php'
Example code of List and Map,
---
# Ansible Data Structure
- name: Playbook - Ansible Data Structure
hosts: localhost
vars:
# Ansible List
var_list: ['db_server', 'web_server', 'app_server']
var_list_2:
- 'db'
- 'web'
- 'app'
# Ansible Map
var_dict: {'db_server':'mysql', 'web_server':'apache', 'app_server':'php'}
var_dict_2:
'db': 'mysql'
'web': 'apache'
'app': 'php'
tasks:
- name: Lets print the list
debug: var=var_list
- name: Lets print the dict
debug: var=var_dict
- name: lets print the second list
debug: var=var_list_2
- name: lets print the second dict
debug: var=var_dict_2
- name: Lets print specific list value
debug:
msg:
- "The second value of list is {{var_list[1]}}"
- "The second value of the dict is {{var_dict_2['web']}}"
- Another method of calling value from dict {{var_dict.get('app_server')}}
- lets get all the dict keys {{var_dict.keys()}}
- lets get all the dict values {{var_dict.values()}}
The below screencap shows the output of the list and map using different methods as defined in the above code.