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

时间:2017-06-03 10:55:29

标签: 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

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

- 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 

我如何让它工作? 还有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

您可以从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') )" 

你可能想为列表设置一个事实,这样就不会重复过滤,但是对于Ansible来说,这只是一个清晰而不是性能的问题。