Skip to content

Netbox Sync Device Interfaces Taskยค

task api name: sync_device_interfaces

The Netbox Sync 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.

Branching Supportยค

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

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 sync_device_interfaces task:

nf# man tree netbox.update.device.interfaces
root
โ””โ”€โ”€ netbox:    Netbox service
    โ””โ”€โ”€ sync:    Update Netbox data
        โ””โ”€โ”€ device:    Update device data
            โ””โ”€โ”€ interfaces:    Update device interfaces
                โ”œโ”€โ”€ 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
                โ”œโ”€โ”€ 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
                โ”‚       โ”œโ”€โ”€ FM:    Filter hosts by platform
                โ”‚       โ”œโ”€โ”€ 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'
                โ”œโ”€โ”€ batch-size:    Number of devices to process at a time, default '10'
                โ””โ”€โ”€ branch:    Branching plugin branch name to use
nf#

Python API Referenceยค

Update or create device interfaces in Netbox using devices interfaces data sourced via Nornir service parse task using NAPALM getter.

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 Netbox 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
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
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
@Task(
    fastapi={"methods": ["PATCH"], "schema": NetboxFastApiArgs.model_json_schema()}
)
def sync_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,
    branch: str = None,
    **kwargs: Any,
) -> Result:
    """
    Update or create device interfaces in Netbox using devices interfaces
    data sourced via Nornir service `parse` task using NAPALM getter.

    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 Netbox 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.
        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_interfaces",
        result={},
        resources=[instance],
        dry_run=dry_run,
        diff={},
    )
    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 interfaces data from Netbox
        nb_interfaces_data = self.get_interfaces(
            job=job,
            instance=instance,
            devices=copy.copy(devices),
            cache="refresh",
        ).result

        # fetch devices data from Netbox
        nb_devices_data = self.get_devices(
            job=job,
            instance=instance,
            devices=copy.copy(devices),
        ).result

        # 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"
            job.event(
                f"retrieving interfaces for devices {', '.join(kwargs['FL'])}"
            )
            data = self.client.run_job(
                "nornir",
                "parse",
                kwargs=kwargs,
                workers="all",
                timeout=timeout,
            )

            # Collect interfaces to update and create in bulk
            interfaces_to_update = []
            interfaces_to_create = []
            mac_addresses_to_create = []

            for worker, results in data.items():
                if results["failed"]:
                    msg = f"{worker} get_interfaces 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} interfaces update failed: '{host_data['napalm_get']['exception']}'"
                        ret.errors.append(msg)
                        log.error(msg)
                        continue

                    nb_interfaces = nb_interfaces_data.get(host, {})
                    if not nb_interfaces:
                        msg = f"'{host}' has no interfaces in Netbox, skipping"
                        ret.errors.append(msg)
                        log.warning(msg)
                        continue

                    # Get device ID for creating new interfaces
                    nb_device = nb_devices_data.get(host)
                    if not nb_device:
                        msg = f"'{host}' does not exist in Netbox"
                        ret.errors.append(msg)
                        log.error(msg)
                        continue

                    interfaces = host_data["napalm_get"]["result"]["get_interfaces"]

                    sync_key = "sync_device_interfaces"
                    create_key = "created_device_interfaces"
                    if dry_run:
                        sync_key = "sync_device_interfaces_dry_run"
                        create_key = "created_device_interfaces_dry_run"
                    ret.result[host] = {
                        sync_key: {},
                        create_key: {},
                    }
                    if branch is not None:
                        ret.result[host]["branch"] = branch

                    # Process network device interfaces
                    for intf_name, interface_data in interfaces.items():
                        if intf_name in nb_interfaces:
                            # Interface exists - prepare update
                            nb_intf = nb_interfaces[intf_name]

                            # Build desired state
                            desired_state = {
                                "description": interface_data.get(
                                    "description", ""
                                ),
                                "enabled": interface_data.get("is_enabled", True),
                            }
                            if 10000 > interface_data.get("mtu", 0) > 0:
                                desired_state["mtu"] = interface_data["mtu"]
                            if interface_data.get("speed", 0) > 0:
                                desired_state["speed"] = (
                                    interface_data["speed"] * 1000
                                )

                            # Build current state
                            current_state = {
                                "description": nb_intf.get("description", ""),
                                "enabled": nb_intf.get("enabled", True),
                            }
                            if nb_intf.get("mtu"):
                                current_state["mtu"] = nb_intf["mtu"]
                            if nb_intf.get("speed"):
                                current_state["speed"] = nb_intf["speed"]

                            # 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_intf["id"])
                                interfaces_to_update.append(updates)
                                ret.diff.setdefault(host, {})[intf_name] = diff

                            ret.result[host][sync_key][intf_name] = (
                                updates if updates else "Interface in sync"
                            )

                            mac_address = (
                                interface_data.get("mac_address", "")
                                .strip()
                                .lower()
                            )
                            if mac_address and mac_address not in ["none", ""]:
                                # Check if MAC already exists
                                for nb_mac in nb_intf.get("mac_addresses") or []:
                                    if (
                                        nb_mac.get("mac_address", "").lower()
                                        == mac_address
                                    ):
                                        break
                                else:
                                    # Prepare MAC address for creation
                                    mac_addresses_to_create.append(
                                        {
                                            "mac_address": mac_address,
                                            "assigned_object_type": "dcim.interface",
                                            "assigned_object_id": int(
                                                nb_intf["id"]
                                            ),
                                        }
                                    )
                        elif create:
                            # Interface doesn't exist - prepare creation
                            new_intf = {
                                "name": intf_name,
                                "device": int(nb_device["id"]),
                                "type": "other",
                                "description": interface_data.get(
                                    "description", ""
                                ),
                                "enabled": interface_data.get("is_enabled", True),
                            }
                            if 10000 > interface_data.get("mtu", 0) > 0:
                                new_intf["mtu"] = interface_data["mtu"]
                            if interface_data.get("speed", 0) > 0:
                                new_intf["speed"] = interface_data["speed"] * 1000

                            mac_address = (
                                interface_data.get("mac_address", "")
                                .strip()
                                .lower()
                            )
                            if mac_address and mac_address not in ["none", ""]:
                                mac_addresses_to_create.append(
                                    {
                                        "mac_address": mac_address,
                                        "assigned_object_type": "dcim.interface",
                                        "assigned_object_id": int(nb_intf["id"]),
                                    }
                                )

                            interfaces_to_create.append(new_intf)
                            ret.result[host][create_key][intf_name] = new_intf

            # Perform bulk updates and creations
            if interfaces_to_update and not dry_run:
                try:
                    nb.dcim.interfaces.update(interfaces_to_update)
                    job.event(
                        f"Bulk updated {len(interfaces_to_update)} interfaces"
                    )
                except Exception as e:
                    msg = f"Bulk interface update failed: {e}"
                    ret.errors.append(msg)
                    log.error(msg)

            if interfaces_to_create and not dry_run:
                try:
                    _ = nb.dcim.interfaces.create(interfaces_to_create)
                    job.event(
                        f"Bulk created {len(interfaces_to_create)} interfaces"
                    )
                except Exception as e:
                    msg = f"Bulk interface creation failed: {e}"
                    ret.errors.append(msg)
                    log.error(msg)

            # Bulk create MAC addresses
            if mac_addresses_to_create and not dry_run:
                try:
                    nb.dcim.mac_addresses.create(mac_addresses_to_create)
                    job.event(
                        f"Bulk created {len(mac_addresses_to_create)} MAC addresses"
                    )
                except Exception as e:
                    msg = f"Bulk MAC address creation failed: {e}"
                    ret.errors.append(msg)
                    log.error(msg)

    else:
        raise UnsupportedServiceError(
            f"'{datasource}' datasource service not supported"
        )

    return ret