Skip to content

Sync VRFs¤

The sync_vrfs task reconciles VRFs from live devices with global NetBox VRF objects and assigns existing NetBox interfaces to their live VRFs. A VRF name is its identity. The task synchronizes its description and adds live import and export route targets to the existing NetBox associations. Route-target and device and routing-policy associations are additive.

The task creates missing NetBox route targets and BGP routing-policy objects before it creates or updates VRFs. Route distinguishers returned by the TTP getter are not stored in NetBox. If the BGP plugin is absent, routing-policy processing is skipped while the rest of VRF synchronization continues.

If multiple existing NetBox VRFs match the same live VRF name, the task logs a warning and reconciles against the matched VRF with the numerically lowest NetBox ID. Other same-name VRFs are left unchanged.

Inputs¤

Input Default Description
instance Worker default NetBox instance name.
dry_run False Calculate the diff without writing to NetBox.
with_approval False Present the prepared plan for approval before writing. Ignored during dry-run.
timeout 600 Timeout in seconds for host resolution and TTP parsing.
devices None Explicit NetBox and Nornir device names.
branch None NetBox Branching plugin branch name.
device_custom_field devices Multi-object VRF custom field related to dcim.device.
rpl_import_ipv4 rpl_import_ipv4 VRF multi-object custom field for IPv4 import routing policies.
rpl_import_ipv6 rpl_import_ipv6 VRF multi-object custom field for IPv6 import routing policies.
rpl_export_ipv4 rpl_export_ipv4 VRF multi-object custom field for IPv4 export routing policies.
rpl_export_ipv6 rpl_export_ipv6 VRF multi-object custom field for IPv6 export routing policies.
preserve_description None Preserve NetBox descriptions only when live text is empty. Use True to always preserve or False to always use live text.
interface_map None Ordered interface-name mapping rules or an nf:// YAML file.
Nornir filters None FO, FB, FH, FC, FR, FG, FP, FL, FM, FX, and FN.

Provide devices or at least one Nornir host filter.

NetBox VRF Device Custom Field¤

By default, the task uses a VRF custom field named devices. Configure it as a multi-object field assigned to ipam.vrf and related to dcim.device. Use device_custom_field to select another field with the same configuration.

The task adds devices on which the VRF was observed and preserves existing associations. It does not remove devices during a scoped run. If the configured field exists but has no value on an existing VRF, it is treated as an empty association list. If the configured field does not exist, the task continues without device association changes.

For example, when device_custom_field="vrf_devices" is requested but NetBox does not have a custom field named vrf_devices, VRFs and route targets are still synchronized. The task does not fail and does not add a device custom field value to the VRF.

Routing-policy custom fields¤

Configure each selected policy field on ipam.vrf as a multi-object custom field related to netbox_bgp.routingpolicy. The four arguments select the custom-field names; missing fields are skipped. The task combines policy names reported for each address family across selected devices, compares them with the NetBox references by name, and adds new associations without removing NetBox-only policies. An empty live policy does not clear an existing field. Missing policy objects are included in dry-run and approval plans and created before VRF writes. The BGP plugin must be installed for this processing; its absence produces a warning and leaves policy fields out of the VRF diff.

Live data¤

The task runs Nornir parse_ttp with get="vrfs", which returns:

- name: TENANT_A
  description: Tenant A services
  rd: 65000:201
  interfaces:
    - Ethernet1.201
  address_families:
    ipv4:
      rt_import:
        - 65000:201
        - 65000:301
      rt_export:
        - 65000:201
        - 65000:302
      route_policy_import: TENANT_A_IMPORT
      route_policy_export: TENANT_A_EXPORT
    ipv6:
      rt_import: []
      rt_export: []
      route_policy_import: null
      route_policy_export: null

The task uses name, description, interfaces, and the import/export route targets and policies from every address family. When instance_type is present, records whose value is not vrf are silently skipped. Description text and route-target values are used without string normalization, and null descriptions become an empty string.

Interface assignments¤

The task maps each parsed interface name with interface_map, then compares a normalized {device: {interface: {vrf: name}}} live state with the matching NetBox interfaces. Changed assignments are updated in bulk and matching assignments are reported under in_sync. Missing interfaces are reported and skipped. Interfaces not named by live VRF data are outside the task scope and their existing assignments are retained.

For each VRF, devices are ordered alphabetically. The first non-empty description in that order becomes the NetBox description; the description is empty when no device supplies one. For existing VRFs, the default preserve_description=None keeps the NetBox description when this aggregate live description is empty. Set it to True to always retain the NetBox value, or False to always apply the live value, including an empty string. Different descriptions from multiple devices are resolved by this rule and are not reported as conflicts.

