Skip to content

Netbox Create IP Task¤

task api name: create_ip

Allocates the next available IP address from a parent prefix, or reuses an existing matching IP address. The task can assign the IP to a device interface, update metadata, set the address as primary, and optionally create an address for the connected peer interface.

Set ip_index to select a usable address by its one-based position in the subnet. For example, index 1 selects .1 in an IPv4 /30, while indexes 1 and 2 select both addresses of a /31. An index beyond the usable addresses fails. Existing group or interface assignments are reused before allocating a child subnet. Dry runs with mask_len still preview an address from the parent prefix.

An existing assignment to the requested interface is reused first. If none is found, ip_index selects a specific usable address; without it, the task allocates the next available address. The requested role, including anycast or vip, is set on the allocated IP. If an indexed address already exists, the task can create another record for anycast or vip after setting the existing record's role. An existing indexed address with another requested role causes an error.

The task can also be called from Nornir templates through the netbox.create_ip Jinja2 filter.

Interface reuse searches by device, interface, and parent prefix. A supplied description prefers an exact match; if none matches, the sole candidate is reused and its description is updated. Multiple remaining candidates cause an ambiguity error. This applies to ordinary, anycast, and VIP addresses, before indexed allocation. Description-only and VRRP-group lookups retain their description matching behavior.

VRRP virtual IP allocation¤

Supply vrrp_group with an existing, uniquely named VRRPv2 or VRRPv3 group. The task assigns the address to that group and defaults its role to vrrp. Repeated calls reuse the group's address within the selected prefix, optionally matching description. Missing, ambiguous, or non-VRRP groups fail before allocation.

create_ip:
  prefix:
    site: LAB
    role: MGMT
  vrrp_group: LAB-mgmt

Group allocation cannot accompany device, interface, or is_primary: true. ip_index selects the initial group address; later calls reuse the group's IP. It disables peer allocation. Dry runs resolve the group without writing; the existing dry-run limitation for mask_len still applies. Results include vrrp_group when supplied. Omitting it preserves existing task behavior.

Output¤

Returns the allocated or updated IP address data. When create_peer_ip=True, peer allocation details may be included in the result.

{
    "address": "10.0.0.1/31",
    "device": "ceos-leaf-1",
    "interface": "Ethernet1",
    "description": "leaf-1 to spine-1",
    "...": "...",
}

Notes / Gotchas¤

  • prefix can be a network string, a prefix description, or a dictionary of pynetbox prefix filters.
  • When mask_len differs from the parent prefix length, the task creates or reuses a child prefix through create_prefix.
  • If no child subnet can be selected, the task returns an error that includes any failed availability checks.
  • In dry-run mode, mask_len is ignored and the candidate IP is allocated directly from the parent prefix.
  • IPv4 /32 and IPv6 /128 allocations automatically disable peer creation and peer-subnet reuse, including when the supplied parent is itself a host prefix.
  • If peer allocation fails, the task returns the peer error in errors; the local IP may already be allocated.
  • ip_index is one-based over usable IPs; /31 and /127 include both endpoints.
  • Object and multiobject custom fields accept related object names or IDs. The task resolves names using each field's NetBox definition, adds new list values on repeated calls, and replaces scalar or null values. Missing or ambiguous names fail.
  • Branch writes require the NetBox Branching Plugin.

Examples¤

Allocate an IP for an interface:

nf#netbox create ip prefix 10.0.0.0/24 device ceos-leaf-1 interface Ethernet1 description "leaf-1 uplink"

Allocate a /31 link subnet and create the peer IP:

nf#netbox create ip prefix 10.0.0.0/24 device ceos-leaf-1 interface Ethernet1 mask-len 31 create-peer-ip

Set DNS name and mark the address as primary:

nf#netbox create ip prefix loopbacks device ceos-leaf-1 interface Loopback0 dns-name ceos-leaf-1.example.net is-primary

Preview allocation without writing:

nf#netbox create ip prefix 10.0.0.0/24 device ceos-leaf-1 interface Ethernet1 dry-run
from norfab.core.nfapi import NorFab

nf = NorFab(inventory="./inventory.yaml")
nf.start()
client = nf.make_client()

