I'd like to filter out entries from a nested list depending on a presence of a key. Given the following dictionary:
hostvars:
host1:
backups:
- src: somesource
target: sometarget
- src: anothersource
host2:
backups:
- src: somesource for host2
target: fancy target
host3:
backups:
- src: yet another src
- src: and another one
I'd like to filter out all elements of the backups lists when the target key is not present.
The closest I've come is:
- set_fact:
data: "{{ hostvars | dict2items | json_query(query) }}"
vars:
query: "[?value.backups[?target]]"
which results in
hostvars:
host1:
backups:
- src: somesource
target: sometarget
- src: anothersource
host2:
backups:
- src: somesource for host2
target: fancy target
So I've successfully filtered out host3 which does not have an element containing the target key in the backups list.
However, I'd also like to remove the second element from the backups list of host1 (which also does not contain the target key).
Any pointers are greatly appreciated.