Skip to content

NetBox Sync BGP Communities Task¤

task API name: sync_bgp_community

The NetBox Sync BGP Communities task collects named BGP communities from live devices and reconciles them with NetBox. Route-target (rt) communities are stored as IPAM route targets. Other community types are stored as NetBox BGP plugin community objects when the plugin is installed.

Route targets are matched by community value. BGP plugin communities are matched by value and live community-set name so NetBox can hold several standard communities with the same value. The task creates missing objects and extends their optional community-name custom field with missing live names. An optional multi-object custom field associates each community with the devices on which it was observed. When the field is unavailable for an object type, the task can create missing records of that type and leaves existing records unchanged. The task never deletes NetBox objects or associations.

How It Works¤

  1. Resolve explicit device names and optional Nornir host filters.
  2. Confirm the selected devices exist in NetBox.
  3. Run Nornir parse_ttp with the TTP Templates bgp_communities getter.
  4. Group route targets by community value and BGP plugin communities by community value plus live community-set name.
  5. Compare each device's names and membership with matching NetBox objects.
  6. Return the diff or apply bulk create and update operations.

For BGP plugin communities, existing NetBox objects are matched in this order: same value with the live name contained in the configured community-name custom field, same value with a description matching the live name, then an unlabeled same-value object. If the community-name custom field is disabled or missing, the task starts with the description match.

If several route-target records use different names for the same value, the configured custom field stores the names as a comma-separated string. For example, 65000:200 named TENANT_BLUE on one device and VPN_BLUE on another is stored as:

TENANT_BLUE, VPN_BLUE

Existing custom-field values are preserved. New live names are appended only when they are missing.

Inputs¤

Parameter Required Default Description
devices Conditional None NetBox device names from which to collect communities
Nornir filters Conditional None Host filters such as FB, FC, FG, FL, or FR; may be combined with devices
instance No Worker default NetBox instance to target
branch No None NetBox Branching plugin branch to use
dry_run No False Return the calculated diff without writing to NetBox
with_approval No False Preview the diff and request approval before writing
timeout No 600 Timeout in seconds for host resolution and live parsing
community_name_field No community_name Custom field used to store live community-set names; set to False to disable name synchronization
device_custom_field No devices Multi-object custom field related to dcim.device that stores associated devices

At least one explicit device or Nornir host filter must select a device. Device names from both sources are combined and deduplicated.

Prerequisites¤

  • Selected devices must exist in NetBox.
  • The Nornir worker must support the TTP Templates bgp_communities getter for the device platform.
  • The NetBox BGP plugin is required to store non-route-target communities.
  • To synchronize community-set names, the configured custom field must exist and be assigned to ipam.routetarget, netbox_bgp.community, or both.
  • To associate devices, device_custom_field must name a multi-object custom field assigned to the community models and related to dcim.device.

The community-name custom field is optional. If it does not exist, the task emits a warning and continues creating community objects without updating community names. A missing device custom field is ignored. If the BGP plugin is unavailable, the task emits a warning and synchronizes route targets only.

Live Data¤

The getter returns one record for each concrete community value:

- value: 65000:100
  type: standard
  name: CUSTOMER_EXPORT
- value: 65000:200
  type: rt
  name: TENANT_BLUE

Records must contain non-empty string values for value, type, and name. Malformed worker, device, or record data is reported in the task errors.

Execution Modes¤

Dry run — dry_run=True returns the prepared diff and performs no NetBox writes.

With approval — with_approval=True presents the prepared diff for review before applying it. A declined review returns the diff with status="skipped" and dry_run=True. When both options are enabled, dry-run behavior takes precedence and no approval prompt is shown.

Live run — The default mode creates and updates NetBox objects. The prepared plan remains available in the top-level diff field.

Output¤

Results and diffs are keyed by device, with route_targets and communities scopes. Shared keys appear under each reporting device. The communities scope is omitted when the NetBox BGP plugin is unavailable.

Dry-run output uses create, update, delete, and in_sync actions:

{
  "edge-1": {
    "route_targets": {
      "create": [
        "65000:200"
      ],
      "update": {},
      "delete": [],
      "in_sync": []
    },
    "communities": {
      "create": [
        "65000:100::BLUE_EXPORT"
      ],
      "update": {},
      "delete": [],
      "in_sync": []
    }
  }
}

Live-run output uses created, updated, deleted, and in_sync:

