Bootstrap FreeKB - Ansible - Flatten a nested list
Ansible - Flatten a nested list

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 0dd651 in the box below so that we can be sure you are a human.