Skip to content

Netbox Get Nornir Inventory Task¤

task api name: get_nornir_inventory

Builds a Nornir inventory from NetBox device data. Nornir workers can call this task during startup to source hosts, host data, platform, hostname, interfaces, connections, circuits, and BGP peerings from NetBox.

Netbox get Nornir inventory

How It Works¤

  1. Nornir worker or client submits a get_nornir_inventory request to the NetBox worker
  2. NetBox worker checks the target NetBox instance status
  3. NetBox worker fetches device data with get_devices
  4. NetBox worker builds a Nornir hosts inventory from NetBox device data and config context
  5. Optional interface, connection, circuit, and BGP peering datasets are added to host data
  6. NetBox worker returns the assembled Nornir inventory

Inputs¤

Parameter Required Description
filters No NetBox device filter dictionaries
devices No Device names to include in inventory
instance No NetBox instance name to target
interfaces No True to include interfaces, or a dictionary of get_interfaces kwargs
connections No True to include connections, or a dictionary of get_connections kwargs
circuits No True to include circuits, or a dictionary of get_circuits kwargs
bgp_peerings No True to include BGP peerings, or a dictionary of get_bgp_peerings kwargs
nbdata No Include NetBox device data in host data, default True
primary_ip No Primary IP family to use for hostname, default ip4
cache No Cache usage mode passed to supporting data retrieval tasks

Output¤

Returns a Nornir inventory dictionary:

{
    "hosts": {
        "ceos-leaf-1": {
            "hostname": "192.0.2.11",
            "platform": "eos",
            "groups": ["lab"],
            "data": {
                "site": {"name": "lab"},
                "interfaces": {},
                "connections": {},
            },
        },
    },
}

Notes / Gotchas¤

  • The host name can be overridden by config_context.nornir.name on the NetBox device.
  • If host platform or hostname is not present in NetBox config context, the task derives them from NetBox platform and primary IP fields.
  • interfaces, connections, circuits, and bgp_peerings can be True or dictionaries with kwargs for the related task.
  • The current NFCLI command model does not expose get_nornir_inventory directly under netbox get, so this task is commonly used by Nornir worker startup or Python API callers.

Examples¤

from norfab.core.nfapi import NorFab

nf = NorFab(inventory="./inventory.yaml")
nf.start()
client = nf.make_client()

# build inventory for specific devices
result = client.run_job(
    "netbox",
    "get_nornir_inventory",
    workers="any",
    kwargs={
        "devices": ["ceos-leaf-1", "ceos-leaf-2"],
    },
)

# build inventory from NetBox filters
result = client.run_job(
    "netbox",
    "get_nornir_inventory",
    workers="any",
    kwargs={
        "filters": [{"site": "lab", "status": "active"}],
    },
)

# include related interface and connection data
result = client.run_job(
    "netbox",
    "get_nornir_inventory",
    workers="any",
    kwargs={
        "devices": ["ceos-leaf-1"],
        "interfaces": {"ip_addresses": True},
        "connections": True,
        "cache": "refresh",
    },
)

# use IPv6 primary addresses for hostnames
result = client.run_job(
    "netbox",
    "get_nornir_inventory",
    workers="any",
    kwargs={
        "devices": ["ceos-leaf-1"],
        "primary_ip": "ip6",
    },
)

nf.destroy()

Python API Reference¤

Retrieve and construct Nornir inventory from NetBox data.

Parameters:

Name Type Description Default
job Job

NorFab Job object containing relevant metadata

required
filters list

List of filters to apply when retrieving devices from NetBox.

None
devices list

List of specific devices to retrieve from NetBox.

None
instance str

NetBox instance to use.

None
interfaces Union[dict, bool]

If True, include interfaces data in the inventory. If a dict, use it as arguments for the get_interfaces method.

False
connections Union[dict, bool]

If True, include connections data in the inventory. If a dict, use it as arguments for the get_connections method.

False
circuits Union[dict, bool]

If True, include circuits data in the inventory. If a dict, use it as arguments for the get_circuits method.

False
nbdata bool

If True, include a copy of NetBox device's data in the host's data.

True
primary_ip str

Specify whether to use 'ip4' or 'ip6' for the primary IP address. Defaults to 'ip4'.

'ip4'
cache Union[bool, str]

