Remove a dict in a nested dict

18 views
Skip to first unread message

Baptiste Doublet

unread,
Mar 25, 2024, 12:40:00 PM3/25/24
to Ansible Project
Hi,
I block on manipuling data with ansible / jinja2 / python filter.

I have this yaml structure which is an ansible inventory in yaml
```
all:
  children:
    admin_administration:
      hosts:
        admin_administration1:
          server_ip: 127.0.0.1
    int:
      children:
        int_administration:
        int_console:
        int_swarmanager:
        int_swarmworker:
          children:
            int_swarmvip:
            int_swarminfra:
            int_swarmload:
            int_scw_swarmload:
    int_swarmvip:
      hosts:
        int_swarmvip1:
          server_hostname: swarmvip-001
          server_ip: 127.0.0.1
```

and I have this list of dict:
```
remove_groups:
  - name:
      int_swarmworker:
        children:
          int_swarmvip:
```
I loop on it so the task gets group.name dict on each iteration
```
- name: Remove group from inventory file
  include_tasks: remove_group.yml
  loop: "{{ remove_groups }}"
  loop_control:
    loop_var: group
```

In the section:
```
        int_swarmworker:
          children:
            int_swarmvip:
            int_swarminfra:
            int_swarmload:
            int_scw_swarmload:
```

Only the int_swarmvip must be removed but if there is no more subobject after removing int_swarmvip below int_swarmworker, the group int_swarmworker must be removed too.

Also this section must be removed:
```
    int_swarmvip:
      hosts:
        int_swarmvip1:
          server_hostname: swarmvip-001
          server_ip: 127.0.0.1
```

So the new yaml ansible inventory should be:
```
all:
  children:
    admin_administration:
      hosts:
        admin_administration1:
          server_ip: 127.0.0.1
    int:
      children:
        int_administration:
        int_console:
        int_swarmanager:
        int_swarmworker:
          children:
            int_swarminfra:
            int_swarmload:
            int_scw_swarmload:
```

I did the add_host with ansible dict combine and I try it to remove a dict --> fail
Also try a custom plugin fillter -> fail
jinja2 code -> fail
I debug too much but I'm sure the solution is easy ...

Thanks for your help
Reply all
Reply to author
Forward
0 new messages