Ansible - 比较两个不同字典中的值并在匹配时输出

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

我有两个 Ansible 字典

    "small_d": {
        "cluster-c8836": [
            "aaaa-111",
            "bbbb-222",
            "cccc-222"
        ]
    }

    "big_d": {
        "2cc5b2fbe6c6": [
            "dddd-asda",
            "aaaa-111",
            "ddd-2411",
            "bbbb-222",
            "dddd-76543",
            "cccc-222",
            "dddd-66666"
        ],
        "0a722267a5bd": [
            "dddd-2468"
        ]
    }

我想循环遍历small_d的值,看看big_d中是否存在相同的值。 如果是,我想输出 big_d 中的相关键和匹配值的列表 例如

"2cc5b2fbe6c6": ["aaaa-111", "bbbb-222", "cccc-222"]

我正在尝试使用 Jinja2 模板

- name: try Jinja2 filtering
  set_fact:
    worth_a_try: |
      {% for cluster_id, node_ids in small_d.items() %}
      {% for node_id in node_ids %}
      {% for group_id, member_ids in big_d.items() %}
      {% if node_id in member_ids %}
        - {{group_id}}:
            {{node_id}}
      {% endif %}
      {% endfor %}
      {% endfor %}
      {% endfor %}
- debug: var=worth_a_try

我得到的输出是

    worth_a_try|from_yaml": [
        {
            "2cc5b2fbe6c6": "aaaa-111"
        },
        {
            "2cc5b2fbe6c6": "bbbb-222"
        },
        {
            "2cc5b2fbe6c6": "cccc-222"
        }

我怎样才能最好地清理这个输出?

dictionary ansible compare jinja2
1个回答
0
投票

假设您想坚持使用 Jinja 块,这里有一个实现。基本上创建一个字典,其中包含 big_d 字典的所有键和初始化为列表的值。每次满足条件时,将 node_id 附加到 group_id 的值。最后循环打印 yaml 格式的变量。

神社任务:

  - name: try Jinja2 filtering
    set_fact:
      worth_a_try: |
        {% set cluster_dict = {} %}
        {% for group_id in big_d.keys() %}
        {% set _ = cluster_dict.update({group_id: []}) %}
        {% endfor %}
        {% for cluster_id, node_ids in small_d.items() %}
        {% for node_id in node_ids %}
        {% for group_id, member_ids in big_d.items() %}
        {% if node_id in member_ids %}
        {% set _ = cluster_dict.update({group_id: cluster_dict[group_id] + [node_id]}) %}
        {% endif %}
        {% endfor %}
        {% endfor %}
        {% endfor %}
        {% for key, value in cluster_dict.items() %}
        {% if value != [] %}
        - {{ key}}:
        {% for entry in value %}
          - {{ entry }}
        {% endfor %}
        {% endif %}
        {% endfor %}

  - debug:
      var: worth_a_try|from_yaml

打印:

TASK [debug] **************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "worth_a_try|from_yaml": [
        {
            "2cc5b2fbe6c6": [
                "aaaa-111",
                "bbbb-222",
                "cccc-222"
            ]
        }
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.