Cache usage options:

  • True: Use data stored in cache if it is up to date, refresh it otherwise.
  • False: Do not use cache and do not update cache.
  • "refresh": Ignore data in cache and replace it with data fetched from Netbox.
  • "force": Use data in cache without checking if it is up to date.
None

Returns:

Name Type Description
dict Result

Nornir inventory dictionary containing hosts and their respective data.

Source code in norfab\workers\netbox_worker\nornir_inventory_tasks.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@Task(
    input=GetNornirInventoryInput,
    output=GetNornirInventoryResult,
    fastapi={"methods": ["GET"], "schema": NetboxFastApiArgs.model_json_schema()},
    mcp={
        "annotations": {
            "title": "Get Nornir Inventory",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True,
        }
    },
)
def get_nornir_inventory(
    self,
    job: Job,
    filters: Union[None, list] = None,
    devices: Union[None, list] = None,
    instance: Union[None, str] = None,
    interfaces: Union[dict, bool] = False,
    connections: Union[dict, bool] = False,
    circuits: Union[dict, bool] = False,
    nbdata: bool = True,
    bgp_peerings: Union[dict, bool] = False,
    primary_ip: str = "ip4",
    cache: Union[bool, str] = None,
) -> Result:
    """
    Retrieve and construct Nornir inventory from NetBox data.

    Args:
        job: NorFab Job object containing relevant metadata
        filters (list, optional): List of filters to apply when retrieving devices from NetBox.
        devices (list, optional): List of specific devices to retrieve from NetBox.
        instance (str, optional): NetBox instance to use.
        interfaces (Union[dict, bool], optional): If True, include interfaces data
                in the inventory. If a dict, use it as arguments for the get_interfaces method.
        connections (Union[dict, bool], optional): If True, include connections data
                in the inventory. If a dict, use it as arguments for the get_connections method.
        circuits (Union[dict, bool], optional): If True, include circuits data in the
                inventory. If a dict, use it as arguments for the get_circuits method.
        nbdata (bool, optional): If True, include a copy of NetBox device's data in the host's data.
        primary_ip (str, optional): Specify whether to use 'ip4' or 'ip6' for the primary
                IP address. Defaults to 'ip4'.
        cache (Union[bool, str], optional): Cache usage options:

            - True: Use data stored in cache if it is up to date, refresh it otherwise.
            - False: Do not use cache and do not update cache.
            - "refresh": Ignore data in cache and replace it with data fetched from Netbox.
            - "force": Use data in cache without checking if it is up to date.

    Returns:
        dict: Nornir inventory dictionary containing hosts and their respective data.
    """
    hosts = {}
    filters = filters or []
    devices = devices or []
    inventory = {"hosts": hosts}
    ret = Result(task=f"{self.name}:get_nornir_inventory", result=inventory)

    # check Netbox status
    job.event(f"checking NetBox status for '{instance or self.default_instance}'")
    netbox_status = self.get_netbox_status(job=job, instance=instance)
    if netbox_status.result[instance or self.default_instance]["status"] is False:
        job.event(
            "NetBox status check failed for Nornir inventory", severity="ERROR"
        )
        return ret

    # retrieve devices data
    job.event("fetching devices data for Nornir inventory")
    nb_devices = self.get_devices(
        job=job, filters=filters, devices=devices, instance=instance, cache=cache
    )
    if nb_devices.errors:
        job.event("failed to fetch devices for Nornir inventory", severity="ERROR")
        ret.errors.extend(nb_devices.errors)
        ret.failed = True
        return ret
    job.event(f"processing {len(nb_devices.result)} device(s) for Nornir inventory")

    # form Nornir hosts inventory
    for device_name, device in nb_devices.result.items():
        host = device["config_context"].pop("nornir", {})
        host.setdefault("data", {})
        name = host.pop("name", device_name)
        hosts[name] = host
        # add platform if not provided in device config context
        if not host.get("platform"):
            if device["platform"]:
                host["platform"] = device["platform"]["name"]
            else:
                log.warning(f"{self.name} - No platform found for '{name}' device")
        # add hostname if not provided in config context
        if not host.get("hostname"):
            if device["primary_ip4"] and primary_ip in ["ip4", "ipv4"]:
                host["hostname"] = device["primary_ip4"]["address"].split("/")[0]
            elif device["primary_ip6"] and primary_ip in ["ip6", "ipv6"]:
                host["hostname"] = device["primary_ip6"]["address"].split("/")[0]
            else:
                host["hostname"] = name
        # add netbox data to host's data
        if nbdata is True:
            host["data"].update(device)

    # return if no hosts found for provided parameters
    if not hosts:
        log.warning(f"{self.name} - No viable hosts returned by Netbox")
        job.event("no viable Nornir hosts returned by NetBox")
        return ret

    # add interfaces data
    if interfaces:
        job.event(f"fetching interfaces for {len(hosts)} Nornir host(s)")
        # decide on get_interfaces arguments
        kwargs = interfaces if isinstance(interfaces, dict) else {}
        kwargs.setdefault("cache", cache)
        # add 'interfaces' key to all hosts' data
        for host in hosts.values():
            host["data"].setdefault("interfaces", {})
        # query interfaces data from netbox
        nb_interfaces = self.get_interfaces(
            job=job, devices=list(hosts), instance=instance, **kwargs
        )
        if nb_interfaces.errors:
            job.event(
                "interface retrieval completed with errors", severity="WARNING"
            )
            ret.errors.extend(nb_interfaces.errors)
        # save interfaces data to hosts' inventory
        while nb_interfaces.result:
            device, device_interfaces = nb_interfaces.result.popitem()
            hosts[device]["data"]["interfaces"] = device_interfaces

    # add connections data
    if connections:
        job.event(f"fetching connections for {len(hosts)} Nornir host(s)")
        # decide on get_interfaces arguments
        kwargs = connections if isinstance(connections, dict) else {}
        kwargs.setdefault("cache", cache)
        # add 'connections' key to all hosts' data
        for host in hosts.values():
            host["data"].setdefault("connections", {})
        # query connections data from netbox
        nb_connections = self.get_connections(
            job=job, devices=list(hosts), instance=instance, **kwargs
        )
        if nb_connections.errors:
            job.event(
                "connection retrieval completed with errors", severity="WARNING"
            )
            ret.errors.extend(nb_connections.errors)
        # save connections data to hosts' inventory
        while nb_connections.result:
            device, device_connections = nb_connections.result.popitem()
            hosts[device]["data"]["connections"] = device_connections

    # add circuits data
    if circuits:
        job.event(f"fetching circuits for {len(hosts)} Nornir host(s)")
        # decide on get_interfaces arguments
        kwargs = circuits if isinstance(circuits, dict) else {}
        kwargs.setdefault("cache", cache)
        # add 'circuits' key to all hosts' data
        for host in hosts.values():
            host["data"].setdefault("circuits", {})
        # query circuits data from netbox
        nb_circuits = self.get_circuits(
            job=job, devices=list(hosts), instance=instance, **kwargs
        )
        if nb_circuits.errors:
            job.event("circuit retrieval completed with errors", severity="WARNING")
            ret.errors.extend(nb_circuits.errors)
        # save circuits data to hosts' inventory
        while nb_circuits.result:
            device, device_circuits = nb_circuits.result.popitem()
            hosts[device]["data"]["circuits"] = device_circuits

    # add bgp peerings data
    if bgp_peerings:
        job.event(f"fetching BGP peerings for {len(hosts)} Nornir host(s)")
        # decide on get_interfaces arguments
        kwargs = bgp_peerings if isinstance(bgp_peerings, dict) else {}
        kwargs.setdefault("cache", cache)
        # add 'bgp_peerings' key to all hosts' data
        for host in hosts.values():
            host["data"].setdefault("bgp_peerings", {})
        # query bgp_peerings data from netbox
        nb_bgp_peerings = self.get_bgp_peerings(
            job=job, devices=list(hosts), instance=instance, **kwargs
        )
        if nb_bgp_peerings.errors:
            job.event(
                "BGP peering retrieval completed with errors", severity="WARNING"
            )
            ret.errors.extend(nb_bgp_peerings.errors)
        # save circuits data to hosts' inventory
        while nb_bgp_peerings.result:
            device, device_bgp_peerings = nb_bgp_peerings.result.popitem()
            hosts[device]["data"]["bgp_peerings"] = device_bgp_peerings

    job.event(f"Nornir inventory build complete: {len(hosts)} host(s)")
    return ret