首页 > 解决方案 > 使用ansible,我如何遍历列表并将项目用作查找值的键

问题描述

我正在尝试编写一个收集包的名称和版本号并将相关名称和包号输出到本地报告中的剧本。我如何在列表的迭代中将当前项目作为另一个项目查找中的键,该项目使用 jinja 进行解析。

---
- name: gather facts about packages that are installed on you managed nodes and write a report
  gather_facts: false
  hosts: servers
  vars:
    target_packages:
    - bash
    - kernel
    - glibc
  tasks:
  - name: gather facts
    package_facts:
      manager: rpm
  - name: output the relevant package number into a local file
    defer_to: localhost
    command: echo "{{ ansible_facts.packages['item']['name'] }}"="{{ ansible_facts.packages['item']['name']\>\> logfile
    loop: "{{ target_packages }}"
    

标签: ansible

解决方案


例如,在 Ubuntu

    - package_facts:
    - debug:
        msg: "{{ ansible_facts.packages[item] }}"
      loop: "{{ target_packages }}"
      when: item in ansible_facts.packages

ok: [localhost] => (item=bash) => 
  msg:
  - arch: amd64
    category: shells
    name: bash
    origin: ''
    source: apt
    version: 5.0-6ubuntu1.1
skipping: [localhost] => (item=kernel) 
skipping: [localhost] => (item=glibc)

字典中的项目是列表,因为可能安装了同一包的多个版本。如果要将结果放入文件中,例如

    - copy:
        dest: "logfile.{{ inventory_hostname }}"
        content: |-
          {% for pkg in target_packages %}
          {% if pkg in ansible_facts.packages %}
          {% for i in ansible_facts.packages[pkg] %}
          {{ i['name'] }} {{ i['version'] }}
          {% endfor %}
          {% endif %}
          {% endfor %}
      delegate_to: localhost

shell> cat logfile.localhost 
bash 5.0-6ubuntu1.1

上面的示例仅在本地主机上运行。在远程主机上运行时,需要delegate_to指令将日志写入 localhost。您可能希望将主机名称附加到日志文件中。否则,如果该剧中有更多的主机,它将被覆盖。


推荐阅读