{
  "edge-1": {
    "route_targets": {
      "created": [
        "65000:200"
      ],
      "updated": [],
      "deleted": [],
      "in_sync": []
    },
    "communities": {
      "created": [
        "65000:100::BLUE_EXPORT"
      ],
      "updated": [],
      "deleted": [],
      "in_sync": []
    }
  }
}

Deletion lists are always empty because community objects may be shared beyond the selected device scope.

Branching Support¤

Pass branch=<name> to read and write objects through a NetBox Branching plugin branch instead of the main database. The task creates the branch if it does not exist and waits for it to become ready.

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¤

Preview communities collected from explicit devices:

nf# netbox sync bgp-communities devices fn-ceos-lf-1 fn-ceos-lf-2 dry-run

Select devices with a Nornir filter and use a different custom field:

nf# netbox sync bgp-communities FC leaf community-name-field community_aliases

Create objects without synchronizing community-set names:

nf# netbox sync bgp-communities devices edge-1 community-name-field false

Preview and request approval before applying changes:

nf# netbox sync bgp-communities devices edge-1 with-approval

Synchronize into a NetBox branch:

nf# netbox sync bgp-communities devices edge-1 branch community-review
from norfab.core.nfapi import NorFab

with NorFab(inventory="./inventory.yaml") as nf:
    client = nf.make_client()
    result = client.run_job(
        "netbox",
        "sync_bgp_community",
        workers="any",
        kwargs={
            "devices": ["edge-1", "edge-2"],
            "dry_run": True,
            "community_name_field": "community_aliases",
        },
    )
    print(result)

The same task can use Nornir filters without an explicit device list:

from norfab.core.nfapi import NorFab

nf = NorFab(inventory="./inventory.yaml")
nf.start()
try:
    client = nf.make_client()
    result = client.run_job(
        "netbox",
        "sync_bgp_community",
        workers="any",
        kwargs={"FR": "edge-[12]", "community_name_field": False},
    )
    print(result)
finally:
    nf.destroy()

Notes and Gotchas¤

  • Devices on platforms without a BGP community parser are skipped and listed in resources_unsupported.
  • The NetBox BGP plugin must accept each non-route-target value returned by the getter. Unsupported values produce NetBox API validation errors.
  • A shared record can be in sync for one device and need an update for another. The task combines the required changes into one write per record.
  • NetBox-only objects are retained because a scoped live query cannot prove that a globally shared community is stale.
  • with_approval cannot be combined with the NFCLI nowait option.

Troubleshooting¤

If a device has no live result, confirm its platform supports the bgp_communities getter and that the Nornir worker can reach it. Also confirm that every explicitly selected device exists in NetBox.

For custom-field warnings, confirm the field name and its object assignments. Use a long-text field so it can hold multiple comma-separated community names.

NORFAB NetBox Sync BGP Communities Command Shell Reference¤

nf# man tree netbox.sync.bgp-communities
root
└── netbox:    NetBox service
    └── sync:    Synchronize data with NetBox
        └── bgp-communities:    Sync live BGP communities with NetBox
            ├── timeout:    Job timeout, default 600
            ├── workers:    Filter worker to target, default 'any'
            ├── verbose-result:    Control output details, default 'False'
            ├── nowait:    Do not wait for job completion, default 'False'
            ├── instance:    NetBox instance name to target
            ├── branch:    NetBox Branching plugin branch name to use
            ├── dry-run:    Return the diff without writing to NetBox
            ├── with-approval:    Preview changes and ask for approval
            ├── devices:    NetBox devices from which to collect communities
            ├── community-name-field:    Custom field for live community-set names
            ├── FO:    Filter hosts using a Filter Object
            ├── FB:    Filter hosts by name using glob patterns
            ├── FH:    Filter hosts by hostname
            ├── FC:    Filter hosts by name containment
            ├── FR:    Filter hosts by name using regular expressions
            ├── FG:    Filter hosts by group
            ├── FP:    Filter hosts by hostname using an IP prefix
            ├── FL:    Filter hosts by name list
            ├── FM:    Filter hosts by platform
            ├── FX:    Exclude hosts by name
            └── FN:    Negate the host filter match
nf#

Python API Reference¤

Synchronize live BGP communities with NetBox.

Route-target communities are stored as IPAM route targets. Every other community type is stored as a NetBox BGP plugin community. Route targets are keyed by community value. BGP plugin communities are keyed by community value and live community-set name, allowing NetBox to hold several standard communities with the same value. Objects are never deleted. When the configured custom field exists, it stores the sorted, comma-separated live community-set names observed for each object. The selected device custom field records devices on which each community was observed. Existing records can be updated only when that field applies to their object type. Platforms without a parser are reported in resources_unsupported. Missing live data is reported per device.

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
community_name_field Union[str, bool]

