Skip to content

Netbox Get Nornir Inventory Task¤

task api name: get_nornir_inventory

This task designed to provide Nornir workers with inventory data sourced from Netbox.

How it works

Netbox NorFab workers able to talk with Netbox GraphQL and REST API. Nornir workers can be configured to request Nornir inventory from Netbox workers on startup. Netbox workers in response to such a request will be fetching devices data from Netbox and constructing Nornir inventory returning it to Nornir worker.

Netbox get Nornir inventory

  1. On startup Nornir worker sends get_nornir_inventory request to Netbox NorFab Workers

  2. Netbox worker fetches devices data from netbox - hostnames, interfaces, ip addresses, circuits, connections, configuration contexts etc.

  3. Netbox worker constructs Nornir inventory and sends it back to Nornir worker

Get Nornir Inventory Sample Usage¤

NORFAB Netbox Get Nornir Inventory Command Shell Reference¤

NorFab shell supports these command options for Netbox get_nornir_inventory task:

Python API Reference¤

Retrieve and construct Nornir inventory from NetBox data.

Parameters:

Name Type Description Default
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'

Returns:

Name Type Description
dict dict

Nornir inventory dictionary containing hosts and their respective data.

Source code in norfab\workers\netbox_worker.py
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
def get_nornir_inventory(
    self,
    filters: list = None,
    devices: list = None,
    instance: str = None,
    interfaces: Union[dict, bool] = False,
    connections: Union[dict, bool] = False,
    circuits: Union[dict, bool] = False,
    nbdata: bool = True,
    primary_ip: str = "ip4",
) -> dict:
    """
    Retrieve and construct Nornir inventory from NetBox data.

    Args:
        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'.

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

    # check Netbox status
    netbox_status = self.get_netbox_status(instance=instance)
    if netbox_status.result[instance or self.default_instance]["status"] is False:
        return ret

    # retrieve devices data
    nb_devices = self.get_devices(
        filters=filters, devices=devices, instance=instance
    )

    # 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")
        return ret

    # add interfaces data
    if interfaces:
        # decide on get_interfaces arguments
        kwargs = interfaces if isinstance(interfaces, dict) else {}
        # 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(
            devices=list(hosts), instance=instance, **kwargs
        )
        # 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:
        # decide on get_interfaces arguments
        kwargs = connections if isinstance(connections, dict) else {}
        # 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(
            devices=list(hosts), instance=instance, **kwargs
        )
        # 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:
        # decide on get_interfaces arguments
        kwargs = circuits if isinstance(circuits, dict) else {}
        # 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(
            devices=list(hosts), instance=instance, **kwargs
        )
        # save circuits data to hosts' inventory
        while nb_circuits.result:
            device, device_circuits = nb_circuits.result.popitem()
            hosts[device]["data"]["circuits"] = device_circuits

    return ret