# allocate an IP for an interface
result = client.run_job(
    "netbox",
    "create_ip",
    workers="any",
    kwargs={
        "prefix": "10.0.0.0/24",
        "device": "ceos-leaf-1",
        "interface": "Ethernet1",
        "description": "leaf-1 uplink",
    },
)

# allocate a /31 link subnet and peer IP
result = client.run_job(
    "netbox",
    "create_ip",
    workers="any",
    kwargs={
        "prefix": {"prefix": "10.0.0.0/24", "site": "lab"},
        "device": "ceos-leaf-1",
        "interface": "Ethernet1",
        "mask_len": 31,
        "create_peer_ip": True,
    },
)

nf.destroy()

NORFAB Netbox Create IP Command Shell Reference¤

NorFab shell supports these command options for Netbox create_ip task:

nf# man tree netbox.create.ip
root
└── netbox:    Netbox service
    └── create:    Create objects in Netbox
        └── ip:    Allocate next available IP address from prefix
            ├── timeout:    Job timeout
            ├── workers:    Filter worker to target, default 'any'
            ├── verbose-result:    Control output details, default 'False'
            ├── progress:    Display progress events, default 'True'
            ├── instance:    Netbox instance name to target
            ├── dry-run:    Do not commit to database
            ├── prefix:    Prefix to allocate IP address from, can also provide prefix name or filters
            ├── device:    Device name to associate IP address with
            ├── interface:    Device interface name to associate IP address with
            ├── description:    IP address description
            ├── vrf:    VRF to associate with IP address
            ├── tags:    Tags to add to IP address
            ├── dns-name:    IP address DNS name
            ├── tenant:    Tenant name to associate with IP address
            ├── comments:    IP address comments field
            ├── role:    IP address functional role
            ├── status:    IP address status
            ├── is-primary:    Set the IP address as the primary IP for the device
            ├── mask-len:    Mask length to use for IP address
            ├── create-peer-ip:    Create link peer IP address as well
            └── branch:    Branching plugin branch name to use
nf#

Python API Reference¤

Allocate the next available or indexed usable IP address from a subnet.

.. warning::

**Dry-run limitation**: when ``dry_run=True``, ``mask_len`` is ignored and
the candidate IP address is allocated directly from the parent prefix using
the parent prefix mask length — no child subnet is created.

This task finds or creates an IP address in NetBox, updates its metadata, optionally links it to a device/interface, and supports a dry run mode for previewing changes. Existing group or interface assignments are reused before ip_index selects an address for a new allocation. An indexed address already in NetBox can be duplicated for anycast or VIP roles.

Parameters:

Name Type Description Default
prefix str

The prefix from which to allocate the IP address, could be:

  • IPv4 prefix string e.g. 10.0.0.0/24
  • IPv6 prefix string e.g. 2001::/64
  • Prefix description string to filter by
  • Dictionary with prefix filters to feed pynetbox filter method e.g. {"prefix": "10.0.0.0/24", "site": "foo", "role": "bar"}, site accepts a site name and role accepts a role name resolved to role_id. An unknown role name raises NetboxAllocationError.
required
custom_fields dict

Custom-field names and values to PATCH on the allocated IP. Object and multiobject fields accept related object names or IDs. List values add to existing values; scalar values and null replace them. Definitions must exist in NetBox.

None
description str

A description for the allocated IP address. For device/interface reuse, prefers an exact description match; otherwise reuses the sole address within the selected prefix and updates its description. Multiple remaining candidates raise NetboxAllocationError instead of allocating another address.

None
device str

The device associated with the IP address.

None
interface str

The interface associated with the IP address.

None
is_primary bool

If True, set the allocated IPv4 or IPv6 address as the device's primary IP, including when already assigned.

None
vrrp_group str

Existing VRRP group name to assign the IP to. Must uniquely identify a VRRPv2 or VRRPv3 group. Reuses an IP assigned to that group within the selected prefix, optionally matching description. Cannot accompany device, interface, or is_primary=True. Disables peer allocation and defaults role to vrrp. Missing or ambiguous groups raise NetboxAllocationError before allocation. Returned when supplied.

None
vrf str

The VRF (Virtual Routing and Forwarding) instance.

