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
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
@Task(
    fastapi={"methods": ["PATCH"], "schema": NetboxFastApiArgs.model_json_schema()}
)
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