# filtering out attributes

**URL:** <https://forum.ansible.com/t/filtering-out-attributes/29319>\
**Category:** Ansible Project\
**Created:** [December 21, 2018, 11:13pm UTC](https://forum.ansible.com/t/filtering-out-attributes/29319 "2018-12-21T23:13:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Justin\_DynamicD](https://avatars.discourse-cdn.com/v4/letter/j/97f17d/32.png) [@Justin\_DynamicD](https://forum.ansible.com/u/Justin_DynamicD)\
**Post date:** [December 21, 2018, 11:13pm UTC](https://forum.ansible.com/t/filtering-out-attributes/29319/1 "2018-12-21T23:13:44Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![cassell](https://avatars.discourse-cdn.com/v4/letter/c/ecae2f/32.png) [@cassell](https://forum.ansible.com/u/cassell)\
**Post date:** [December 22, 2018, 4:11am UTC](https://forum.ansible.com/t/filtering-out-attributes/29319/2 "2018-12-22T04:11:46Z")

</div>

Look at the json\_query filter. You can use it with JMESPath queries to extract what you need.

V/r,  
James Cassell
