Skip to content

Netbox Update Device Facts Task¤

task api name: update_device_facts

Limitations¤

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

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

Branching Support¤

Update device facts task is branch aware and can push updates to the branch. Netbox Branching Plugin need to be installed on Netbox instance.

Update Device Facts Sample Usage¤

NORFAB Netbox Update Device Facts Command Shell Reference¤

NorFab shell supports these command options for Netbox update_device_facts task:

nf# man tree netbox.update.device.facts
root
└── netbox:    Netbox service
    └── update:    Update Netbox data
        └── device:    Update device data
            └── facts:    Update device serial, OS version
                ├── timeout:    Job timeout
                ├── workers:    Filter worker to target, default 'any'
                ├── verbose-result:    Control output details, default 'False'
                ├── progress:    Display progress events, default 'True'
                ├── instance:    Netbox instance name to target
                ├── dry-run:    Return information that would be pushed to Netbox but do not push it
                ├── devices:    List of Netbox devices to update
                ├── batch-size:    Number of devices to process at a time, default '10'
                ├── datasource:    Service to use to retrieve device data, default 'nornir'
                │   └── nornir:    Use Nornir service to retrieve data from devices
                │       ├── FO:    Filter hosts using Filter Object
                │       ├── FB:    Filter hosts by name using Glob Patterns
                │       ├── FH:    Filter hosts by hostname
                │       ├── FC:    Filter hosts containment of pattern in name
                │       ├── FR:    Filter hosts by name using Regular Expressions
                │       ├── FG:    Filter hosts by group
                │       ├── FP:    Filter hosts by hostname using IP Prefix
                │       ├── FL:    Filter hosts by names list
                │       ├── FX:    Filter hosts excluding them by name
                │       ├── FN:    Negate the match
                │       ├── add-details:    Add task details to results, default 'False'
                │       ├── num-workers:    RetryRunner number of threads for tasks execution
                │       ├── num-connectors:    RetryRunner number of threads for device connections
                │       ├── connect-retry:    RetryRunner number of connection attempts
                │       ├── task-retry:    RetryRunner number of attempts to run task
                │       ├── reconnect-on-fail:    RetryRunner perform reconnect to host on task failure
                │       ├── connect-check:    RetryRunner test TCP connection before opening actual connection
                │       ├── connect-timeout:    RetryRunner timeout in seconds to wait for test TCP connection to establish
                │       ├── 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'
                └── branch:    Branching plugin branch name to use
nf#

Python API Reference¤

Updates the device facts in NetBox:

  • serial number

Parameters:

Name Type Description Default
job Job

NorFab Job object containing relevant metadata

required
instance str

The NetBox instance 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_facts getter
'nornir'
timeout int

The timeout for the job execution. Defaults to 60.

60
devices list

The list of devices to update.

None
batch_size int

The number of devices to process in each batch.

10
branch str

Branch name to use, need to have branching plugin installed, automatically creates branch if it does not exist in Netbox.

None
**kwargs

Additional keyword arguments to pass to the 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
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
@Task(fastapi={"methods": ["PATCH"]})
def update_device_facts(
    self,
    job: Job,
    instance: Union[None, str] = None,
    dry_run: bool = False,
    datasource: str = "nornir",
    timeout: int = 60,
    devices: Union[None, list] = None,
    batch_size: int = 10,
    branch: str = None,
    **kwargs,
) -> Result:
    """
    Updates the device facts in NetBox:

    - serial number

    Args:
        job: NorFab Job object containing relevant metadata
        instance (str, optional): The NetBox instance 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_facts getter

        timeout (int, optional): The timeout for the job execution. Defaults to 60.
        devices (list, optional): The list of devices to update.
        batch_size (int, optional): The number of devices to process in each batch.
        branch (str, optional): Branch name to use, need to have branching plugin installed,
            automatically creates branch if it does not exist in Netbox.
        **kwargs: Additional keyword arguments to pass to the 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_facts", result=result, resources=[instance]
    )
    nb = self._get_pynetbox(instance, branch=branch)
    kwargs["add_details"] = True

    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_facts"
            job.event(
                f"retrieving facts data for devices {', '.join(kwargs['FL'])}",
                resource=instance,
            )
            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_facts failed, errors: {'; '.join(results['errors'])}"
                    )
                    continue
                for host, host_data in results["result"].items():
                    if host_data["napalm_get"]["failed"]:
                        log.error(
                            f"{host} facts update failed: '{host_data['napalm_get']['exception']}'"
                        )
                        job.event(
                            f"{host} facts update failed",
                            resource=instance,
                            status="failed",
                            severity="WARNING",
                        )
                        continue
                    nb_device = nb.dcim.devices.get(name=host)
                    if not nb_device:
                        raise Exception(f"'{host}' does not exist in Netbox")
                    facts = host_data["napalm_get"]["result"]["get_facts"]
                    # update serial number
                    nb_device.serial = facts["serial_number"]
                    if not dry_run:
                        nb_device.save()
                    result[host] = {
                        (
                            "update_device_facts_dry_run"
                            if dry_run
                            else "update_device_facts"
                        ): {
                            "serial": facts["serial_number"],
                        }
                    }
                    if branch is not None:
                        result[host]["branch"] = branch
                    job.event(f"{host} facts updated", resource=instance)
    else:
        raise UnsupportedServiceError(
            f"'{datasource}' datasource service not supported"
        )

    return ret