None
tags list

A list of tags to associate with the IP address.

None
dns_name str

The DNS name for the IP address.

None
tenant str

The tenant associated with the IP address.

None
comments str

Additional comments for the IP address.

None
status str

Status for the IP address, such as active, reserved, or deprecated. Updates an existing IP when different.

None
instance str

The NetBox instance to use.

None
dry_run bool

If True, do not actually allocate the IP address.

False
branch str

Branch name to use, need to have branching plugin installed, automatically creates branch if it does not exist in Netbox.

None
mask_len int

mask length to use for IP address on creation or to update existing IP address. On new IP address creation will create child subnet of mask_len within parent prefix, new subnet not created for existing IP addresses. Ignored when dry_run=True.

None
ip_index int

One-based position among usable IPs in the selected subnet. On a /31 or /127, both addresses are usable. Out-of-range positions raise NetboxAllocationError. When mask_len creates a child subnet, dry runs use the parent subnet because they do not create child subnets.

None
create_peer_ip bool

If True creates IP address for link peer - remote device interface connected to requested device and interface. Disabled for IPv4 /32 and IPv6 /128 allocations, which have no room for a peer. Host allocations also skip peer-subnet reuse. Peer allocation errors are returned while the local IP remains allocated.

True

Returns:

Name Type Description
Result Result

Allocation details. If no child subnet can be selected, the result is marked failed and includes any subnet probe errors.

Tasks execution follow these steps:

  1. Tries to find an existing IP in NetBox within the selected prefix. For device/interface assignments, prefers a matching description or reuses the sole candidate, including anycast and VIP addresses. Ambiguous candidates fail; no candidates proceeds to allocation.

  2. If prefix is a string, determines if it's an IP network or a description. Builds a filter dictionary for NetBox queries, optionally including VRF.

  3. Queries NetBox for the prefix using the constructed filter.

  4. If dry_run is True, fetches the next available IP but doesn't create it.

  5. If not a dry run, creates the next available IP in the prefix.

  6. Updates IP attributes (description, VRF, tenant, DNS name, comments, role, tags) if provided and different from current values. Handles interface assignment and can set the IP as primary for the device.

  7. If changes were made and not a dry run, saves the IP and device updates to NetBox.

