Skip to content

NetBox Sync BGP ASNs¤

task API name: sync_bgp_asn

The sync_bgp_asn task collects globally unique BGP ASNs from live devices using the Nornir TTP bgp_asn getter and reconciles them with NetBox IPAM. It updates descriptions only when requested and optionally records the devices on which each local ASN was observed. It never deletes ASNs or device associations.

Existing local ASNs can be updated without rir. Creating missing ASNs requires an existing RIR. If you supply an invalid RIR, the task stops before collecting data.

The device custom field must be assigned to ipam.asn, use the multi-object type, and relate to dcim.device. The task accepts either field membership or an ASN reference on a NetBox BGP session for that device as association evidence. The task only writes field memberships for local ASNs. If a device has neither a configured field nor session evidence, the task only compares ASN existence and can create missing ASNs.

By default, existing NetBox ASN descriptions are preserved. Set preserve_description=False to apply the selected peer-group label to the shared ASN when it is observed locally and association evidence is available. New ASNs receive a parsed label when available.

Output¤

Results are keyed by reporting device and contain created, updated, deleted, and in_sync ASN lists. Dry-run output uses create, update, delete, and in_sync. The delete list is always empty. Observed ASNs appear under each reporting device. Shared ASNs are written once. BGP ASN sync skips devices on platforms with no BGP ASN parser and lists them in resources_unsupported. When every selected device is unsupported, the task succeeds with an empty result and diff. Association updates show a boolean change for that device. The diff uses device_associated when only sessions provide association evidence.

{
  "edge-1": {
    "created": [65001],
    "updated": [],
    "deleted": [],
    "in_sync": [65002]
  }
}

Bulk Request Batching¤

List-based NetBox writes are sent as sequential requests containing at most batch_size objects. The default is 1000; set any integer greater than zero to tune the request size. Each batch emits matching progress event and log messages. If a request fails, the task stops and returns the results recorded for earlier successful batches.

Examples¤

nf# netbox sync bgp-asn devices edge-1 edge-2 rir Private

Ignore individual ASNs and ranges:

nf# netbox sync bgp-asn devices edge-1 rir Private ignore-asn-by-range 65000 65100-65200

Preview updates without supplying an RIR:

nf# netbox sync bgp-asn devices edge-1 dry-run

Apply the selected peer-group label to existing ASN descriptions:

nf# netbox sync bgp-asn devices edge-1 preserve-description false
from norfab.core.nfapi import NorFab

with NorFab(inventory="./inventory.yaml") as nf:
    result = nf.make_client().run_job(
        "netbox",
        "sync_bgp_asn",
        workers="any",
        kwargs={
            "devices": ["edge-1", "edge-2"],
            "rir": "Private",
        },
    )
    print(result)

Notes and Gotchas¤

  • When several devices report the same ASN, the first non-empty peer-group label in device-name order is used.
  • Existing device associations are preserved and newly observed devices are appended.
  • with_approval cannot be combined with the NFCLI nowait option.

Python API Reference¤

Synchronize globally unique live BGP ASNs with NetBox.

Existing ASNs are updated without requiring an RIR. Missing ASNs are created only when rir identifies an existing NetBox RIR. The selected ASN custom field and NetBox BGP sessions provide device association evidence. Existing ASN updates apply only to devices that report the ASN as local. Without association evidence sources for a device, the task only compares ASN existence. ASNs, memberships, and peerings are never deleted by this task.

Parameters:

Name Type Description Default
job Job

NorFab job object.

required
instance Union[None, str]

NetBox instance name. Uses the default instance when omitted.

None
dry_run bool

Return the calculated diff without writing to NetBox.

False
with_approval bool

Ask for approval before applying the prepared diff.

False
timeout int

Timeout in seconds for Nornir host resolution and parsing.

600
devices Union[None, list]

Explicit NetBox and Nornir device names.

None
branch Union[None, str]

NetBox Branching plugin branch name.

None
rir Union[None, str]

NetBox RIR name required when creating missing ASNs.

None
device_custom_field str

