首页 > 解决方案 > 列表中的 Ansible 字典 - 获取字典的键和值

问题描述

我有一个可变值的ansible剧本,如下所示 -

"instances": [
    {
        "architecture": "x86_64",
        "tags": {
            "A": "B",
            "C": "D"
        }
    },
    {
        "architecture": "x86",
        "tags": {
            "A": "X",
            "G": "D"
        }
    }
]

实例列表是动态的,每次运行时#values 可能会有所不同。

我想要 -

  1. 如果我们在整个列表中存在标签键“A”,则获取键“架构”的值。
  2. 如果整个列表中存在标签值“D”,则获取键“architecture”的值。

我试过with_subelements但没有运气,因为它需要一个列表。

标签: ansible

解决方案


第一个任务可以用纯 Jinja 完成,第二个任务需要一些 JMESPath。

- name: List archs with tag A present
  debug:
    msg: >-
      {{ instances
         | selectattr('tags.A','defined')
         | map(attribute='architecture')
         | list
         | unique
      }}

- name: List archs with any tag set to D
  debug:
    msg: >-
      {{ instances
         | json_query('[?contains(values(tags),`D`)]')
         | map(attribute='architecture')
         | list
         | unique
      }}

推荐阅读