Skip to content

Netbox Update Device Interfaces Task¤

task api name: update_device_interfaces

The Netbox Update Device Interfaces Task is a feature of the NorFab Netbox Service that allows you to synchronize and update the interface data of your network devices in Netbox. This task ensures that the interface configurations in Netbox are accurate and up-to-date, reflecting the current state of your network infrastructure.

Keeping interface data accurate and up-to-date is crucial for effective network management. The Netbox Update Device Interfaces Task automates the process of updating interface information, such as interface names, statuses, mac addresses, and other relevant details.

How it works - Netbox worker on a call to update interfaces task fetches live data from network devices using nominated datasource, by default it is Nornir service parse task using NAPALM get_interfaces getter. Once data retrieved from network, Netbox worker updates records in Netbox database for device interfaces.

Netbox Update Device Interfaces

  1. Client submits and on-demand request to NorFab Netbox worker to update device interfaces

  2. Netbox worker sends job request to nominated datasource service to fetch live data from network devices

  3. Datasource service fetches data from the network

  4. Datasource returns devices interfaces data back to Netbox Service worker

  5. Netbox worker processes device interfaces data and updates records in Netbox for requested devices

Limitations¤

Datasource nornir uses NAPALM get_interfaces getter and as such only supports these device platforms:

  • Arista EOS
  • Cisco IOS
  • Cisco IOSXR
  • Cisco NXOS
  • Juniper JUNOS

Update Device Interfaces Sample Usage¤

NORFAB Netbox Update Device Interfaces Command Shell Reference¤

NorFab shell supports these command options for Netbox update_device_interfaces task:

nf# man tree netbox.update.device.interfaces
root
└── netbox:    Netbox service
    └── update:    Update Netbox data
        └── device:    Update device data
            └── interfaces:    Update device interfaces
                ├── timeout:    Job timeout
                ├── workers:    Filter workers to target, default 'any'
                ├── instance:    Netbox instance name to target
                ├── dry_run:    Return information that would be pushed to Netbox but do not push it
                ├── devices:    Devices to update
                └── datasource:    Service to use to retrieve device data, default 'nornir'
                    └── nornir:    Use Nornir service to retrieve data from devices
                        ├── add_details:    Add task details to results, default 'False'
                        ├── run_num_workers:    RetryRunner number of threads for tasks execution
                        ├── run_num_connectors:    RetryRunner number of threads for device connections
                        ├── run_connect_retry:    RetryRunner number of connection attempts
                        ├── run_task_retry:    RetryRunner number of attempts to run task
                        ├── run_reconnect_on_fail:    RetryRunner perform reconnect to host on task failure
                        ├── run_connect_check:    RetryRunner test TCP connection before opening actual connection
                        ├── run_connect_timeout:    RetryRunner timeout in seconds to wait for test TCP connection to establish
                        ├── run_creds_retry:    RetryRunner list of connection credentials and parameters to retry
                        ├── tf:    File group name to save task results to on worker file system
                        ├── tf_skip_failed:    Save results to file for failed tasks
                        ├── diff:    File group name to run the diff for
                        ├── diff_last:    File version number to diff, default is 1 (last)
                        └── progress:    Display progress events, default 'True'
nf#

Python API Reference¤

Update or create device interfaces in Netbox. Interface parameters updated:

  • interface name
  • interface description
  • mtu
  • mac address
  • admin status
  • speed

Parameters:

Name Type Description Default
job Job

NorFab Job object containing relevant metadata

required
instance str

The instance name to use.

None
dry_run bool

If True, no changes will be made to Netbox.

False
datasource str

The data source to use. Supported datasources:

  • nornir - uses Nornir Service parse task to retrieve devices' data using NAPALM get_interfaces getter
'nornir'
timeout int

The timeout for the job.

60
devices list

List of devices to update.

None
create bool

If True, new interfaces will be created if they do not exist.

True
batch_size int

The number of devices to process in each batch.

10
**kwargs

Additional keyword arguments to pass to the datasource job.

{}

Returns:

Name Type Description
dict Result

A dictionary containing the results of the update operation.

Raises:

Type Description
Exception

If a device does not exist in Netbox.

UnsupportedServiceError

If the specified datasource is not supported.

