Help with filtering inventory

Hello

New to the nornir and seeking for a lil bit of help.
What I’m trying to achive is to find stp root bridges and execute new tasks on the ones found.

Currently the approach I’m using is to save matches to root_bridges list.
Unable to figure out how could I filter inventory based on these results.
I’m a reinventing a wheel, is there a better way to do this?

def stp():
    stp_result = nr.run(task=netmiko_send_command, command_string='show spanning-tree | inc This bridge is the root')

    root_bridges = []
    for i, u in stp_result.items():
        if 'This bridge is the root' in u.result:
            root_bridges.append(i)
    
    print(root_bridges) -> ['SW1', 'SW2']

hosts.yaml
---
SW1:
   hostname: 10.1.1.1
   groups:
     - cisco
   data:
     type: network_device
SW2:
   hostname: 10.1.1.2
   groups:
     - cisco
   data:
     type: network_device

Hi,
Just do this to solve you problem:

    for i, u in stp_result.items():
        if 'This bridge is the root' in u.result:
            # root_bridges.append(i)
            # you can print your result
            print(u.result)
            # and you will find here is not your wanted result
            # Then you should print this
            print(u[0].result)

So, you should use if 'This bridge is the root' in u[0].result:.
Many times print can solve some problems because you can see it directly.
More info:https://nornir.readthedocs.io/en/latest/tutorials/intro/task_results.html

Hope I can help you ~ :grinning:

Hi

That’s not quite what I had in mind.
Finding root bridges in not the issue.
Couldn’t figure out how to execute new tasks only on the hosts (outermost keys) saved into root_bridges list.

Oh,sorry.
You can use the F object to filter your root_bridges list.

from nornir.core.filter import F
#  ……
# print(root_bridges) -> ['SW1', 'SW2']
root_bridges = ['SW1', 'SW2']
for host in root_bridges:
    nr_root_bridge = nr.filter(F(name__contains=f"{host}"))
    print(nr_root_bridge.inventory.hosts)

Hope this can help you~
:sweat_smile: