Ansible - Flatten a nested list
by
Jeremy Canfield |
Updated: July 09 2024
| Ansible articles
Let's say you have a nested list. In this example, "my_list" contains nested lists.
---
- hosts: all
tasks:
- ansible.builtin.set_fact:
my_list: [1 , 2, [3, [4, 5]], 6]
- ansible.builtin.debug:
var: my_list
...
Running this playbook should return something like this.
ok: [server1.example.com] => {
"my_list": [
1,
2,
[
3,
[
4,
5
]
],
6
]
}
flatten can be used to flatten the nested list.
---
- hosts: all
tasks:
- ansible.builtin.set_fact:
my_list: [1 , 2, [3, [4, 5]], 6]
- ansible.builtin.debug:
var: my_list
- ansible.builtin.set_fact:
my_list_flattened: "{{ my_list | flatten }}"
- ansible.builtin.debug:
var: my_list_flattened
...
In this example, "my_list_flattened" should return the following.
ok: [server1.example.com] => {
"my_list_flattened": [
1,
2,
3,
4,
5,
6
]
}
Did you find this article helpful?
If so, consider buying me a coffee over at