在ansible中用列表值反转一个字典。

问题描述 投票:0回答:1

我如何转换一个像下面这样的字典

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

到下面的ansible中。

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

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

ansible ansible-2.x ansible-facts
1个回答
1
投票

游戏手册

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"
        ]
    }
© www.soinside.com 2019 - 2024. All rights reserved.