Import and export route-target lists from every reporting device and address family are combined and deduplicated in first-seen order. The shared make_diff method compares that aggregate with NetBox and ignores route-target order. If it finds an import or export route-target difference for an existing VRF, the task combines the current NetBox list with live targets that are not already in that list and places the combined list in the update. For a new VRF, or an existing VRF with an empty target set, the live aggregate populates the association. Route-target differences are not reported as errors, and all reporting devices are added to the device custom field.

Routing-policy lists use the same first-seen deduplication and additive update policy. Only changed custom fields are written for an existing VRF.

Multi-device aggregation example¤

Assume the selected devices return the following records for the same VRF:

- name: TENANT_A
  description:
  interfaces: [Ethernet1.100]
  address_families:
    ipv4:
      rt_import: [65000:100, 65000:200]
      rt_export: [65000:100]
- name: TENANT_A
  description: Tenant A services
  interfaces: [Ethernet1.100]
  address_families:
    ipv4:
      rt_import: [65000:100, 65000:300]
      rt_export: [65000:100, 65000:400]

The task processes edge-a before edge-b because device names are sorted. The empty description from edge-a is skipped, so Tenant A services from edge-b becomes the desired description. It combines the live lists as follows:

TENANT_A:
  description: Tenant A services
  import_targets:
    - 65000:100
    - 65000:200
    - 65000:300
  export_targets:
    - 65000:100
    - 65000:400
  devices:
    - edge-a
    - edge-b

The task preserves first-seen order while removing duplicate aggregate values. NetBox stores VRF route targets as object relationships, so the resulting VRF is associated with import targets 65000:100, 65000:200, and 65000:300, and export targets 65000:100 and 65000:400.

If NetBox initially associates TENANT_A with import target 65000:999 and export targets 65000:100 and 65000:999, the task produces this state:

NetBox item Result
TENANT_A description Changed to Tenant A services.
Import associations Extended to 65000:999, 65000:100, 65000:200, and 65000:300.
Export associations Extended to 65000:100, 65000:999, and 65000:400.
Missing route-target objects Created before the VRF is updated; existing objects are reused.
Existing 65000:999 associations Retained on TENANT_A.
Route-target object 65000:999 Retained in NetBox.
Device associations edge-a and edge-b are added; devices already recorded on the VRF are retained.

The shared make_diff method initially detects the difference between the raw live aggregate and the current NetBox VRF. The task then replaces the route-target value in that update plan with the combined list. An order-only difference does not update the VRF. A missing live membership extends the existing relationship and does not add an error to the result. A NetBox-only membership is retained in the merged update.

Because the comparison uses the raw live aggregate before the merge, a NetBox-only route target remains a difference on later runs. The task can report the VRF as updated again, but the NetBox-only association remains attached and is never removed.

Output¤

Results contain separate vrfs, route_targets, routing_policies, and interfaces sections. Dry-run returns the standard sync diff:

{
  "vrfs": {
    "create": ["TENANT_A"],
    "update": {
      "TENANT_B": {
        "export_targets": {
          "old_value": ["65000:999"],
          "new_value": ["65000:999", "65000:202"]
        }
      }
    },
    "delete": [],
    "in_sync": ["CONTROL_PLANE"]
  },
  "route_targets": {
    "create": ["65000:201", "65000:202"],
    "update": {},
    "delete": [],
    "in_sync": []
  },
  "routing_policies": {
    "create": ["TENANT_A_IMPORT", "TENANT_A_EXPORT"],
    "update": {},
    "delete": [],
    "in_sync": []
  },
  "interfaces": {
    "edge-a": {
      "create": [],
      "update": {},
      "delete": [],
      "in_sync": ["Ethernet1.100"]
    }
  }
}

Live runs use completed-action verbs. The prepared plan remains available in the top-level diff field:

{
  "vrfs": {
    "created": ["TENANT_A"],
    "updated": ["TENANT_B"],
    "deleted": [],
    "in_sync": ["CONTROL_PLANE"]
  },
  "route_targets": {
    "created": ["65000:201", "65000:202"],
    "updated": [],
    "deleted": [],
    "in_sync": []
  },
  "routing_policies": {
    "created": ["TENANT_A_IMPORT", "TENANT_A_EXPORT"],
    "updated": [],
    "deleted": [],
    "in_sync": []
  },
  "interfaces": {
    "edge-a": {
      "created": [],
      "updated": ["Ethernet1.201"],
      "deleted": [],
      "in_sync": []
    }
  }
}

The route_targets and routing_policies sections report only missing objects that the task plans to create or has created. Their update, delete, and in-sync categories remain empty. Association changes are reported as fields of the corresponding VRF update.

Deletions¤

