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

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?

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