如果 Ansible 中某个值包含两个以上项目,则拆分字典

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

我有以下 Ansible 词典列表:

ok: [localhost] => {
    "msg": [
        {
            "animal": "fox",
            "food": [
                "chickens"
            ]
        },
        {
            "animal": "rabbit",
            "food": [
                "carrots",
        "apples"
            ]
        }
    ]
}

如您所见,第二个字典有两个“food”键值。我想把它分成两部分,像这样:

ok: [localhost] => {
    "msg": [
        {
            "animal": "fox",
            "food": [
                "chickens"
            ]
        },
        {
            "animal": "rabbit",
            "food": [
        "apples"
            ]
        },
        {
            "animal": "rabbit",
            "food": [
                "carrots"
            ]
        }
    ]
}

不幸的是我无法想出其中的逻辑。你能帮我吗?

dictionary ansible
2个回答
0
投票

我自己找到了解决方案:

- name: Splitting the dictionaries if we have multiple values for a single key
  set_fact:
    final_list: "{{ final_list|default([]) + [{'animal': item.0.animal, 'food': item.1}] }}"
  loop: "{{ animal-list|subelements('food') }}"

0
投票

也可以使用 Jinja

  final_list: |
    {% filter from_yaml %}
    {% for i in animal_list|subelements('food') %}
    - { animal: {{ i.0.animal }}, food: {{ i.1 }} }
    {% endfor %}
    {% endfilter %}

给予

  final_list:
  - animal: fox
    food: chickens
  - animal: rabbit
    food: carrots
  - animal: rabbit
    food: apples

用于测试的完整剧本示例

- hosts: localhost

  vars:

    animal_list:
      - animal: fox
        food: [chickens]
      - animal: rabbit
        food: [carrots, apples]

    final_list: |
      {% filter from_yaml %}
      {% for i in animal_list|subelements('food') %}
      - {animal: {{ i.0.animal }}, food: {{ i.1 }}}
      {% endfor %}
      {% endfilter %}

  tasks:

    - debug:
        var: final_list
© www.soinside.com 2019 - 2024. All rights reserved.