Passing a list to filter object

I’m trying to pass a list to the filter however it is returning an empty dict. Is there another way to do this or perhaps I’ve missed something here? The reason I want to do this is because I’m dynamically determining what hosts I want within the script, when I have a host I need to make changes on I’d like to just append it to a list then pass that list to Nornir at the end to run tasks on.

task_filter = nr.filter(hostname=[“10.0.253.129”, “10.0.253.15”])
print(task_filter.inventory.hosts.keys())

Result:
dict_keys([])

Process finished with exit code 0

Probably using a filter_func is the easiest way for this IMO:

>>> nr.inventory.hosts
{'cisco3': Host: cisco3, 'cisco4': Host: cisco4, 'nxos1': Host: nxos1, 'nxos2': Host: nxos2, 'arista1': Host: arista1, 'arista2': Host: arista2, 'arista3': Host: arista3, 'arista4': Host: arista4, 'srx2': Host: srx2}
>>> select_hosts = ["cisco3", "arista2", "srx2"]
>>> filtered_nr = nr.filter(filter_func=lambda h: h.name in select_hosts)
>>> filtered_nr.inventory.hosts
{'cisco3': Host: cisco3, 'arista2': Host: arista2, 'srx2': Host: srx2}
1 Like

In addition to the previous response, you can use the F object, there are examples in the documentation:

https://nornir.readthedocs.io/en/stable/howto/advanced_filtering.html

In your case, the following should do the trick:

nr.filter(F(hostname__any=["host1", "host2", ...]))