I have this structure. For each host this structure may have more or less items. In a task I want to know if there is a a module defined with a particular name.
---
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
For instance I want to know if the module_name Reporting is defined so that I include a set of tasks for it.
- 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
How do I get this to work? Is there a better way?
To use it in a playbook, specify: ansible.utils.index_of. This plugin returns the indices of items matching some criteria in a list. When working with a list of dictionaries, the key to evaluate can be specified.
I need the ansible Playbook way to filter the list. Show activity on this post. Once you load your csv into a variable using the corresponding read_csv module, you can filter and select values inside the list with the usual filtering tools ( selectattr, map, ...) For the demo, I placed your above file in files/example.csv.
This module is part of ansible-base and included in all Ansible installations. In most cases, you can use the short module name find even without specifying the collections: keyword.
If you are a Red Hat customer, refer to the Ansible Automation Platform Life Cycle page for subscription details. This lookup plugin is part of ansible-core and included in all Ansible installations. In most cases, you can use the short plugin name items even without specifying the collections: keyword.
You can create a list of values of a key from your web_module_list
and check if a string is on that 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') )"
You might want to set a fact for the list, so that the filtering is not repeated, but with Ansible it's rather a matter of clarity than performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With