簡體   English   中英

用 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"
        ]
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM