# Undefined variable when using lookup('dict', hostvars) or map('extract', hostvars)

**URL:** <https://forum.ansible.com/t/undefined-variable-when-using-lookup-dict-hostvars-or-map-extract-hostvars/28935>\
**Category:** Ansible Project\
**Created:** [November 3, 2018, 6:54pm UTC](https://forum.ansible.com/t/undefined-variable-when-using-lookup-dict-hostvars-or-map-extract-hostvars/28935 "2018-11-03T18:54:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Barry\_Kaplan](https://avatars.discourse-cdn.com/v4/letter/b/48db29/32.png) [@Barry\_Kaplan](https://forum.ansible.com/u/Barry_Kaplan)\
**Post date:** [November 3, 2018, 6:54pm UTC](https://forum.ansible.com/t/undefined-variable-when-using-lookup-dict-hostvars-or-map-extract-hostvars/28935/1 "2018-11-03T18:54:16Z")

</div>

I’m trying to extract a few values from hostvars for subset of hosts, eg:

`

- debug:  
msg:
- “just a string” # a constant just to show the problem is not here  
loop: “{{ lookup(‘dict’, hostvars) }}”  
when: “item.key in groups[‘mygroup’]”  
`

or

`

- debug:  
msg:
- “just a string” # a constant just to show the problem is not here  
loop: “{{ groups[host\_group] | map(‘extract’, hostvars) | list }}”  
`

when either of these run I get errors like

`TASK [debug] *********************************************************************************************************************************************************************************************************************************** fatal: [localhost]: FAILED! => {"msg": "'ansible_memtotal_mb' is undefined"} to retry, use: --limit @/Users/bkaplan/.ansible/retry-files/ops-elk.retry`

Where the undefined variable could be anything that might be in the huge set of variables for a host.

This seems to imply that lookup(‘dict’) and map(‘extract’) are trying to eagerly resolve the variables.

Is this expected? Why would these lookups so aggressively inspect the entire dict?

---

<div class="post-metadata">

**Author:** ![Barry\_Kaplan](https://avatars.discourse-cdn.com/v4/letter/b/48db29/32.png) [@Barry\_Kaplan](https://forum.ansible.com/u/Barry_Kaplan)\
**Post date:** [November 3, 2018, 7:09pm UTC](https://forum.ansible.com/t/undefined-variable-when-using-lookup-dict-hostvars-or-map-extract-hostvars/28935/2 "2018-11-03T19:09:13Z")

</div>

Here is what I did to get my results. Seems smelly but works.

`

- debug:  
msg:
- “{{ item }}”  
with\_subelements:
- “{{ groups[host\_group] | map(‘extract’, hostvars) | dicts\_pick([‘ec2\_id’, ‘ansible\_hostname’, ‘ansible\_mounts’]) }}”
- ‘ansible\_mounts’  
`

with a custom filter

`def dicts_pick(dicts, keys): results = [] for d in dicts: results.append({k: d[k] for k in keys}) return results`