ASN custom field containing associated devices.

'devices'
ignore_asn_by_range Union[None, list]

ASN values or numerical ranges to ignore.

None
preserve_description bool

Keep existing NetBox ASN descriptions unchanged by default. False applies the selected peer-group label.

True
batch_size int

Maximum number of ASN records per write request.

1000
**kwargs Any

Nornir FFun host filters.

{}

Returns:

Name Type Description
Result Result

Per-device ASN synchronization actions and devices skipped in resources_unsupported.

Source code in norfab\workers\netbox_worker\bgp_asn_tasks.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
@Task(
    fastapi={"methods": ["POST"], "schema": NetboxFastApiArgs.model_json_schema()},
    input=SyncBgpAsnInput,
    output=SyncBgpAsnResult,
    mcp={
        "annotations": {
            "title": "Sync BGP ASNs",
            "readOnlyHint": False,
            "destructiveHint": True,
            "idempotentHint": True,
            "openWorldHint": True,
        }
    },
)
def sync_bgp_asn(
    self,
    job: Job,
    instance: Union[None, str] = None,
    dry_run: bool = False,
    with_approval: bool = False,
    timeout: int = 600,
    devices: Union[None, list] = None,
    branch: Union[None, str] = None,
    rir: Union[None, str] = None,
    device_custom_field: str = "devices",
    ignore_asn_by_range: Union[None, list] = None,
    preserve_description: bool = True,
    batch_size: int = 1000,
    **kwargs: Any,
) -> Result:
    """Synchronize globally unique live BGP ASNs with NetBox.

    Existing ASNs are updated without requiring an RIR. Missing ASNs are
    created only when ``rir`` identifies an existing NetBox RIR. The
    selected ASN custom field and NetBox BGP sessions provide device
    association evidence. Existing ASN updates apply only to devices that
    report the ASN as local. Without association evidence sources for a
    device, the task only compares ASN existence.
    ASNs, memberships, and peerings are never deleted by this task.

    Args:
        job: NorFab job object.
        instance: NetBox instance name. Uses the default instance when omitted.
        dry_run: Return the calculated diff without writing to NetBox.
        with_approval: Ask for approval before applying the prepared diff.
        timeout: Timeout in seconds for Nornir host resolution and parsing.
        devices: Explicit NetBox and Nornir device names.
        branch: NetBox Branching plugin branch name.
        rir: NetBox RIR name required when creating missing ASNs.
        device_custom_field: ASN custom field containing associated devices.
        ignore_asn_by_range: ASN values or numerical ranges to ignore.
        preserve_description: Keep existing NetBox ASN descriptions unchanged
            by default. False applies the selected peer-group label.
        batch_size: Maximum number of ASN records per write request.
        **kwargs: Nornir FFun host filters.

    Returns:
        Result: Per-device ASN synchronization actions and devices skipped in
            ``resources_unsupported``.
    """
    devices = list(devices or [])
    instance = instance or self.default_instance
    ret = Result(
        task=f"{self.name}:sync_bgp_asn",
        result={},
        resources=[instance],
        dry_run=dry_run,
        diff={},
    )

    job.event(
        f"starting BGP ASN sync using NetBox instance '{instance}' for "
        f"{len(devices)} explicit device(s)"
    )
    log.info(
        f"{self.name} - Sync BGP ASNs: instance '{instance}', dry_run={dry_run}"
    )
    nb = self._get_pynetbox(instance, branch=branch, job=job)

    # Validate creation prerequisites before collecting reconciliation data.
    rir_obj = None
    if rir is not None:
        rir_matches = self.bulk_filter(nb.ipam.rirs, name=rir, fields="id,name")
        if len(rir_matches) != 1:
            msg = f"RIR '{rir}' must match exactly one NetBox RIR"
            job.event(msg, severity="ERROR")
            ret.errors.append(msg)
            ret.failed = True
            return ret
        rir_obj = rir_matches[0]

    if kwargs:
        job.event("resolving devices from Nornir filters")
        devices.extend(self.get_nornir_hosts(kwargs, timeout))
    devices = sorted(set(devices))
    if not devices:
        msg = "no devices specified"
        job.event(msg, severity="ERROR")
        log.error(f"{self.name} - Sync BGP ASNs: {msg}")
        ret.errors.append(msg)
        ret.failed = True
        return ret

    # Keep ignore ranges as bounds, including reversed ranges and comma lists.
    ignored_ranges = []
    for expression in ignore_asn_by_range or []:
        for token in expression.split(","):
            first, separator, last = token.strip().partition("-")
            try:
                start, end = int(first), int(last if separator else first)
            except ValueError:
                msg = f"invalid ignored ASN range '{token}'"
                job.event(msg, severity="ERROR")
                ret.errors.append(msg)
                ret.failed = True
                return ret
            ignored_ranges.append((min(start, end), max(start, end)))

    # Collect ASN numbers, labels, and the parser's local ownership marker.
    job.event(f"collecting live BGP ASNs from {len(devices)} device(s)")
    parse_data = self.client.run_job(
        "nornir",
        "parse_ttp",
        kwargs={"get": "bgp_asn", "FL": devices},
        workers="all",
        timeout=timeout,
    )
    live_asn = {}
    for worker_name, worker_data in (parse_data or {}).items():
        ret.messages.extend(worker_data.get("messages") or [])
        ret.resources_unsupported.extend(
            worker_data.get("resources_unsupported") or []
        )
        ret.resources_failed.extend(worker_data.get("resources_failed") or [])
        if worker_data.get("failed"):
            ret.errors.append(f"worker '{worker_name}' failed to collect BGP ASNs")
            continue
        for device, records in (worker_data.get("result") or {}).items():
            if device not in devices or not isinstance(records, list):
                continue
            device_asns = {}
            for record in records:
                asn = int(record["asn"])
                if any(start <= asn <= end for start, end in ignored_ranges):
                    continue
                label, local = device_asns.get(asn, ("", False))
                device_asns[asn] = (
                    label or record.get("description") or "",
                    local or record.get("local_asn") is True,
                )
            collected = live_asn.setdefault(device, {})
            for asn, (label, local) in device_asns.items():
                previous_label, previous_local = collected.get(asn, ("", False))
                collected[asn] = (previous_label or label, previous_local or local)

    ret.resources_failed = sorted(set(ret.resources_failed) - live_asn.keys())
    ret.resources_unsupported = sorted(
        set(ret.resources_unsupported) - set(ret.resources_failed)
    )
    # Exit successfully when no selected device has a matching parser.
    if not ret.errors and set(devices).issubset(ret.resources_unsupported):
        return ret
    if ret.resources_unsupported:
        devices = sorted(set(devices) - set(ret.resources_unsupported))
        if not devices:
            ret.failed = True
            return ret

    # Resolve the selected devices and discard live data for missing devices.
    nb_devices = {
        device.name: device
        for device in self.bulk_filter(
            nb.dcim.devices,
            name=devices,
            fields="id,name",
        )
    }
    for device_name in devices:
        if device_name not in nb_devices:
            msg = f"device '{device_name}' not found in NetBox"
            job.event(msg, severity="ERROR")
            ret.errors.append(msg)
            ret.resources_failed.append(device_name)
    live_asn = {
        device: asns for device, asns in live_asn.items() if device in nb_devices
    }

    for device in devices:
        if device in nb_devices and device not in live_asn:
            ret.resources_failed.append(device)
            msg = f"device '{device}' is missing a live BGP ASN result"
            job.event(msg, severity="ERROR")
            ret.errors.append(msg)
    ret.resources_failed = sorted(set(ret.resources_failed))
    if not live_asn:
        ret.failed = True
        return ret

    # Read the configured ASN field, the shared ASN catalog, and NetBox sessions.
    if device_custom_field:
        definitions = self.bulk_filter(
            nb.extras.custom_fields,
            name=device_custom_field,
            object_type="ipam.asn",
            type="multiobject",
            fields="name,related_object_type",
        )
        if not any(
            field.related_object_type == "dcim.device" for field in definitions
        ):
            device_custom_field = None

    asn_devices = {}
    for device in sorted(live_asn):
        for asn in sorted(live_asn[device]):
            asn_devices.setdefault(asn, []).append(device)
    netbox_objects = {
        int(record.asn): record
        for record in (
            self.bulk_filter(
                nb.ipam.asns,
                asn=sorted(asn_devices),
                fields="id,asn,description,custom_fields",
            )
            if asn_devices
            else []
        )
    }

    # Index both ASN references on each session by its NetBox device.
    session_members = {}
    devices_with_sessions = set()
    if asn_devices:
        devices_by_id = {nb_devices[device].id: device for device in live_asn}
        try:
            sessions = self.bulk_filter(
                nb.plugins.bgp.session,
                device_id=list(devices_by_id),
                fields="device,local_as,remote_as",
            )
        except RequestError as exc:
            job.event(
                f"netbox BGP sessions are unavailable: {exc}", severity="WARNING"
            )
        else:
            for session in sessions:
                if session.device is None or session.device.id not in devices_by_id:
                    continue
                for reference in (session.local_as, session.remote_as):
                    if reference is not None:
                        devices_with_sessions.add(session.device.id)
                        session_members.setdefault(int(reference.asn), set()).add(
                            session.device.id
                        )

    # Build comparable ASN records for each device.
    live = {device: {} for device in live_asn}
    netbox_asn = {device: {} for device in live_asn}
    create_descriptions = {}
    stored_members = {}
    for asn, observers in asn_devices.items():
        record = netbox_objects.get(asn)
        local_observers = [
            device for device in observers if live_asn[device][asn][1]
        ]
        description_sources = observers
        if record is not None:
            description_sources = [
                device
                for device in local_observers
                if device_custom_field
                or nb_devices[device].id in devices_with_sessions
            ]
        source = next(
            (device for device in description_sources if live_asn[device][asn][0]),
            description_sources[0] if description_sources else None,
        )
        description = live_asn[source][asn][0] if source is not None else ""
        members = set()
        if record is None:
            create_descriptions[asn] = description
        elif device_custom_field:
            members = {
                int(
                    value["id"]
                    if isinstance(value, dict)
                    else getattr(value, "id", value)
                )
                for value in (record.custom_fields or {}).get(device_custom_field)
                or []
            }
            stored_members[asn] = members

        for device in observers:
            live[device][asn] = {}
            if record is not None:
                netbox_asn[device][asn] = {}
            device_id = nb_devices[device].id
            if device in local_observers and (
                device_custom_field or device_id in devices_with_sessions
            ):
                associated = (
                    device_id in members
                    or device_id in session_members.get(asn, ())
                )
                field = device_custom_field or "device_associated"
                live[device][asn][field] = True
                if record is not None:
                    netbox_asn[device][asn][field] = associated
        if record is not None and source is not None:
            live[source][asn]["description"] = apply_description_policy(
                description, record.description, preserve_description
            )
            netbox_asn[source][asn]["description"] = record.description or ""

    device_diffs = self.make_diff(live, netbox_asn)

    # Publish the same per-device diff for dry runs, approval, and applied results.
    for device, diff in device_diffs.items():
        ret.diff[device] = {
            **diff,
            "update": {
                str(asn): changes for asn, changes in diff["update"].items()
            },
        }
        ret.result[device] = {
            "created": [],
            "updated": [],
            "deleted": [],
            "in_sync": diff["in_sync"],
        }

    if dry_run:
        ret.result = ret.diff
        return ret
    if ret.failed:
        return ret
    # Merge device-level actions into one payload per ASN.
    creates = {}
    updates = {}
    for device, diff in sorted(device_diffs.items()):
        for asn in diff["create"]:
            creates.setdefault(asn, []).append(device)
        for asn, changes in diff["update"].items():
            if "description" not in changes and device_custom_field not in changes:
                continue
            payload, affected = updates.setdefault(
                asn, ({"id": netbox_objects[asn].id}, [])
            )
            if "description" in changes:
                payload["description"] = changes["description"]["new_value"]
            if device_custom_field in changes:
                if "custom_fields" not in payload:
                    payload["custom_fields"] = {
                        device_custom_field: stored_members[asn].copy()
                    }
                payload["custom_fields"][device_custom_field].add(
                    nb_devices[device].id
                )
            affected.append(device)

    # Prepare create payloads only when a valid RIR is available.
    create_items = []
    if rir_obj:
        for asn, devices in sorted(creates.items()):
            payload = {
                "asn": asn,
                "rir": rir_obj.id,
                "description": create_descriptions[asn],
            }
            if device_custom_field:
                payload["custom_fields"] = {
                    device_custom_field: sorted(
                        nb_devices[device].id
                        for device in devices
                        if live[device][asn].get(device_custom_field)
                    )
                }
            create_items.append((asn, payload, devices))
    elif creates:
        msg = "cannot create missing ASNs: no RIR provided, use 'rir' parameter"
        job.event(msg, severity="WARNING")
        log.warning(f"{self.name} - {msg}")
        ret.errors.append(msg)

    update_items = []
    for asn, (payload, affected) in sorted(updates.items()):
        if "custom_fields" in payload:
            fields = payload["custom_fields"]
            fields[device_custom_field] = sorted(fields[device_custom_field])
        update_items.append((asn, payload, affected))

    if not create_items and not update_items:
        job.event("no BGP ASN writes planned")
        return ret
    job.event(
        f"planned {len(create_items)} ASN creates and {len(update_items)} updates"
    )
    if with_approval and not review_sync_task_result(job, "BGP ASN sync", ret.diff):
        ret.status = "skipped"
        ret.result = ret.diff
        ret.dry_run = True
        ret.messages.append("review declined; changes were not applied")
        return ret

    # Create missing ASNs in batches and record each successful create.
    total_batches = (len(create_items) + batch_size - 1) // batch_size
    for offset in range(0, len(create_items), batch_size):
        batch = create_items[offset : offset + batch_size]
        batch_number = offset // batch_size + 1
        msg = f"creating ASN batch {batch_number}/{total_batches} ({len(batch)} ASN(s))"
        job.event(msg)
        log.info(msg)
        try:
            nb.ipam.asns.create([payload for _, payload, _ in batch])
        except Exception as exc:
            msg = f"failed ASN create batch {batch_number}/{total_batches}: {exc}"
            job.event(msg, severity="ERROR")
            ret.errors.append(msg)
            ret.failed = True
            # Include the failed batch and writes skipped after the failure.
            ret.resources_failed = sorted(
                set(ret.resources_failed)
                | {
                    device
                    for _, _, devices in create_items[offset:] + update_items
                    for device in devices
                }
            )
            return ret
        for asn, _, devices in batch:
            for device in devices:
                ret.result[device]["created"].append(asn)

    # Update existing ASNs in batches and credit only devices that needed the update.
    total_batches = (len(update_items) + batch_size - 1) // batch_size
    for offset in range(0, len(update_items), batch_size):
        batch = update_items[offset : offset + batch_size]
        batch_number = offset // batch_size + 1
        msg = f"updating ASN batch {batch_number}/{total_batches} ({len(batch)} ASN(s))"
        job.event(msg)
        log.info(msg)
        try:
            nb.ipam.asns.update([payload for _, payload, _ in batch])
        except Exception as exc:
            msg = f"failed ASN update batch {batch_number}/{total_batches}: {exc}"
            job.event(msg, severity="ERROR")
            ret.errors.append(msg)
            ret.failed = True
            ret.resources_failed = sorted(
                set(ret.resources_failed)
                | {
                    device
                    for _, _, devices in update_items[offset:]
                    for device in devices
                }
            )
            return ret
        for asn, _, devices in batch:
            for device in devices:
                ret.result[device]["updated"].append(asn)

    job.event("bgp asn sync complete")
    return ret