在ansible中用列表值反转字典

Invert a dictionary with list values in ansible

如何转换如下字典

{
"host1": ["tag1", "tag2"],
"host2": ["tag1"]
}

在ansible下面:

{
"tag1": ["host1","host2"],
"tag2": ["host1"]
}

我一直在尝试这样做,但由于值是一个列表而卡住了。

剧本

shell> cat playbook.yml
- hosts: localhost
  vars:
    dict1:
      host1: ["tag1", "tag2"]
      host2: ["tag1"]
  tasks:
    - set_fact:
        dict2: "{{ dict2|default({})|
                   combine({item: list_of_hosts}) }}"
      loop: "{{ dict1.values()|flatten|unique|list }}"
      vars:
        list_of_hosts: "{{ dict1|
                           dict2items|
                           selectattr('value', 'contains', item)|
                           map(attribute='key')|
                           list }}"
    - debug:
        var: dict2

给予

    "dict2": {
        "tag1": [
            "host1",
            "host2"
        ],
        "tag2": [
            "host1"
        ]
    }