Source code in norfab\workers\netbox_worker\ip_tasks.py
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
@Task(
    fastapi={"methods": ["POST"], "schema": NetboxFastApiArgs.model_json_schema()},
    input=CreateIpInput,
    output=CreateIpResult,
    mcp={
        "annotations": {
            "title": "Create IP Address",
            "readOnlyHint": False,
            "destructiveHint": False,
            "idempotentHint": False,
            "openWorldHint": True,
        }
    },
)
def create_ip(
    self,
    job: Job,
    prefix: Union[str, dict],
    device: Union[None, str] = None,
    interface: Union[None, str] = None,
    description: Union[None, str] = None,
    vrf: Union[None, str] = None,
    tags: Union[None, list] = None,
    dns_name: Union[None, str] = None,
    tenant: Union[None, str] = None,
    comments: Union[None, str] = None,
    role: Union[None, str] = None,
    status: Union[None, str] = None,
    is_primary: Union[None, bool] = None,
    instance: Union[None, str] = None,
    dry_run: Union[None, bool] = False,
    branch: Union[None, str] = None,
    mask_len: Union[None, int] = None,
    ip_index: Union[None, int] = None,
    create_peer_ip: Union[None, bool] = True,
    custom_fields: Union[None, dict] = None,
    vrrp_group: Union[None, str] = None,
) -> Result:
    """
    Allocate the next available or indexed usable IP address from a subnet.

    .. warning::

        **Dry-run limitation**: when ``dry_run=True``, ``mask_len`` is ignored and
        the candidate IP address is allocated directly from the parent prefix using
        the parent prefix mask length — no child subnet is created.

    This task finds or creates an IP address in NetBox, updates its metadata,
    optionally links it to a device/interface, and supports a dry run mode for
    previewing changes. Existing group or interface assignments are reused
    before ``ip_index`` selects an address for a new allocation. An indexed
    address already in NetBox can be duplicated for anycast or VIP roles.

    Args:
        prefix (str): The prefix from which to allocate the IP address, could be:

            - IPv4 prefix string e.g. 10.0.0.0/24
            - IPv6 prefix string e.g. 2001::/64
            - Prefix description string to filter by
            - Dictionary with prefix filters to feed `pynetbox` filter method
                e.g. `{"prefix": "10.0.0.0/24", "site": "foo", "role": "bar"}`,
                `site` accepts a site name and `role` accepts a role name
                resolved to `role_id`. An unknown role name raises
                `NetboxAllocationError`.

        custom_fields (dict, optional): Custom-field names and values to PATCH
            on the allocated IP. Object and multiobject fields accept related
            object names or IDs. List values add to existing values; scalar
            values and null replace them. Definitions must exist in NetBox.
        description (str, optional): A description for the allocated IP address.
            For device/interface reuse, prefers an exact description match;
            otherwise reuses the sole address within the selected prefix and
            updates its description. Multiple remaining candidates raise
            NetboxAllocationError instead of allocating another address.
        device (str, optional): The device associated with the IP address.
        interface (str, optional): The interface associated with the IP address.
        is_primary (bool, optional): If True, set the allocated IPv4 or IPv6
            address as the device's primary IP, including when already assigned.
        vrrp_group (str, optional): Existing VRRP group name to assign the IP to.
            Must uniquely identify a VRRPv2 or VRRPv3 group. Reuses an IP assigned
            to that group within the selected prefix, optionally matching description.
            Cannot accompany device, interface, or is_primary=True. Disables peer
            allocation and defaults role to vrrp. Missing or ambiguous groups raise
            NetboxAllocationError before allocation. Returned when supplied.
        vrf (str, optional): The VRF (Virtual Routing and Forwarding) instance.
        tags (list, optional): A list of tags to associate with the IP address.
        dns_name (str, optional): The DNS name for the IP address.
        tenant (str, optional): The tenant associated with the IP address.
        comments (str, optional): Additional comments for the IP address.
        status (str, optional): Status for the IP address, such as active,
            reserved, or deprecated. Updates an existing IP when different.
        instance (str, optional): The NetBox instance to use.
        dry_run (bool, optional): If True, do not actually allocate the IP address.
        branch (str, optional): Branch name to use, need to have branching plugin
            installed, automatically creates branch if it does not exist in Netbox.
        mask_len (int, optional): mask length to use for IP address on creation or to
            update existing IP address. On new IP address creation will create child
            subnet of `mask_len` within parent `prefix`, new subnet not created for
            existing IP addresses. Ignored when ``dry_run=True``.
        ip_index (int, optional): One-based position among usable IPs in the
            selected subnet. On a /31 or /127, both addresses are usable.
            Out-of-range positions raise ``NetboxAllocationError``. When
            ``mask_len`` creates a child subnet, dry runs use the parent
            subnet because they do not create child subnets.
        create_peer_ip (bool, optional): If True creates IP address for link peer -
            remote device interface connected to requested device and interface.
            Disabled for IPv4 /32 and IPv6 /128 allocations, which have no
            room for a peer. Host allocations also skip peer-subnet reuse.
            Peer allocation errors are returned while the local IP remains allocated.

    Returns:
        Result: Allocation details. If no child subnet can be selected, the
            result is marked failed and includes any subnet probe errors.

    Tasks execution follow these steps:

    1. Tries to find an existing IP in NetBox within the selected prefix.
        For device/interface assignments, prefers a matching description or
        reuses the sole candidate, including anycast and VIP addresses.
        Ambiguous candidates fail; no candidates proceeds to allocation.

    2. If prefix is a string, determines if it's an IP network or a description.
        Builds a filter dictionary for NetBox queries, optionally including VRF.

    3. Queries NetBox for the prefix using the constructed filter.

    4. If dry_run is True, fetches the next available IP but doesn't create it.

    5. If not a dry run, creates the next available IP in the prefix.

    6. Updates IP attributes (description, VRF, tenant, DNS name, comments, role, tags)
        if provided and different from current values. Handles interface assignment and
        can set the IP as primary for the device.

    7. If changes were made and not a dry run, saves the IP and device updates to NetBox.
    """
    instance = instance or self.default_instance
    log.info(
        f"{self.name} - Create IP: Allocating IP from '{prefix}' for '{device}:{interface}' in '{instance}' Netbox"
    )
    ret = Result(task=f"{self.name}:create_ip", result={}, resources=[instance])
    tags = tags or []
    has_changes = False
    nb_ip = None
    nb_device = None
    create_peer_ip_data = {}
    nb = self._get_pynetbox(instance, branch=branch, job=job)
    job.event(
        f"creating IP address in '{instance}' for "
        f"'{device}:{interface}' from prefix '{prefix}', dry_run={dry_run}"
    )

    nb_vrrp_group = None
    if vrrp_group is not None:
        try:
            nb_vrrp_group = nb.ipam.fhrp_groups.get(name=vrrp_group)
            if not nb_vrrp_group or nb_vrrp_group.protocol not in (
                "vrrp2",
                "vrrp3",
            ):
                raise ValueError("expected an existing VRRPv2 or VRRPv3 group")
        except Exception as exc:
            raise NetboxAllocationError(
                f"Unable to resolve VRRP group '{vrrp_group}': {exc}"
            ) from exc
        create_peer_ip = False
        role = role or "vrrp"

    # source parent prefix from Netbox
    if isinstance(prefix, str):
        # try converting prefix to network, if fails prefix is not an IP network
        try:
            _ = ipaddress.ip_network(prefix)
            is_network = True
        except Exception:
            is_network = False
        if is_network is True and vrf:
            prefix = {"prefix": prefix, "vrf__name": vrf}
        elif is_network is True:
            prefix = {"prefix": prefix}
        elif is_network is False and vrf:
            prefix = {"description": prefix, "vrf__name": vrf}
        elif is_network is False:
            prefix = {"description": prefix}
    elif isinstance(prefix, dict):
        prefix = dict(prefix)
        prefix_site = prefix.pop("site", None)
        if prefix_site:
            nb_site = nb.dcim.sites.get(name=prefix_site)
            if not nb_site:
                raise NetboxAllocationError(
                    f"Failed to get parent prefix site '{prefix_site}' from NetBox"
                )
            prefix.update(scope_type="dcim.site", scope_id=nb_site.id)
        # NetBox's prefix filter accepts role slugs or role_id, not role names.
        # Resolve the task's role-name input to an ID before filtering prefixes.
        prefix_role = prefix.pop("role", None)
        if prefix_role is not None:
            nb_role = nb.ipam.roles.get(name=prefix_role)
            if not nb_role:
                raise NetboxAllocationError(
                    f"Failed to get parent prefix role '{prefix_role}' from NetBox"
                )
            prefix["role_id"] = nb_role.id
    nb_prefixes = self.bulk_filter(nb.ipam.prefixes, **prefix)
    if not nb_prefixes:
        raise NetboxAllocationError(
            f"Unable to source parent prefix from Netbox - {prefix}"
        )
    # try to source existing IP from netbox
    for nb_prefix in nb_prefixes:
        if nb_vrrp_group is not None:
            filters = {
                "assigned_object_type": "ipam.fhrpgroup",
                "assigned_object_id": nb_vrrp_group.id,
                "parent": str(nb_prefix),
            }
            if description:
                filters["description"] = description
            nb_ip = nb.ipam.ip_addresses.get(**filters)
        elif device and interface:
            candidates = list(
                nb.ipam.ip_addresses.filter(
                    device=device, interface=interface, parent=str(nb_prefix)
                )
            )
            if description:
                matching = [
                    ip for ip in candidates if ip.description == description
                ]
                if matching:
                    candidates = matching
            if len(candidates) > 1:
                raise NetboxAllocationError(
                    f"Multiple IP addresses match '{device}:{interface}' "
                    f"within prefix '{nb_prefix}' with description preference '{description}'"
                )
            nb_ip = candidates[0] if candidates else None
        elif description:
            nb_ip = nb.ipam.ip_addresses.get(
                description=description, parent=str(nb_prefix)
            )
        if nb_ip:
            break
    # if no existing IP found, find parent prefix that has available subnets to allocate
    else:
        allocation_errors = []
        for nb_prefix in nb_prefixes:
            parent_prefix_len = int(str(nb_prefix).split("/")[1])
            if ip_index is not None:
                break
            # check if can create child subnet in prefix
            elif mask_len and mask_len != parent_prefix_len:
                try:
                    candidate = self.create_prefix(
                        job=job,
                        parent=str(nb_prefix),
                        prefixlen=mask_len,
                        instance=instance,
                        branch=branch,
                        dry_run=True,
                    )
                    if candidate.failed is False and candidate.result.get("prefix"):
                        break
                except Exception as exc:
                    msg = f"error checking available /{mask_len} subnet in '{nb_prefix}' - {exc}"
                    log.error(msg)
                    allocation_errors.append(msg)
                    continue
            elif nb_prefix.available_ips.list():
                break
        else:
            ret.errors.extend(allocation_errors)
            ret.errors.append(
                f"No subnets of {mask_len} length or IPs available in parent prefix - {prefix}"
            )
            ret.failed = True
            return ret

    # create new IP address
    if not nb_ip:
        parent_prefix_len = ipaddress.ip_network(str(nb_prefix)).prefixlen
        # A host prefix has only one address, regardless of peer settings.
        allocation_prefix = ipaddress.ip_network(str(nb_prefix))
        host_allocation = (
            mask_len if mask_len is not None else allocation_prefix.prefixlen
        ) == allocation_prefix.max_prefixlen
        if host_allocation:
            create_peer_ip = False
        # check if interface has link peer that has IP within parent prefix
        if device and interface and not host_allocation and ip_index is None:
            connection = self.get_connections(
                job=job,
                devices=[device],
                interfaces=[interface],
                instance=instance,
                branch=branch,
            )
            if interface in connection.result[device]:
                peer = connection.result[device][interface]
                # do not process breakout cables
                if isinstance(peer["remote_interface"], list):
                    peer["remote_interface"] = None
                # try to source peer ip subnet
                nb_peer_ip = None
                if peer["remote_device"] and peer["remote_interface"]:
                    nb_peer_ip = nb.ipam.ip_addresses.get(
                        device=peer["remote_device"],
                        interface=peer["remote_interface"],
                        parent=str(nb_prefix),
                    )
                # try to source peer ip subnet
                nb_peer_prefix = None
                if nb_peer_ip:
                    peer_ip = ipaddress.ip_interface(nb_peer_ip.address)
                    nb_peer_prefix = nb.ipam.prefixes.get(
                        prefix=str(peer_ip.network),
                        vrf__name=vrf,
                    )
                elif create_peer_ip and peer["remote_interface"]:
                    create_peer_ip_data = {
                        "device": peer["remote_device"],
                        "interface": peer["remote_interface"],
                        "vrf": vrf,
                        "branch": branch,
                        "tenant": tenant,
                        "dry_run": dry_run,
                        "tags": tags,
                        "status": status,
                        "create_peer_ip": False,
                        "instance": instance,
                        "mask_len": mask_len,
                    }
                # use peer subnet to create IP address
                if nb_peer_prefix:
                    nb_prefix = nb_peer_prefix
                    mask_len = None  # cancel subnet creation
                    job.event(
                        f"using link peer '{peer['remote_device']}:{peer['remote_interface']}' "
                        f"prefix '{nb_peer_prefix}' to create IP address"
                    )
        # if mask_len provided create new subnet
        if mask_len and not dry_run and mask_len != parent_prefix_len:
            if mask_len < parent_prefix_len:
                raise ValueError(
                    f"Mask length '{mask_len}' must be longer then '{parent_prefix_len}' prefix length"
                )
            prefix_status = status
            if prefix_status not in ["active", "reserved", "deprecated"]:
                prefix_status = None
            # find next available subnet with available IPs
            while not job.is_timed_out():
                child_subnet = self.create_prefix(
                    job=job,
                    parent=str(nb_prefix),
                    prefixlen=mask_len,
                    vrf=vrf,
                    tags=tags,
                    tenant=tenant,
                    status=prefix_status,
                    instance=instance,
                    branch=branch,
                )
                if child_subnet.failed is True:
                    raise NetboxAllocationError(
                        f"Unable to create child subnet of mask length "
                        f"'{mask_len}' inside '{prefix}' parent prefix"
                    )

                child_prefix = {"prefix": child_subnet.result["prefix"]}
                if vrf:
                    child_prefix["vrf__name"] = vrf
                nb_child_prefix = nb.ipam.prefixes.get(**child_prefix)

                if not nb_child_prefix:
                    raise NetboxAllocationError(
                        f"Unable to source child prefix of mask length "
                        f"'{mask_len}' from '{child_prefix}' parent prefix"
                    )

                # check how many IPs available in child prefix
                available_ip_count = len(nb_child_prefix.available_ips.list())
                if not available_ip_count:
                    msg = f"{nb_child_prefix} - created child prefix but it has no available IPs, continue"
                    log.info(msg)
                    job.event(msg)
                elif create_peer_ip and available_ip_count < 2:
                    msg = f"{nb_child_prefix} - created child prefix but it has less than 2 available IPs, create peer ip is True, need two IPs, continue"
                    log.info(msg)
                    job.event(msg)
                else:
                    nb_prefix = nb_child_prefix
                    break
            else:
                raise NetboxAllocationError(
                    f"Unable to find a child subnet of mask length '{mask_len}' "
                    f"with sufficient available IPs inside '{nb_prefix}', vrf '{vrf}'"
                )
        if ip_index is not None:
            network = ipaddress.ip_network(str(nb_prefix))
            # hosts() includes both /31 endpoints and excludes IPv4 broadcasts.
            selected_ip = next(
                islice(network.hosts(), ip_index - 1, ip_index), None
            )
            if selected_ip is None:
                raise NetboxAllocationError(
                    f"ip_index {ip_index} exceeds the usable IPs in {network}"
                )
            address = f"{selected_ip}/{network.prefixlen}"
            existing_ip = None
            for ip in nb.ipam.ip_addresses.filter(address=address):
                if getattr(ip.vrf, "name", None) == vrf:
                    existing_ip = ip
                    break
            if existing_ip and role not in ("anycast", "vip"):
                raise NetboxAllocationError(
                    f"cannot create IP address {address}: it already exists"
                )
            if dry_run:
                preview_address = address
            else:
                if existing_ip and existing_ip.role != role:
                    # NetBox requires the existing record to have a shared role.
                    existing_ip.update({"role": role})
                nb_ip = nb.ipam.ip_addresses.create(address=address, role=role)
        else:
            if dry_run:
                preview_address = str(nb_prefix.available_ips.list()[0])
            else:
                nb_ip = nb_prefix.available_ips.create()

        if dry_run:
            ret.status = "unchanged"
            ret.dry_run = True
            ret.result = {
                "address": preview_address,
                "description": description,
                "vrf": vrf,
                "device": device,
                "interface": interface,
            }
            if vrrp_group is not None:
                ret.result["vrrp_group"] = vrrp_group
            # add branch to results
            if branch is not None:
                ret.result["branch"] = branch
            job.event(f"dry-run: would create IP address '{preview_address}'")
            return ret
        job.event(
            f"created '{nb_ip}' IP address for '{device}:{interface}' within '{nb_prefix}' prefix"
        )
        ret.status = "created"
    else:
        job.event(f"using existing IP address {nb_ip}")
        ret.status = "updated"

    # update IP address parameters
    if nb_vrrp_group is not None and (
        nb_ip.assigned_object_type != "ipam.fhrpgroup"
        or nb_ip.assigned_object_id != nb_vrrp_group.id
    ):
        nb_ip.assigned_object_type = "ipam.fhrpgroup"
        nb_ip.assigned_object_id = nb_vrrp_group.id
        has_changes = True
    if custom_fields is not None:
        reference_fields = self.bulk_filter(
            nb.extras.custom_fields,
            object_type="ipam.ipaddress",
            type=["object", "multiobject"],
        )
        # The helper converts NetBox's reference objects to writeable IDs
        # and adds new list values without duplicating existing ones.
        current_fields, merged_fields = merge_resolved_custom_fields(
            self,
            nb,
            nb_ip,
            custom_fields,
            [field for field in reference_fields if field.type.value == "object"],
            [
                field
                for field in reference_fields
                if field.type.value == "multiobject"
            ],
        )
        if merged_fields != current_fields:
            if not dry_run:
                nb_ip.update({"custom_fields": merged_fields})
            has_changes = True
    if description and description != nb_ip.description:
        nb_ip.description = description
        has_changes = True
    if vrf and vrf != nb_ip.vrf:
        nb_ip.vrf = {"name": vrf}
        has_changes = True
    if tenant and tenant != getattr(nb_ip.tenant, "name", None):
        nb_ip.tenant = {"name": tenant}
        has_changes = True
    if dns_name and dns_name != nb_ip.dns_name:
        nb_ip.dns_name = dns_name
        has_changes = True
    if comments and comments != nb_ip.comments:
        nb_ip.comments = comments
        has_changes = True
    if role and role != getattr(nb_ip.role, "value", nb_ip.role):
        nb_ip.role = role
        has_changes = True
    if status and status != getattr(nb_ip.status, "value", nb_ip.status):
        nb_ip.status = status
        has_changes = True
    if tags and not any(t in nb_ip.tags for t in tags):
        for t in tags:
            if t not in nb_ip.tags:
                nb_ip.tags.append({"name": t})
                has_changes = True
    if device and interface:
        nb_interface = nb.dcim.interfaces.get(device=device, name=interface)
        if not nb_interface:
            raise NetboxAllocationError(
                f"Unable to source '{device}:{interface}' interface from Netbox"
            )
        if not nb_ip.assigned_object or (
            nb_ip.assigned_object.id != nb_interface.id
        ):
            nb_ip.assigned_object_id = nb_interface.id
            nb_ip.assigned_object_type = "dcim.interface"
            has_changes = True
            log.info(
                f"{device}:{nb_interface} - association {nb_ip} IP address with interface"
            )
        if is_primary is True:
            device_record = nb.dcim.devices.get(name=device)
            if ipaddress.ip_interface(str(nb_ip)).version == 4:
                if (
                    not device_record.primary_ip4
                    or device_record.primary_ip4.id != nb_ip.id
                ):
                    device_record.primary_ip4 = nb_ip.id
                    nb_device = device_record
            elif (
                not device_record.primary_ip6
                or device_record.primary_ip6.id != nb_ip.id
            ):
                device_record.primary_ip6 = nb_ip.id
                nb_device = device_record
    if mask_len and not str(nb_ip).endswith(f"/{mask_len}"):
        address = str(nb_ip).split("/")[0]
        nb_ip.address = f"{address}/{mask_len}"
        has_changes = True

    # save IP address into Netbox
    if dry_run is True:
        ret.status = "unchanged"
        ret.dry_run = True
    elif has_changes or nb_device:
        if has_changes:
            nb_ip.save()
            job.event(f"updated '{str(nb_ip)}' IP address parameters")
        if nb_device:
            nb_device.save()
    elif ret.status != "created":
        ret.status = "unchanged"

    # form and return results
    ret.result = {
        "address": str(nb_ip),
        "description": str(nb_ip.description),
        "vrf": str(nb_ip.vrf) if not vrf else nb_ip.vrf["name"],
        "device": device,
        "interface": interface,
    }
    if vrrp_group is not None:
        ret.result["vrrp_group"] = vrrp_group
    # add branch to results
    if branch is not None:
        ret.result["branch"] = branch

    # create IP address for peer
    if create_peer_ip and create_peer_ip_data:
        job.event(
            f"creating IP address for link peer '{create_peer_ip_data['device']}:{create_peer_ip_data['interface']}'"
        )
        try:
            peer_ip = self.create_ip(
                **create_peer_ip_data, prefix=str(nb_prefix), job=job
            )
        except Exception as exc:
            ret.errors.append(
                f"failed to allocate link peer IP: {exc}; local IP '{nb_ip}' may already be allocated"
            )
        else:
            if peer_ip.failed:
                ret.errors.append(
                    f"failed to allocate link peer IP; local IP '{nb_ip}' may already be allocated"
                )
                ret.errors.extend(peer_ip.errors)
            else:
                ret.result["peer"] = peer_ip.result

    job.event(f"IP address task complete for '{str(nb_ip)}'")
    return ret