Source code in norfab\workers\netbox_worker.py
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
@Task()
def update_device_interfaces(
    self,
    job: Job,
    instance: Union[None, str] = None,
    dry_run: bool = False,
    datasource: str = "nornir",
    timeout: int = 60,
    devices: Union[None, list] = None,
    create: bool = True,
    batch_size: int = 10,
    **kwargs,
) -> Result:
    """
    Update or create device interfaces in Netbox. Interface parameters updated:

    - interface name
    - interface description
    - mtu
    - mac address
    - admin status
    - speed

    Args:
        job: NorFab Job object containing relevant metadata
        instance (str, optional): The instance name to use.
        dry_run (bool, optional): If True, no changes will be made to Netbox.
        datasource (str, optional): The data source to use. Supported datasources:

            - **nornir** - uses Nornir Service parse task to retrieve devices' data
                using NAPALM get_interfaces getter

        timeout (int, optional): The timeout for the job.
        devices (list, optional): List of devices to update.
        create (bool, optional): If True, new interfaces will be created if they do not exist.
        batch_size (int, optional): The number of devices to process in each batch.
        **kwargs: Additional keyword arguments to pass to the datasource job.

    Returns:
        dict: A dictionary containing the results of the update operation.

    Raises:
        Exception: If a device does not exist in Netbox.
        UnsupportedServiceError: If the specified datasource is not supported.
    """
    result = {}
    devices = devices or []
    instance = instance or self.default_instance
    ret = Result(task=f"{self.name}:update_device_interfaces", result=result)
    nb = self._get_pynetbox(instance)

    if datasource == "nornir":
        # source hosts list from Nornir
        if kwargs:
            devices.extend(self.get_nornir_hosts(kwargs, timeout))
        # iterate over devices in batches
        for i in range(0, len(devices), batch_size):
            kwargs["FL"] = devices[i : i + batch_size]
            kwargs["getters"] = "get_interfaces"
            data = self.client.run_job(
                "nornir",
                "parse",
                kwargs=kwargs,
                workers="all",
                timeout=timeout,
            )
            for worker, results in data.items():
                if results["failed"]:
                    log.error(
                        f"{worker} get_interfaces failed, errors: {'; '.join(results['errors'])}"
                    )
                    continue
                for host, host_data in results["result"].items():
                    updated, created = {}, {}
                    result[host] = {
                        (
                            "update_device_interfaces_dry_run"
                            if dry_run
                            else "update_device_interfaces"
                        ): updated,
                        (
                            "created_device_interfaces_dry_run"
                            if dry_run
                            else "created_device_interfaces"
                        ): created,
                    }
                    interfaces = host_data["napalm_get"]["get_interfaces"]
                    nb_device = nb.dcim.devices.get(name=host)
                    if not nb_device:
                        raise Exception(f"'{host}' does not exist in Netbox")
                    nb_interfaces = nb.dcim.interfaces.filter(
                        device_id=nb_device.id
                    )
                    # update existing interfaces
                    for nb_interface in nb_interfaces:
                        if nb_interface.name not in interfaces:
                            continue
                        interface = interfaces.pop(nb_interface.name)
                        if dry_run is not True:
                            nb_interface.description = interface["description"]
                            if interface["mtu"] > 0:
                                nb_interface.mtu = interface["mtu"]
                            if interface["speed"] > 0:
                                nb_interface.speed = interface["speed"] * 1000
                            if interface["mac_address"].strip().lower() not in [
                                "none",
                                "",
                            ]:
                                mac_address = interface["mac_address"]
                                if self.nb_version[instance] >= (4, 2, 0):
                                    try:
                                        nb_mac_addr = nb.dcim.mac_addresses.get(
                                            mac_address=mac_address,
                                            interface_id=nb_interface.id,
                                        )
                                    except Exception as e:
                                        msg = f"{worker} failed to get {mac_address} mac-address from netbox: {e}"
                                        job.event(msg, severity="WARNING")
                                        ret.messages.append(msg)
                                        log.error(msg)
                                    else:
                                        if not nb_mac_addr:
                                            nb_mac_addr = nb.dcim.mac_addresses.create(
                                                mac_address=mac_address,
                                                assigned_object_type="dcim.interface",
                                                assigned_object_id=nb_interface.id,
                                            )
                                        elif not nb_mac_addr.assigned_object_id:
                                            nb_mac_addr.assigned_object_type = (
                                                "dcim.interface"
                                            )
                                            nb_mac_addr.assigned_object_id = (
                                                nb_interface.id
                                            )
                                        if not nb_interface.primary_mac_address:
                                            nb_interface.primary_mac_address = (
                                                nb_mac_addr.id
                                            )
                                            job.event(
                                                f"{host} {mac_address} MAC associating with interface {nb_interface.name}",
                                                resource=instance,
                                            )
                                    nb_interface.mac_address = mac_address
                            nb_interface.enabled = interface["is_enabled"]
                            nb_interface.save()
                        updated[nb_interface.name] = interface
                        job.event(
                            f"{host} updated interface {nb_interface.name}",
                            resource=instance,
                        )
                    # create new interfaces
                    if create is not True:
                        continue
                    for interface_name, interface in interfaces.items():
                        interface["type"] = "other"
                        if dry_run is not True:
                            nb_interface = nb.dcim.interfaces.create(
                                name=interface_name,
                                device={"name": nb_device.name},
                                type=interface["type"],
                            )
                            nb_interface.description = interface["description"]
                            if interface["mtu"] > 0:
                                nb_interface.mtu = interface["mtu"]
                            if interface["speed"] > 0:
                                nb_interface.speed = interface["speed"] * 1000
                            # create MAC address
                            if interface["mac_address"].strip().lower() not in [
                                "none",
                                "",
                            ]:
                                mac_address = interface["mac_address"]
                                if self.nb_version[instance] >= (4, 2, 0):
                                    try:
                                        nb_mac_addr = nb.dcim.mac_addresses.create(
                                            mac_address=mac_address,
                                            assigned_object_type="dcim.interface",
                                            assigned_object_id=nb_interface.id,
                                        )
                                    except Exception as e:
                                        msg = f"{host} {mac_address} MAC failed to create, interface {nb_interface.name}: {e}"
                                        job.event(msg, severity="WARNING")
                                        ret.messages.append(msg)
                                        log.error(msg)
                                    else:
                                        nb_interface.primary_mac_address = (
                                            nb_mac_addr.id
                                        )
                                else:
                                    nb_interface.mac_address = mac_address
                                job.event(
                                    f"{host} {mac_address} MAC created, associating with interface {nb_interface.name}",
                                    resource=instance,
                                )
                            nb_interface.enabled = interface["is_enabled"]
                            nb_interface.save()
                        created[interface_name] = interface
                        job.event(
                            f"{host} created interface {interface_name}",
                            resource=instance,
                        )
    else:
        raise UnsupportedServiceError(
            f"'{datasource}' datasource service not supported"
        )

    return ret