ansibleansible-2.x

How do I reverse lookup on an ansible dict?


Is there a way to transform a dict into another dict in order to invert the lookup based on an internal field? I expect the internal field to be unique for each item, and always present. Here's an example of what I want to do.

I have a data structure as such:

lookup_dict:
  a1:
    b: 123
  a2:
    b: 456
  a3:
    b: 789

The mapping between a and b is 1-to-1 and onto. I want to convert it to:

reverse_lookup_dict:
  123: a1
  456: a2
  789: a3

So I can then perform reverse lookup for a using b.


Solution

  • After some study, I found the answer to be the following:

    name: Reverse Lookup
    set_fact:
      reverse_lookup_dict: "{{reverse_lookup_dict|default({})|combine({item.value.b: item.key})}}"
    loop: "{{lookup('dict', lookup_dict)}}"