ansible - 使用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 }}"
解决方案
例如,在 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。您可能希望将主机名称附加到日志文件中。否则,如果该剧中有更多的主机,它将被覆盖。
推荐阅读
- nginx - Nginx:如果 index.html 不存在,则加载默认文件?
- javascript - 如何在 jQuery Nestable 中停止水平移动?
- android - Unity Input.gyro.enabled 在Android上抛出空指针异常
- rest - 使用 REST API 封装基于事件的系统
- linux - 在 Ubuntu 3.13.0-163-generic 上构建 GRPC 编译失败
- android - Android WebView 不会加载本地文件
- android - Android studio 文件路径目录未创建
- ide - Visual Studio 2019 中无扩展的结构导航
- javascript - 在表格javascript中的最小值旁边显示*
- python - 使用嵌套循环在列表中查找素数