Nornir for Network Engineers
Filtering the Inventory: F() and nr.filter()
What you'll learn
- How nr.filter() selects a subset of hosts by a field
- How F() expresses more flexible queries
- That filtering returns a new Nornir object, leaving the original untouched
- Why targeting a subset matters for real operational tasks
Listen to a guided explanation of this lesson.
Spoken narration isn't supported in this browser.
A genuinely new capability
Every other lesson in this module maps onto something Phase 3.3 already built by hand. Filtering is the exception — Phase 3.3's package always ran against the whole loaded inventory. Nornir makes targeting a subset a first-class operation.
Filtering by custom data
branch1_only = nr.filter(site="Branch1")
print(list(branch1_only.inventory.hosts.keys()))site is the exact custom data field set on each host in Lesson 2's hosts.yaml -- filtering by it is a direct, meaningful demonstration, not an abstract example.
['SW4', 'SW5']Real, verified output. Only Branch1's two hosts match -- HQ's three (SW1, SW2, SW3) are correctly excluded.
F() for more flexible queries
nr.filter(field=value) only expresses equality. F() handles richer conditions.
from nornir.core.filter import F
subset = nr.filter(F(name__any=["SW1", "SW4"]))
print(list(subset.inventory.hosts.keys()))name__any=[...] is one of F()'s query operators -- matches any host whose name is in the given list, spanning both sites at once, something a single nr.filter(field=value) call can't express.
['SW1', 'SW4']Real, verified output — one host from each site, selected by an explicit name list rather than a shared field value.
Filtering never mutates the original
print("original nr still has all hosts:", list(nr.inventory.hosts.keys()))Run after every filter above -- real, verified output.
original nr still has all hosts: ['SW1', 'SW2', 'SW3', 'SW4', 'SW5']nr.filter() always returns a NEW Nornir object; the original is untouched, confirmed directly — safe to filter repeatedly for different subsets without losing the full inventory.
Key takeaways
- nr.filter(field=value) selects hosts by an exact field match — including custom data fields like site, verified against the HQ/Branch1 grouping.
- F() expresses richer queries (like name__any=[...]) that a single equality filter can't.
- Filtering always returns a new Nornir object — the original inventory is never mutated, verified directly.
- Filtering is the one capability in this module with no Phase 3.3 equivalent — a genuinely new, first-class operation.