Ansible 通过对象字段的值在列表中查找对象

Rhy*_*vil 8 ansible

我有这个结构。对于每个主机,这个结构可能有更多或更少的项目。在任务中,我想知道是否有使用特定名称定义的模块。

---
web_module_list:
  - module_name: LaunchPad 
    module_version: 1.4.0
  - module_name: Manager
    module_version: 1.6.0
  - module_name: NetworkInventory
    module_version: 1.1.4
  - module_name: Reporting
    module_version: 1.0.18
  - module_name: TriadJ
    module_version: 4.1.0-1.1.7
Run Code Online (Sandbox Code Playgroud)

例如,我想知道是否定义了 module_name 报告,以便我为其包含一组任务。

- set_fact:
    reporting: if the web_module_list contains an item with module_name Reporting then true else false
    woprinting: if the web_module_list contains an item with module_name WorkOrderPrinting then true else false


- name: If the reporting module is listed in inventory then execute its tasks
  include: reporting.yml
  when: reporting 

- name: If the work order printing module is listed in inventory then execute its tasks
  include: woprinting.yml
  when: woprinting 
Run Code Online (Sandbox Code Playgroud)

我如何让这个工作?有没有更好的办法?

tec*_*raf 10

您可以从您的键中创建一个键值列表web_module_list并检查字符串是否在该列表中:

- name: If the reporting module is listed in inventory then execute its tasks
  include: reporting.yml
  when: "'Reporting' in (web_module_list | map(attribute='module_name') )" 

- name: If the work order printing module is listed in inventory then execute its tasks
  include: woprinting.yml
  when: "'WorkOrderPrinting' in (web_module_list | map(attribute='module_name') )" 
Run Code Online (Sandbox Code Playgroud)

您可能想要为列表设置一个事实,这样过滤就不会重复,但是对于 Ansible,它更像是一个清晰度而不是性能问题。