The task does not delete VRFs, route-target or routing-policy objects, their associations, device associations, or interface assignments that are absent from live VRF data. A selected device set does not prove that existing NetBox data is stale, so delete and deleted remain empty.

Condition Action
Live VRF is missing from NetBox Create the VRF.
Live route target is missing from NetBox Create the route-target object and associate it with the VRF.
Live routing policy is missing from NetBox Create the routing-policy object and associate it with the VRF custom field.
NetBox VRF association is absent from the live aggregate Keep the existing association on the VRF.
Existing route-target object is not reported by live data Keep the route-target object.
NetBox VRF is absent from the selected devices Keep the NetBox VRF.

Branches¤

The task obtains its NetBox client with the requested branch. Reads and writes therefore remain inside that branch. The NetBox Branching plugin must be installed and configured for branch use.

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 VRF changes:

nf# netbox sync vrfs devices fn-ceos-lf-1 dry-run

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

nf# netbox sync vrfs FC leaf device-custom-field vrf_devices

Always keep existing NetBox descriptions:

nf# netbox sync vrfs devices fn-ceos-lf-1 preserve-description true
from norfab.core.nfapi import NorFab

with NorFab(inventory="./inventory.yaml") as nf:
    client = nf.make_client()
    result = client.run_job(
        "netbox",
        "sync_vrfs",
        workers="any",
        kwargs={
            "devices": ["fn-ceos-lf-1", "fn-ceos-lf-2"],
            "dry_run": True,
            "device_custom_field": "devices",
            "rpl_import_ipv4": "rpl_import_ipv4",
            "rpl_import_ipv6": "rpl_import_ipv6",
            "rpl_export_ipv4": "rpl_export_ipv4",
            "rpl_export_ipv6": "rpl_export_ipv6",
            "preserve_description": None,
            "interface_map": [],
        },
    )
    print(result)

Troubleshooting¤

Missing parser data¤

Confirm the device platform is supported by the TTP vrfs getter and that the Nornir worker can run the getter's command. Missing or malformed results are reported as errors; valid results from other devices and workers still proceed.

Live VRF aggregation¤

Every selected device contributes its import and export route targets. Check the selected device set when the aggregate contains an unexpected target. For descriptions, the first non-empty value in sorted device-name order is used.

Device custom field¤

Confirm that the field is assigned to ipam.vrf, uses the multi-object type, and relates to dcim.device. The field name must match device_custom_field exactly.

Routing-policy custom fields¤

Confirm the BGP plugin is installed and the selected VRF fields use multiobject references to netbox_bgp.routingpolicy. The Arista EOS VRF getter maps import map and export map to IPv4 policy values and returns empty IPv6 policy values; platforms with explicit IPv6 address-family policies can populate the IPv6 fields.

Missing interfaces¤

Run sync_device_interfaces first and use the same interface_map in both tasks. VRF sync reports a referenced interface that does not exist in NetBox and continues with the remaining assignments.

NetBox write failures¤

Confirm route-target values are valid NetBox route-target names and that the custom field accepts device object IDs. Correct the validation error and rerun the dry-run before applying changes.

Task command shell reference¤

nf# man tree netbox.sync.vrfs

R - required field, M - supports multiline input, D - dynamic key

root
└── netbox:    Netbox service
    └── sync:    Sync Netbox data
        └── vrfs:    Sync live VRF configuration with NetBox
            ├── instance:    Netbox instance name to target
            ├── dry-run:    Calculate the VRF diff without writing to NetBox, default 'False'
            ├── branch:    NetBox branching plugin branch name to use
            ├── 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
            ├── FX:    Filter hosts excluding them by name
            ├── FN:    Negate the match
            ├── devices:    List of NetBox devices to collect VRFs from
            ├── timeout:    Job timeout
            ├── with-approval:    Preview VRF changes and ask for review before writing to NetBox, default 'False'
            ├── device-custom-field:    VRF custom field that stores associated NetBox devices, default 'devices'
            ├── rpl-import-ipv4:    VRF custom field for IPv4 import routing policies, default 'rpl_import_ipv4'
            ├── rpl-import-ipv6:    VRF custom field for IPv6 import routing policies, default 'rpl_import_ipv6'
            ├── rpl-export-ipv4:    VRF custom field for IPv4 export routing policies, default 'rpl_export_ipv4'
            ├── rpl-export-ipv6:    VRF custom field for IPv6 export routing policies, default 'rpl_export_ipv6'
            ├── preserve-description:    Preserve NetBox descriptions always (true), when live text is empty (null), or never (false)
            ├── interface-map:    Ordered interface name mapping rules or nf:// YAML file reference
            ├── workers:    Filter worker to target, default 'any'
            ├── verbose-result:    Control output details, default 'False'
            └── nowait:    Do not wait for job to complete, default 'False'
