I am trying to create a ansible role which filter out host based on dictionary(passed to role) in comparison with host variables. If host variables contains key:value from dictionary it will added to filtered_host list. This is what I found till point but not getting desired output:
Ansible role:
---
- name: Filtering host
debug:
msg: "Here is the response {{ filters }} {{groups['all']}}"
- name: Setting filter
set_fact:
input_filter: "{{ filters }}"
- name: Setting filtered hosts
set_fact:
filtered_hosts: "{{ groups['all'] | map('extract', hostvars) | select('@ in filters') | map(attribute='inventory_hostname') | list }}"
vars:
input_filter: "{{ filters | to_json }}"
- name: Print filtered hosts
debug:
var: filtered_hosts
Here filters is a dictionary(filter) passed from playbook to test but actually i want to pass a dictionary, and this role should return list of hosts which contains key:value from this dictionary.
Sample dictionary:
{
"os_type":"linux",
"datacenter" : "REM",
"location" : "IND"
}
Sample Host variables:
HOST A variables:
{
"os_type":"linux",
"datacenter" : "REM",
"location" : "IND"
}
HOST B variables:
{
"os_type":"linux",
"datacenter" : "REM",
"location" : "USA",
"status" : "success"
}
HOST C variables:
{
"os_type":"linux",
"datacenter" : "REM",
"location" : "IND",
"status" : "success"
}
OUTPUT:
[Host A, Host C]
because both host contains key:value passed through dictionary. Also number of keys differ from different hosts.
Actual Scenario: I created a dynamic inventory which will fetch all host and host vars from DB based on some filters and assign it to inventory. Groups are created using some general info based on host vars. Now templates are created for different organizations/product who require to filter host based on some conditions(dynamically) out of the host vars. Since we cant create groups for everything, we decided to have a common ansible role which will act as a filter.
Within playbook there are multiple task will be performed on different host and to get those specific host some conditions are generated in the form of dictionary. These dictionary will be passed to ansible role to filter further based on the dynamic condition. The filter in given scenario is comparing 2 dictionaries to find out proper host for that task. A simplified example is what I have shown in the question.
Given the dictionary
In the vars, select the keys
Select and join the values
gives
In the tasks, create the variable my_fvals
gives (abridged)
Select hosts that match the criteria
gives
The playbook
gives
because in this inventory plugin
lookups were disabled from templating