我如何循环遍历 Ansible 中特定字段的字典?

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

我创建了一个从 ansible.package_facts 过滤的 ansible 包字典,仅包含特定版本的包。 (示例如下)

"filtered_ansible_packages": {
    "cool_package1": [
       {
         "arch": "noarch",
         "epoch": "null",
         "name": "cool_package1",
         "release": "el7",
         "version": "1.2.6"
       }
    ],
    "cool_package2": [
       {
         "arch": "noarch",
         "epoch": "null",
         "name": "cool_package2",
         "release": "el7",
         "version": "1.4.7"
       }
    ]
 }

我想要的是循环遍历每个包并获取名称、版本、版本和架构。

然后我想将它们连接成一个字符串变量,我们可以称之为“full_package_name”,在酷包 1 的情况下将是:“cool_package1.1.2.6.el7.noarch”,然后将这些完整的包名称存储到列表中称为“full_package_name_list”。

以我需要的方式检索数据的最佳方式是什么?我应该将其转换为带有“dict2items”的列表吗?我是 Ansible 的新手,因此我们将不胜感激。

json ansible ansible-facts ansible-filter
1个回答
0
投票

问:“循环遍历每个包并获取名称、版本、版本和架构。”

A:将字典转换为列表并迭代子元素

    - debug:
        msg: |
          arch: {{ item.1.arch }}
          name: {{ item.1.name }}
          release: {{ item.1.release }}
          version: {{ item.1.version }}
      loop: "{{ filtered_ansible_packages | dict2items | subelements('value') }}"
      loop_control:
        label: "{{ item.0.key }} {{ item.1.name }}"

给予

ok: [localhost] => (item=cool_package1 cool_package1) =>
  msg: |-
    arch: noarch
    name: cool_package1
    release: el7
    version: 1.2.6
ok: [localhost] => (item=cool_package2 cool_package2) => 
  msg: |-
    arch: noarch
    name: cool_package2
    release: el7
    version: 1.4.7

用于测试的完整剧本示例

- hosts: localhost

  vars:

    filtered_ansible_packages:
      cool_package1:
        - {arch: noarch, epoch: 'null', name: cool_package1, release: el7, version: 1.2.6}
      cool_package2:
        - {arch: noarch, epoch: 'null', name: cool_package2, release: el7, version: 1.4.7}

  tasks:

    - debug:
        msg: |
          arch: {{ item.1.arch }}
          name: {{ item.1.name }}
          release: {{ item.1.release }}
          version: {{ item.1.version }}
      loop: "{{ filtered_ansible_packages | dict2items | subelements('value') }}"
      loop_control:
        label: "{{ item.0.key }} {{ item.1.name }}"
© www.soinside.com 2019 - 2024. All rights reserved.