Optional custom field for community-set names.

'community_name'
device_custom_field str

Community custom field containing associated devices.

'devices'
batch_size int

Maximum number of records per NetBox write.

1000
**kwargs Any

Nornir FFun host filters.

{}

Returns:

Name Type Description
Result Result

Per-device route-target and BGP community synchronization actions.

Source code in norfab\workers\netbox_worker\bgp_community_tasks.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
@Task(
    fastapi={"methods": ["POST"], "schema": NetboxFastApiArgs.model_json_schema()},
    input=SyncBgpCommunityInput,
    output=SyncBgpCommunityResult,
    mcp={
        "annotations": {
            "title": "Sync BGP Communities",
            "readOnlyHint": False,
            "destructiveHint": True,
            "idempotentHint": True,
            "openWorldHint": True,
        }
    },
)
def sync_bgp_community(
    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,
    community_name_field: Union[str, bool] = "community_name",
    device_custom_field: str = "devices",
    batch_size: int = 1000,
    **kwargs: Any,
) -> Result:
    """Synchronize live BGP communities with NetBox.

    Route-target communities are stored as IPAM route targets. Every other
    community type is stored as a NetBox BGP plugin community. Route
    targets are keyed by community value. BGP plugin communities are keyed
    by community value and live community-set name, allowing NetBox to hold
    several standard communities with the same value. Objects are never
    deleted. When the configured custom field exists, it stores the sorted,
    comma-separated live community-set names observed for each object. The
    selected device custom field records devices on which each community was
    observed. Existing records can be updated only when that field applies
    to their object type. Platforms without a parser are reported in
    `resources_unsupported`. Missing live data is reported per device.

    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.
        community_name_field: Optional custom field for community-set names.
        device_custom_field: Community custom field containing associated devices.
        batch_size: Maximum number of records per NetBox write.
        **kwargs: Nornir FFun host filters.

    Returns:
        Result: Per-device route-target and BGP community synchronization actions.
    """
    devices = list(devices or [])
    instance = instance or self.default_instance
    ret = Result(
        task=f"{self.name}:sync_bgp_community",
        result={},
        resources=[instance],
        dry_run=dry_run,
        diff={},
    )

    msg = (
        f"starting BGP community sync using NetBox instance '{instance}' for "
        f"{len(devices)} explicit device(s), dry_run={dry_run}"
    )
    job.event(msg)
    log.info(f"{self.name} - {msg}")

    msg = f"validating NetBox BGP plugin for '{instance}'"
    job.event(msg)
    log.info(f"{self.name} - {msg}")
    has_bgp_plugin = self.has_plugin("netbox_bgp", instance)
    if not has_bgp_plugin:
        msg = (
            f"netbox instance '{instance}' has no BGP plugin installed; "
            "syncing route targets only"
        )
        job.event(msg, severity="WARNING")
        log.warning(f"{self.name} - {msg}")

    nb = self._get_pynetbox(instance, branch=branch, job=job)

    if kwargs:
        msg = "resolving devices from Nornir filters"
        job.event(msg)
        log.info(f"{self.name} - {msg}")
        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} - {msg}")
        ret.errors.append(msg)
        ret.failed = True
        return ret

    netbox_devices = {
        device.name: device
        for device in self.bulk_filter(
            nb.dcim.devices,
            name=devices,
            fields="id,name",
        )
    }
    for device_name in [name for name in devices if name not in netbox_devices]:
        msg = f"device '{device_name}' not found in NetBox"
        job.event(msg, severity="ERROR")
        log.error(f"{self.name} - {msg}")
        ret.errors.append(msg)
        ret.resources_failed.append(device_name)
    devices = [name for name in devices if name in netbox_devices]
    if not devices:
        ret.failed = True
        return ret
    msg = f"validated {len(devices)} NetBox device(s)"
    job.event(msg)
    log.info(f"{self.name} - {msg}")

    if community_name_field and not nb.extras.custom_fields.get(
        name=community_name_field
    ):
        msg = (
            f"custom field '{community_name_field}' not found in NetBox; "
            "community name synchronization disabled"
        )
        job.event(msg, severity="WARNING")
        log.warning(f"{self.name} - {msg}")
        community_name_field = False

    endpoints = {
        "route_targets": (nb.ipam.route_targets, "name", "ipam.routetarget"),
    }
    if has_bgp_plugin:
        endpoints["communities"] = (
            nb.plugins.bgp.community,
            "value",
            "netbox_bgp.community",
        )
    device_field = nb.extras.custom_fields.get(name=device_custom_field)
    device_object_types = (
        getattr(device_field, "object_types", None)
        or getattr(device_field, "content_types", None)
        or []
    )

    msg = f"collecting live BGP communities from {len(devices)} device(s)"
    job.event(msg)
    log.info(f"{self.name} - {msg}")
    parsed = self.client.run_job(
        "nornir",
        "parse_ttp",
        kwargs={"get": "bgp_communities", "FL": devices},
        workers="all",
        timeout=timeout,
    )
    # Keep each device's live names separate until comparison.
    observations = {}
    identities = {community_type: {} for community_type in endpoints}
    reported_failures = set()
    unsupported = set()
    parsed_count = 0
    for worker_name, worker_data in parsed.items():
        ret.messages.extend(worker_data.get("messages") or [])
        unsupported.update(worker_data.get("resources_unsupported") or [])
        failures = (
            set(worker_data.get("resources_failed") or []) & netbox_devices.keys()
        )
        if failures:
            reported_failures.update(failures)
            msg = (
                f"{worker_name} failed to fetch BGP community data from devices "
                f"{', '.join(sorted(failures))}"
            )
            job.event(msg, severity="ERROR")
            log.error(f"{self.name} - {msg}")
            ret.errors.append(msg)
        if worker_data.get("failed"):
            msg = f"worker '{worker_name}' failed to collect BGP communities"
            job.event(msg, severity="ERROR")
            log.error(f"{self.name} - {msg}")
            ret.errors.append(msg)
            continue
        records_by_device = worker_data.get("result")
        if not isinstance(records_by_device, dict):
            msg = f"worker '{worker_name}' returned malformed community data"
            job.event(msg, severity="ERROR")
            log.error(f"{self.name} - {msg}")
            ret.errors.append(msg)
            continue
        for device, records in records_by_device.items():
            if device not in netbox_devices or device in failures:
                continue
            if not isinstance(records, list):
                msg = f"device '{device}' community result is not a list"
                job.event(msg, severity="ERROR")
                log.error(f"{self.name} - {msg}")
                ret.errors.append(msg)
                reported_failures.add(device)
                continue
            if any(
                not isinstance(record, dict)
                or not all(
                    isinstance(record.get(field), str) and record[field].strip()
                    for field in ("value", "type")
                )
                for record in records
            ):
                msg = f"device '{device}' returned malformed community record"
                job.event(msg, severity="ERROR")
                log.error(f"{self.name} - {msg}")
                ret.errors.append(msg)
                reported_failures.add(device)
                continue
            # An empty parser result still confirms that the device was collected.
            community_types = observations.setdefault(
                device, {community_type: {} for community_type in endpoints}
            )
            for record in records:
                value = record["value"].strip()
                if ":" not in value:
                    continue
                name = record.get("name")
                name = name.strip() if isinstance(name, str) else ""
                community_type = (
                    "route_targets"
                    if record["type"].strip().lower() == "rt"
                    else "communities"
                )
                if community_type not in endpoints:
                    continue
                parsed_count += 1
                key = (
                    value
                    if community_type == "route_targets"
                    else f"{value}::{name or NO_COMMUNITY_NAME}"
                )
                identities[community_type][key] = (value, name)
                names = community_types[community_type].setdefault(key, set())
                if name:
                    names.add(name)

    unsupported &= netbox_devices.keys()
    ret.resources_unsupported = sorted(unsupported - reported_failures)
    # Exit successfully when no selected device has a matching parser.
    if not ret.errors and set(devices).issubset(ret.resources_unsupported):
        return ret
    missing = (
        netbox_devices.keys() - observations.keys() - set(ret.resources_unsupported)
    )
    for device in sorted(missing - reported_failures):
        msg = f"device '{device}' is missing a live community result"
        job.event(msg, severity="ERROR")
        log.error(f"{self.name} - {msg}")
        ret.errors.append(msg)
    ret.resources_failed.extend(sorted(missing))
    if not observations:
        ret.failed = True
        return ret
    msg = (
        f"parsed {parsed_count} live community record(s) from "
        f"{len(observations)} device(s)"
    )
    job.event(msg)
    log.info(f"{self.name} - {msg}")

    live = {device: {} for device in sorted(observations)}
    netbox = {device: {} for device in live}
    matched = {}
    for community_type, (endpoint, value_field, object_type) in endpoints.items():
        has_devices = object_type in device_object_types
        keys = identities[community_type]
        values = sorted({value for value, _ in keys.values()})
        label = (
            "route targets"
            if community_type == "route_targets"
            else "BGP plugin communities"
        )
        msg = f"matching live {label} with NetBox"
        job.event(msg)
        log.info(f"{self.name} - {msg}")
        candidates = {}
        if values:
            fields = f"id,{value_field},custom_fields"
            if community_type == "communities":
                fields += ",description"
            for row in self.bulk_filter(
                endpoint, fields=fields, **{value_field: values}
            ):
                candidates.setdefault(str(getattr(row, value_field)), []).append(
                    row
                )

        # Prefer a stored alias, then a matching description, then an unlabeled record.
        for key, (value, name) in sorted(keys.items()):
            identity = (community_type, key)
            rows = candidates.get(value, [])
            if not rows:
                continue
            if community_type == "route_targets" or not name:
                matched[identity] = rows[0]
                continue
            named, described, unlabeled = None, None, None
            for row in rows:
                custom_fields = row.custom_fields or {}
                names = {
                    item.strip()
                    for item in str(
                        custom_fields.get(community_name_field) or ""
                    ).split(",")
                    if item.strip()
                }
                description = (row.description or "").strip()
                if name in names:
                    named = row
                    break
                if described is None and name == description:
                    described = row
                if unlabeled is None and not names and not description:
                    unlabeled = row
            row = named or described or unlabeled
            if row is not None:
                matched[identity] = row

        # Add only this device's ID and names to the stored values.
        for device in live:
            device_id = netbox_devices[device].id
            desired = live[device]
            current = netbox[device]
            for key, names in sorted(observations[device][community_type].items()):
                identity = (community_type, key)
                row = matched.get(identity)
                custom_fields = (row.custom_fields or {}) if row is not None else {}
                stored_names = str(custom_fields.get(community_name_field) or "")
                device_ids = (
                    {
                        member["id"]
                        for member in custom_fields.get(device_custom_field) or []
                    }
                    if has_devices
                    else set()
                )
                desired[identity] = normalise_community_name_field(
                    stored_names, community_name_field, ", ".join(sorted(names))
                )
                if has_devices or row is not None:
                    desired[identity][device_custom_field] = sorted(
                        device_ids | {device_id}
                    )
                if row is not None:
                    current[identity] = normalise_community_name_field(
                        stored_names, community_name_field, ""
                    )
                    current[identity][device_custom_field] = (
                        sorted(device_ids) if has_devices else None
                    )

    # Compare both community types together and unpack the tuple keys for callers.
    diff = self.make_diff(live, netbox)
    for device in live:
        ret.diff[device] = {
            community_type: {
                "create": [],
                "delete": [],
                "update": {},
                "in_sync": [],
            }
            for community_type in endpoints
        }
        for action, identities_for_action in diff[device].items():
            for identity in identities_for_action:
                community_type, key = identity
                entries = ret.diff[device][community_type][action]
                if action == "update":
                    entries[key] = identities_for_action[identity]
                else:
                    entries.append(key)

    # Merge writes by physical record and track which device actions each write fulfills.
    writes = {}
    for community_type, (_, value_field, object_type) in endpoints.items():
        has_devices = object_type in device_object_types
        keys = identities[community_type]
        writes[community_type] = {"create": {}, "update": {}}
        blocked = set()
        for device in live:
            actions = ret.diff[device][community_type]
            for action in ("create", "update"):
                for key in actions[action]:
                    identity = (community_type, key)
                    if action == "update" and not has_devices:
                        blocked.add(device)
                        continue
                    if action == "create":
                        value, name = keys[key]
                        payload = {value_field: value}
                        if community_type == "communities" and name:
                            payload["description"] = name
                        write_key = key
                    else:
                        write_key = matched[identity].id
                        payload = {"id": write_key}
                    payload, affected = writes[community_type][action].setdefault(
                        write_key, (payload, [])
                    )
                    affected.append((device, key))
                    fields = live[device][identity]
                    if action == "update":
                        fields = {
                            field: change["new_value"]
                            for field, change in actions[action][key].items()
                        }
                    if not fields:
                        continue
                    custom_fields = payload.setdefault("custom_fields", {})
                    if device_custom_field in fields:
                        custom_fields[device_custom_field] = sorted(
                            set(custom_fields.get(device_custom_field, []))
                            | set(fields[device_custom_field])
                        )
                    if community_name_field in fields:
                        custom_fields.update(
                            normalise_community_name_field(
                                custom_fields.get(community_name_field, ""),
                                community_name_field,
                                fields[community_name_field],
                            )
                        )
        if blocked:
            msg = (
                f"custom field '{device_custom_field}' unavailable for "
                f"{community_type.replace('_', ' ')}; existing records cannot be updated "
                f"for {', '.join(sorted(blocked))}"
            )
            ret.messages.append(msg)
            job.event(msg, severity="WARNING")

    create_count = sum(len(actions["create"]) for actions in writes.values())
    update_count = sum(len(actions["update"]) for actions in writes.values())
    in_sync_count = sum(
        len(actions["in_sync"])
        for community_types in ret.diff.values()
        for actions in community_types.values()
    )
    msg = (
        f"bgp community sync diff complete: "
        f"{create_count} create, {update_count} update, {in_sync_count} in sync"
    )
    job.event(msg)
    log.info(f"{self.name} - {msg}")

    if dry_run:
        ret.result = ret.diff
        return ret
    has_writes = bool(create_count or update_count)
    if (
        with_approval
        and has_writes
        and not review_sync_task_result(job, "BGP community sync", ret.diff)
    ):
        ret.status = "skipped"
        ret.dry_run = True
        ret.result = ret.diff
        ret.messages.append("review declined; changes were not applied")
        return ret

    for device, community_types in ret.diff.items():
        ret.result[device] = {
            community_type: {
                "created": [],
                "updated": [],
                "deleted": [],
                "in_sync": actions["in_sync"],
            }
            for community_type, actions in community_types.items()
        }
    if not has_writes:
        job.event("no BGP community sync changes required")
        return ret

    for community_type, actions in writes.items():
        endpoint = endpoints[community_type][0]
        if community_type == "route_targets":
            label, plural, unit = "route target", "route target(s)", "targets"
        else:
            label, plural, unit = (
                "BGP community",
                "BGP community object(s)",
                "objects",
            )
        creates = actions["create"]
        create_keys = list(creates)
        if create_keys:
            msg = f"creating {len(create_keys)} {plural} in NetBox"
            job.event(msg)
            log.info(f"{self.name} - {msg}")
        total_batches = (len(create_keys) + batch_size - 1) // batch_size
        for start in range(0, len(create_keys), batch_size):
            batch = create_keys[start : start + batch_size]
            batch_number = start // batch_size + 1
            msg = (
                f"creating {label} batch {batch_number}/{total_batches} "
                f"({len(batch)} {unit})"
            )
            job.event(msg)
            log.info(msg)
            try:
                endpoint.create([creates[key][0] for key in batch])
            except Exception as exc:
                msg = f"failed to create {label} batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                break
            for write_key in batch:
                _, affected = creates.pop(write_key)
                for device, key in affected:
                    ret.result[device][community_type]["created"].append(key)
        if ret.failed:
            break

        updates = actions["update"]
        update_keys = list(updates)
        if update_keys:
            msg = f"updating {len(update_keys)} {plural} in NetBox"
            job.event(msg)
            log.info(f"{self.name} - {msg}")
        total_batches = (len(update_keys) + batch_size - 1) // batch_size
        for start in range(0, len(update_keys), batch_size):
            batch = update_keys[start : start + batch_size]
            batch_number = start // batch_size + 1
            msg = (
                f"updating {label} batch {batch_number}/{total_batches} "
                f"({len(batch)} {unit})"
            )
            job.event(msg)
            log.info(msg)
            try:
                endpoint.update([updates[key][0] for key in batch])
            except Exception as exc:
                msg = f"failed to update {label} batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                break
            for write_key in batch:
                _, affected = updates.pop(write_key)
                for device, key in affected:
                    ret.result[device][community_type]["updated"].append(key)
        if ret.failed:
            break

    for community_types in ret.result.values():
        for actions in community_types.values():
            actions["created"].sort()
            actions["updated"].sort()
    # Successful batches were removed from the plan, leaving failed and pending writes.
    if ret.failed:
        ret.resources_failed = sorted(
            set(ret.resources_failed)
            | {
                device
                for actions in writes.values()
                for items in actions.values()
                for _, affected in items.values()
                for device, _ in affected
            }
        )
        return ret
    msg = (
        f"bgp community sync complete: {create_count} created, "
        f"{update_count} updated, {in_sync_count} in sync"
    )
    job.event(msg)
    log.info(f"{self.name} - {msg}")
    return ret