First I apologize if this was covered elsewhere, but nothing seemed to match my scenario… at least not in a way I could recreate.
I have a role that builds a list of dictionaries. I’ve found it fairly easy to extend this list, add attributes to individual items, etc, but I’m having a real problem “reducing” the output or creating a simplified dictionary from the complex one.
The scenario:
Assume I have a list that looks something like this:
`
drives:
- volume: 0
size_kb: 102400
name: drive1
datastore: alpha - volume: 1
size_gb: 50
name: drive2
datastore: alpha
`
In this case, I discover with minor manipulation, I can drop {{ drives }} right into my vmware_guest module as long as I filter down to just the relevant attributes. If I drop it in as-is, however, it fails because it doesn’t know what some of the attributes are. So I want to make it look something like this:
`
drives:
- size_kb: 102400
datastore: alpha - size_gb: 50
datastore: alpha
`
I’ve tried using selectattr() and rejectattr(), but those seem to accept/reject the entire dictionary based on an attribute. I’m hoping to simply filter out irrelevant attributes instead. I tried just making a new list but then had issues with dealing with the “size_*” attributes as one is kb and the other is gb. Basically I would love to have some kind of filter where I set a new fact and simply inject every attribute that is relevant.
`
- set_fact:
new_disks: “{{ new_disks | default() + [ drives | selectonly(‘datastore’,‘size_*’) ] }}”
loop: “{{ drives }}”
loop_control:
loop_var: loop_drives
`
Sadly, I’ve been coming up empty when it comes to “trimming” an object down. Any ideas?