Skip to content

Netbox Sync Device Facts Task¤

task api name: sync_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.

Sync Device Facts Sample Usage¤

NORFAB Netbox Update Device Facts Command Shell Reference¤

NorFab shell supports these command options for Netbox sync_device_facts task:

nf# man tree netbox.update.device.facts
root
└── netbox:    Netbox service
    └── sync:    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 device facts in NetBox, this task updates this device attributes:

  • 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 Any

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
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
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
@Task(
    fastapi={"methods": ["PATCH"], "schema": NetboxFastApiArgs.model_json_schema()}
)
def sync_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: Any,
) -> Result:
    """
    Updates device facts in NetBox, this task updates this device attributes:

    - 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 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.
    """
    devices = devices or []
    instance = instance or self.default_instance
    ret = Result(
        task=f"{self.name}:sync_device_facts",
        resources=[instance],
        dry_run=dry_run,
        diff={},
        result={},
    )
    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))
            devices = list(set(devices))
            job.event(f"Syncing {len(devices)} devices")
        # fetch devices data from Netbox
        nb_devices = self.get_devices(
            job=job,
            instance=instance,
            devices=copy.copy(devices),
            cache="refresh",
        ).result
        # remove devices that does not exist in Netbox
        for d in list(devices):
            if d not in nb_devices:
                msg = f"'{d}' device does not exist in Netbox"
                ret.errors.append(msg)
                log.error(msg)
                devices.remove(d)
        # 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 for devices {', '.join(kwargs['FL'])}")
            data = self.client.run_job(
                "nornir",
                "parse",
                kwargs=kwargs,
                workers="all",
                timeout=timeout,
            )

            # Collect devices to update in bulk
            devices_to_update = []

            for worker, results in data.items():
                if results["failed"]:
                    msg = f"{worker} get_facts failed, errors: {'; '.join(results['errors'])}"
                    ret.errors.append(msg)
                    log.error(msg)
                    continue
                for host, host_data in results["result"].items():
                    if host_data["napalm_get"]["failed"]:
                        msg = f"{host} facts update failed: '{host_data['napalm_get']['exception']}'"
                        ret.errors.append(msg)
                        log.error(msg)
                        continue

                    nb_device = nb_devices[host]

                    facts = host_data["napalm_get"]["result"]["get_facts"]
                    desired_state = {
                        "serial": facts["serial_number"],
                    }
                    current_state = {
                        "serial": nb_device["serial"],
                    }

                    # Compare and get fields that need updating
                    updates, diff = compare_netbox_object_state(
                        desired_state=desired_state,
                        current_state=current_state,
                    )

                    # Only update if there are changes
                    if updates:
                        updates["id"] = int(nb_device["id"])
                        devices_to_update.append(updates)
                        ret.diff[host] = diff

                    ret.result[host] = {
                        (
                            "sync_device_facts_dry_run"
                            if dry_run
                            else "sync_device_facts"
                        ): (updates if updates else "Device facts in sync")
                    }
                    if branch is not None:
                        ret.result[host]["branch"] = branch

            # Perform bulk update
            if devices_to_update and not dry_run:
                try:
                    nb.dcim.devices.update(devices_to_update)
                except Exception as e:
                    ret.errors.append(f"Bulk update failed: {e}")
    else:
        raise UnsupportedServiceError(
            f"'{datasource}' datasource service not supported"
        )

    return ret