Ansible Subelements Lookup Example

When you're working with Ansible, you often come across situations where you need to deal with lists inside of lists. Imagine you have a bunch of servers, and each server has its own set of services to manage.
The subelements
lookup plugin is designed to iterate over a list of dictionaries and a specified sub-list within each dictionary. Instead of writing complicated code to dig into each layer, subelements
lets you glide through the outer list and then dive into the inner list easily.
What we will cover?
- Subelements syntax
- Subelements example
- What are item.0 and item.1?
- Subelements example with NetBox
Subelements Syntax
To use subelements
in your playbook, you write a loop that tells Ansible what main list to look at and which sublist to go through. Here’s what a simple line of code looks like.
loop: "{{ query('subelements', your_main_list, 'your_sublist_key') }}"
your_main_list
is where you have all your main items (like servers), and your_sublist_key
is the name of the sublist inside each main item (like tasks for each server). Ansible will then loop through each main item and its sub-items in turn.
Ansible Subelements Example
Suppose you have the following data structure defined in your playbook.
Continue reading