nf#

Python API reference¤

Synchronize live VRFs, route targets, and interface assignments with NetBox.

VRFs have global scope and are identified by name. Descriptions are synchronized, while live import/export route targets extend the existing NetBox associations. Routing-policy references are added to the configured VRF custom fields when the BGP plugin is installed. Route distinguishers returned by the parser are not stored. The selected VRF custom field records devices on which each VRF was observed. Interfaces listed by the parser are assigned to their VRFs when they exist in NetBox.

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
device_custom_field str

VRF custom field containing associated devices.

'devices'
rpl_import_ipv4 str

VRF custom field for IPv4 import routing policies.

'rpl_import_ipv4'
rpl_import_ipv6 str

VRF custom field for IPv6 import routing policies.

'rpl_import_ipv6'
rpl_export_ipv4 str

VRF custom field for IPv4 export routing policies.

'rpl_export_ipv4'
rpl_export_ipv6 str

VRF custom field for IPv6 export routing policies.

'rpl_export_ipv6'
preserve_description Union[None, bool]

Description preservation policy. None preserves NetBox text when the live description is empty, True always preserves NetBox text, and False always uses live text.

None
interface_map Union[None, str, list]

Ordered interface rename rules, or an nf:// YAML file containing them.

None
**kwargs Any

Nornir FFun host filters.

{}

Returns:

Name Type Description
Result Result

VRF, route-target, routing-policy, and interface assignment actions.

Source code in norfab\workers\netbox_worker\vrf_tasks.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
@Task(
    fastapi={"methods": ["POST"], "schema": NetboxFastApiArgs.model_json_schema()},
    input=SyncVrfsInput,
    output=SyncVrfsResult,
    mcp={
        "annotations": {
            "title": "Sync VRFs",
            "readOnlyHint": False,
            "destructiveHint": True,
            "idempotentHint": True,
            "openWorldHint": True,
        }
    },
)
def sync_vrfs(
    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,
    device_custom_field: str = "devices",
    rpl_import_ipv4: str = "rpl_import_ipv4",
    rpl_import_ipv6: str = "rpl_import_ipv6",
    rpl_export_ipv4: str = "rpl_export_ipv4",
    rpl_export_ipv6: str = "rpl_export_ipv6",
    preserve_description: Union[None, bool] = None,
    interface_map: Union[None, str, list] = None,
    batch_size: int = 1000,
    **kwargs: Any,
) -> Result:
    """Synchronize live VRFs, route targets, and interface assignments with NetBox.

    VRFs have global scope and are identified by name. Descriptions are
    synchronized, while live import/export route targets extend the
    existing NetBox associations. Routing-policy references are added to
    the configured VRF custom fields when the BGP plugin is installed.
    Route distinguishers returned by the parser are not stored. The selected VRF custom field
    records devices on which each VRF was observed. Interfaces listed by
    the parser are assigned to their VRFs when they exist in NetBox.

    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.
        device_custom_field: VRF custom field containing associated devices.
        rpl_import_ipv4: VRF custom field for IPv4 import routing policies.
        rpl_import_ipv6: VRF custom field for IPv6 import routing policies.
        rpl_export_ipv4: VRF custom field for IPv4 export routing policies.
        rpl_export_ipv6: VRF custom field for IPv6 export routing policies.
        preserve_description: Description preservation policy. ``None`` preserves
            NetBox text when the live description is empty, ``True`` always
            preserves NetBox text, and ``False`` always uses live text.
        interface_map: Ordered interface rename rules, or an ``nf://`` YAML
            file containing them.
        **kwargs: Nornir FFun host filters.

    Returns:
        Result: VRF, route-target, routing-policy, and interface assignment actions.
    """
    # Normalize task inputs before resolving the selected NetBox devices.
    devices = list(devices or [])
    instance = instance or self.default_instance
    if self.is_url(interface_map):
        interface_map = TypeAdapter(list[InterfaceMapRule]).validate_python(
            yaml.safe_load(self.fetch_file(interface_map, raise_on_fail=True)) or []
        )
    interface_map = [
        rule.model_dump() if hasattr(rule, "model_dump") else dict(rule)
        for rule in interface_map or []
    ]
    ret = Result(
        task=f"{self.name}:sync_vrfs",
        result=SyncVrfsResultPayload().model_dump(),
        resources=[instance],
        dry_run=dry_run,
        diff={
            "vrfs": {},
            "route_targets": {},
            "routing_policies": {},
            "interfaces": {},
        },
    )

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

    if kwargs:
        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"Sync VRFs: {msg}")
        ret.errors.append(msg)
        ret.failed = True
        return ret

    nb_devices = {
        device.name: device
        for device in self.bulk_filter(
            nb.dcim.devices,
            name=devices,
            fields="id,name,device_type",
        )
    }
    for device_name in [name for name in devices if name not in nb_devices]:
        msg = f"device '{device_name}' not found in NetBox"
        job.event(msg, severity="ERROR")
        log.error(f"Sync VRFs: {msg}")
        ret.errors.append(msg)
    devices = [name for name in devices if name in nb_devices]
    if not devices:
        ret.failed = True
        return ret
    ret.result["interfaces"] = {
        device_name: SyncActionSummary().model_dump() for device_name in devices
    }

    if not nb.extras.custom_fields.get(name=device_custom_field):
        device_custom_field = None
    policy_fields = {
        ("ipv4", "import"): rpl_import_ipv4,
        ("ipv6", "import"): rpl_import_ipv6,
        ("ipv4", "export"): rpl_export_ipv4,
        ("ipv6", "export"): rpl_export_ipv6,
    }
    if self.has_plugin("netbox_bgp", instance):
        policy_fields = {
            key: name
            for key, name in policy_fields.items()
            if nb.extras.custom_fields.get(name=name)
        }
    else:
        policy_fields = {}
        msg = "netbox BGP plugin is not installed; skipping VRF routing policies"
        job.event(msg, severity="WARNING")
        log.warning(f"Sync VRFs: {msg}")

    # Collect per-device observations. Address-family route targets and
    # policies are flattened here for the global VRF reconciliation.
    msg = f"collecting live VRFs from {len(devices)} device(s)"
    job.event(msg)
    log.info(f"Sync VRFs: {msg}")
    parse_data = self.client.run_job(
        "nornir",
        "parse_ttp",
        kwargs={"get": "vrfs", "FL": devices},
        workers="all",
        timeout=timeout,
    )
    observations = {}
    result_devices = set()
    failed_devices = set()
    for worker_name, worker_data in parse_data.items():
        resources_failed = worker_data.get("resources_failed") or []
        if resources_failed:
            failed_devices.update(resources_failed)
            ret.resources_failed = sorted(
                set(ret.resources_failed) | set(resources_failed)
            )
            msg = (
                f"{worker_name} failed to fetch VRF data from devices "
                f"{', '.join(sorted(resources_failed))}"
            )
            job.event(msg, severity="ERROR")
            log.error(f"Sync VRFs: {msg}")
            ret.errors.append(msg)
        if worker_data["failed"]:
            msg = f"worker '{worker_name}' failed to collect live VRF data"
            job.event(msg, severity="ERROR")
            log.error(f"Sync VRFs: {msg}")
            ret.errors.append(msg)
            continue
        for device_name, records in worker_data["result"].items():
            if device_name not in nb_devices:
                continue
            result_devices.add(device_name)
            for record in records:
                if record.get("instance_type") and record["instance_type"] != "vrf":
                    continue
                address_families = record["address_families"]
                policies = {}
                for (family, direction), field_name in policy_fields.items():
                    policy = address_families[family][f"route_policy_{direction}"]
                    policies[field_name] = [policy] if policy else []
                observations.setdefault(record["name"], []).append(
                    {
                        "device": device_name,
                        "description": record["description"] or "",
                        "import_targets": [
                            target
                            for family in address_families.values()
                            for target in family["rt_import"]
                        ],
                        "export_targets": [
                            target
                            for family in address_families.values()
                            for target in family["rt_export"]
                        ],
                        "routing_policies": policies,
                        "interfaces": record["interfaces"],
                    }
                )

    for device_name in devices:
        if device_name not in result_devices and device_name not in failed_devices:
            msg = f"device '{device_name}' is missing a live VRF result"
            job.event(msg, severity="ERROR")
            log.error(f"Sync VRFs: {msg}")
            ret.errors.append(msg)
    if not result_devices:
        msg = "no usable live VRF data"
        job.event(msg, severity="ERROR")
        log.error(f"Sync VRFs: {msg}")
        ret.failed = True
        return ret

    # Build the global desired VRF state and a separate interface assignment
    # index. Sorting observations makes description precedence deterministic.
    live_vrfs = {}
    interface_targets = {}
    for vrf_name in sorted(observations):
        records = sorted(observations[vrf_name], key=lambda item: item["device"])
        live_vrfs[vrf_name] = {
            "description": next(
                (
                    record["description"]
                    for record in records
                    if record["description"]
                ),
                "",
            ),
            "import_targets": list(
                dict.fromkeys(
                    target
                    for record in records
                    for target in record["import_targets"]
                )
            ),
            "export_targets": list(
                dict.fromkeys(
                    target
                    for record in records
                    for target in record["export_targets"]
                )
            ),
        }
        if device_custom_field:
            live_vrfs[vrf_name][device_custom_field] = sorted(
                {nb_devices[record["device"]].id for record in records}
            )
        for field_name in policy_fields.values():
            live_vrfs[vrf_name][field_name] = list(
                dict.fromkeys(
                    policy
                    for record in records
                    for policy in record["routing_policies"][field_name]
                )
            )
        for record in records:
            device_name = record["device"]
            device_type = str(nb_devices[device_name].device_type.model)
            for live_name in record["interfaces"]:
                interface_name = map_interface_name(
                    live_name,
                    interface_map,
                    device_name,
                    device_type,
                )
                key = (device_name, interface_name)
                interface_targets[key] = vrf_name

    # Load only live VRF names. NetBox can return duplicate names, so retain
    # the lowest-ID record as the task's authoritative object and warn.
    netbox_vrfs = {}
    object_cache = {}
    vrf_names = list(live_vrfs)
    netbox_vrfs_records = (
        self.bulk_filter(
            nb.ipam.vrfs,
            name=vrf_names,
            fields="id,name,description,import_targets,export_targets,custom_fields",
        )
        if vrf_names
        else []
    )
    for vrf in netbox_vrfs_records:
        current = {
            "description": vrf.description,
            "import_targets": [target.name for target in vrf.import_targets],
            "export_targets": [target.name for target in vrf.export_targets],
        }
        live_vrfs[vrf.name]["description"] = apply_description_policy(
            live_vrfs[vrf.name]["description"],
            current["description"],
            preserve_description,
        )
        if device_custom_field:
            current[device_custom_field] = [
                device["id"]
                for device in (vrf.custom_fields[device_custom_field] or [])
            ]
            live_vrfs[vrf.name][device_custom_field] = sorted(
                set(current[device_custom_field])
                | set(live_vrfs[vrf.name][device_custom_field])
            )
        for field_name in policy_fields.values():
            current[field_name] = [
                policy.get("name") or policy["display"]
                for policy in (vrf.custom_fields[field_name] or [])
            ]
        existing_vrf = object_cache.get(("vrf", vrf.name))
        if existing_vrf:
            msg = (
                f"multiple NetBox VRFs matched "
                f"by name '{vrf.name}', using lowest ID from "
                f"{existing_vrf.id} and {vrf.id}"
            )
            job.event(msg, severity="WARNING")
            log.warning(f"Sync VRFs: {msg}")
        if existing_vrf is None or int(vrf.id) < int(existing_vrf.id):
            netbox_vrfs[vrf.name] = current
            object_cache[("vrf", vrf.name)] = vrf

    # Route-target and routing-policy updates are additive. Retain existing
    # NetBox associations and add values newly observed in live data.
    for vrf_name, current in netbox_vrfs.items():
        for field in (
            "import_targets",
            "export_targets",
            rpl_import_ipv4,
            rpl_import_ipv6,
            rpl_export_ipv4,
            rpl_export_ipv6,
        ):
            if field in current:
                live_vrfs[vrf_name][field] = sorted(
                    set(current[field]) | set(live_vrfs[vrf_name][field])
                )

    vrf_diff = self.make_diff(
        {"vrfs": live_vrfs},
        {"vrfs": netbox_vrfs},
    )["vrfs"]
    vrf_diff["delete"] = []

    create_names = vrf_diff["create"]
    update = vrf_diff["update"]
    in_sync = vrf_diff["in_sync"]

    # Resolve route targets referenced by actionable VRF changes. Missing
    # objects become part of the plan but are not created until after review.
    route_target_names = list(
        dict.fromkeys(
            target
            for vrf_name in [*create_names, *sorted(update)]
            for field in ("import_targets", "export_targets")
            for target in live_vrfs[vrf_name][field]
        )
    )
    if route_target_names:
        object_cache.update(
            {
                ("route_target", target.name): target
                for target in self.bulk_filter(
                    nb.ipam.route_targets,
                    name=route_target_names,
                    fields="id,name",
                )
            }
        )
    missing_route_targets = [
        name
        for name in route_target_names
        if ("route_target", name) not in object_cache
    ]
    route_target_diff = {
        "create": missing_route_targets,
        "update": {},
        "delete": [],
        "in_sync": [],
    }
    # Include missing BGP policy objects in the review plan; resolve IDs
    # only for policies referenced by VRFs that need creation or update.
    policy_names = list(
        dict.fromkeys(
            policy
            for vrf_name in [*create_names, *sorted(update)]
            for field_name in policy_fields.values()
            for policy in live_vrfs[vrf_name][field_name]
        )
    )
    if policy_names:
        object_cache.update(
            {
                ("routing_policy", policy.name): policy
                for policy in self.bulk_filter(
                    nb.plugins.bgp.routing_policy,
                    name=policy_names,
                    fields="id,name",
                )
            }
        )
    missing_policies = [
        name
        for name in policy_names
        if ("routing_policy", name) not in object_cache
    ]
    policy_diff = {
        "create": missing_policies,
        "update": {},
        "delete": [],
        "in_sync": [],
    }

    # Fetch the cross-product of referenced devices and names in one request,
    # then retain exact (device, interface) matches for assignment comparison.
    interface_objects = {}
    if interface_targets:
        interface_records = self.bulk_filter(
            nb.dcim.interfaces,
            device_id=sorted(
                {nb_devices[device].id for device, _ in interface_targets}
            ),
            name=sorted({name for _, name in interface_targets}),
            fields="id,name,device,vrf",
        )
        interface_objects = {
            (str(interface.device.name), str(interface.name)): interface
            for interface in interface_records
            if (str(interface.device.name), str(interface.name))
            in interface_targets
        }

    for device_name, interface_name in sorted(
        interface_targets.keys() - interface_objects.keys()
    ):
        msg = f"interface '{device_name}:{interface_name}' not found in NetBox"
        job.event(msg, severity="ERROR")
        log.error(f"Sync VRFs: {msg}")
        ret.errors.append(msg)

    interface_live = {}
    interface_current = {}
    for key in sorted(interface_targets.keys() & interface_objects.keys()):
        device_name, interface_name = key
        interface = interface_objects[key]
        interface_live.setdefault(device_name, {})[interface_name] = {
            "vrf": interface_targets[key]
        }
        interface_current.setdefault(device_name, {})[interface_name] = {
            "vrf": str(interface.vrf.name) if interface.vrf else None
        }

    # Interface identity is scoped by device. A different current VRF becomes
    # a normal update, while an equal assignment is reported as in sync.
    interface_diff = self.make_diff(interface_live, interface_current)
    ret.result["vrfs"]["in_sync"] = in_sync
    for device_name, actions in interface_diff.items():
        ret.result["interfaces"][device_name]["in_sync"] = actions["in_sync"]
    full_diff = {
        "vrfs": vrf_diff,
        "route_targets": route_target_diff,
        "routing_policies": policy_diff,
        "interfaces": interface_diff,
    }
    msg = (
        "vrf sync diff complete: "
        f"{len(create_names)} create, {len(update)} update, "
        f"{len(in_sync)} in sync"
    )
    job.event(msg)
    log.info(f"Sync VRFs: {msg}")

    ret.diff = full_diff
    if dry_run:
        ret.result = full_diff
        ret.dry_run = True
        return ret
    if not sync_diff_has_changes(full_diff):
        msg = "no VRF sync changes required"
        job.event(msg)
        log.info(f"Sync VRFs: {msg}")
        return ret
    if with_approval and not review_sync_task_result(job, "VRF sync", full_diff):
        ret.status = "skipped"
        ret.result = full_diff
        ret.dry_run = True
        ret.messages.append("review declined; changes were not applied")
        msg = "vrf sync approval declined"
        job.event(msg)
        log.info(f"Sync VRFs: {msg}")
        return ret

    # Apply global VRF changes first so every desired VRF ID is cached before
    # building the dependent interface assignment updates.
    if missing_route_targets:
        target_payloads = [{"name": name} for name in missing_route_targets]
        total_batches = (len(target_payloads) + batch_size - 1) // batch_size
        for batch_start in range(0, len(target_payloads), batch_size):
            batch = target_payloads[batch_start : batch_start + batch_size]
            batch_number = batch_start // batch_size + 1
            msg = f"creating route target batch {batch_number}/{total_batches} ({len(batch)} target(s))"
            job.event(msg)
            log.info(msg)
            try:
                created_targets = nb.ipam.route_targets.create(batch)
            except Exception as exc:
                msg = f"failed to create route target batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                return ret
            for target in created_targets:
                object_cache[("route_target", target.name)] = target
                ret.result["route_targets"]["created"].append(target.name)
    if missing_policies:
        policy_payloads = [{"name": name} for name in missing_policies]
        total_batches = (len(policy_payloads) + batch_size - 1) // batch_size
        for batch_start in range(0, len(policy_payloads), batch_size):
            batch = policy_payloads[batch_start : batch_start + batch_size]
            batch_number = batch_start // batch_size + 1
            msg = f"creating routing policy batch {batch_number}/{total_batches} ({len(batch)} policy(s))"
            job.event(msg)
            log.info(msg)
            try:
                created_policies = nb.plugins.bgp.routing_policy.create(batch)
            except Exception as exc:
                msg = f"failed to create routing policy batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                return ret
            for policy in created_policies:
                object_cache[("routing_policy", policy.name)] = policy
                ret.result["routing_policies"]["created"].append(policy.name)

    create_payloads = []
    for vrf_name in create_names:
        desired = live_vrfs[vrf_name]
        payload = {
            "name": vrf_name,
            "description": desired["description"],
            "import_targets": [
                object_cache[("route_target", name)].id
                for name in desired["import_targets"]
            ],
            "export_targets": [
                object_cache[("route_target", name)].id
                for name in desired["export_targets"]
            ],
        }
        custom_fields = {}
        if device_custom_field:
            custom_fields[device_custom_field] = desired[device_custom_field]
        for field_name in policy_fields.values():
            custom_fields[field_name] = [
                object_cache[("routing_policy", name)].id
                for name in desired[field_name]
            ]
        if custom_fields:
            payload["custom_fields"] = custom_fields
        create_payloads.append(payload)
    if create_payloads:
        total_batches = (len(create_payloads) + batch_size - 1) // batch_size
        for batch_start in range(0, len(create_payloads), batch_size):
            batch = create_payloads[batch_start : batch_start + batch_size]
            batch_number = batch_start // batch_size + 1
            msg = f"creating VRF batch {batch_number}/{total_batches} ({len(batch)} VRF(s))"
            job.event(msg)
            log.info(msg)
            try:
                created_vrfs = nb.ipam.vrfs.create(batch)
            except Exception as exc:
                msg = f"failed to create VRF batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                return ret
            for vrf in created_vrfs:
                object_cache[("vrf", vrf.name)] = vrf
                ret.result["vrfs"]["created"].append(vrf.name)

    update_payloads = []
    for vrf_name in sorted(update):
        desired = live_vrfs[vrf_name]
        payload = {"id": object_cache[("vrf", vrf_name)].id}
        for field in update[vrf_name]:
            if field == "description":
                payload[field] = desired[field]
            elif field in ("import_targets", "export_targets"):
                payload[field] = [
                    object_cache[("route_target", name)].id
                    for name in desired[field]
                ]
            elif field == device_custom_field:
                payload.setdefault("custom_fields", {})[field] = desired[field]
            elif field in policy_fields.values():
                payload.setdefault("custom_fields", {})[field] = [
                    object_cache[("routing_policy", name)].id
                    for name in desired[field]
                ]
        update_payloads.append((vrf_name, payload))
    if update_payloads:
        total_batches = (len(update_payloads) + batch_size - 1) // batch_size
        for batch_start in range(0, len(update_payloads), batch_size):
            batch = update_payloads[batch_start : batch_start + batch_size]
            batch_number = batch_start // batch_size + 1
            msg = f"updating VRF batch {batch_number}/{total_batches} ({len(batch)} VRF(s))"
            job.event(msg)
            log.info(msg)
            try:
                nb.ipam.vrfs.update([payload for _, payload in batch])
            except Exception as exc:
                msg = f"failed to update VRF batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                return ret
            ret.result["vrfs"]["updated"].extend(name for name, _ in batch)

    # Assign only interfaces classified as updates; matching assignments have
    # already been retained in the result's in_sync lists.
    interface_payloads = []
    for device_name, actions in sorted(interface_diff.items()):
        for interface_name in sorted(actions["update"]):
            vrf_name = interface_live[device_name][interface_name]["vrf"]
            interface_payloads.append(
                (
                    (device_name, interface_name),
                    {
                        "id": interface_objects[(device_name, interface_name)].id,
                        "vrf": object_cache[("vrf", vrf_name)].id,
                    },
                )
            )
    if interface_payloads:
        total_batches = (len(interface_payloads) + batch_size - 1) // batch_size
        for batch_start in range(0, len(interface_payloads), batch_size):
            batch = interface_payloads[batch_start : batch_start + batch_size]
            batch_number = batch_start // batch_size + 1
            msg = f"updating VRF interface batch {batch_number}/{total_batches} ({len(batch)} interface(s))"
            job.event(msg)
            log.info(msg)
            try:
                nb.dcim.interfaces.update([payload for _, payload in batch])
            except Exception as exc:
                msg = f"failed to update VRF interface batch {batch_number}/{total_batches}: {exc}"
                job.event(msg, severity="ERROR")
                log.error(msg)
                ret.errors.append(msg)
                ret.failed = True
                return ret
            for (device_name, interface_name), _ in batch:
                ret.result["interfaces"][device_name]["updated"].append(
                    interface_name
                )
    msg = (
        "vrf sync complete: "
        f"{len(create_names)} VRF created, {len(update)} updated, "
        f"{len(in_sync)} in sync"
    )
    job.event(msg)
    log.info(f"Sync VRFs: {msg}")
    return ret