0

Allocate Next Available IP

Published 20 days ago

Reserve the next free IP address(es) in a prefix and create them, optionally assigned to a device interface. Returns the created IP address(es).

Script netbox Verified

The script

Submitted by hugo989 Python3
Verified 20 days ago
1
# py312
2
# requirements:
3
# pynetbox==7.9.0
4

5

6
from typing import List, Literal, Optional, TypedDict
7

8
import pynetbox
9
from pynetbox.core.query import AllocationError
10

11

12
class netbox(TypedDict):
13
    url: str
14
    token: str
15

16

17
DynSelect_prefix_id = str
18

19

20
def api(auth: netbox):
21
    # pynetbox adds /api itself; the resource URL may already end with it.
22
    return pynetbox.api(
23
        auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
24
    )
25

26

27
def keep(**fields):
28
    # The run form sends "" / [] / {} for untouched fields: drop them.
29
    return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
30

31

32
# Dropdown of the instance's prefixes, labelled with their VRF and scope since the same prefix can exist in several.
33
# First 1000 only (NetBox MAX_PAGE_SIZE); set the value by expression beyond that.
34
def prefix_id(auth: netbox):
35
    options = []
36
    for p in api(auth).ipam.prefixes.filter(
37
        fields="id,prefix,vrf,scope,site", limit=1000, offset=0
38
    ):
39
        # Raw dict: a missing attribute on a pynetbox Record triggers a fetch.
40
        p = dict(p)
41
        # Scope (4.2+) or site (older) tells apart the same prefix at two sites.
42
        where = p.get("scope") or p.get("site")
43
        label = f"{p['prefix']} ({p['vrf']['name'] if p.get('vrf') else 'global'})"
44
        if where:
45
            label += f" · {where['display']}"
46
        options.append({"value": str(p["id"]), "label": label})
47
    return options
48

49

50
def main(
51
    auth: netbox,
52
    prefix_id: DynSelect_prefix_id,
53
    count: Optional[int] = None,
54
    status: Optional[
55
        Literal["active", "reserved", "deprecated", "dhcp", "slaac"]
56
    ] = None,
57
    dns_name: Optional[str] = None,
58
    description: Optional[str] = None,
59
    interface_id: Optional[int] = None,
60
    tags: Optional[List[str]] = None,
61
    custom_fields: Optional[dict] = None,
62
):
63
    """
64
    Allocate Next Available IP
65
    Reserve the next free IP address(es) in a prefix and create them, optionally assigned to a device interface. Returns the created IP address(es).
66
    """
67
    if count is not None and count < 1:
68
        raise ValueError(f"count must be at least 1, got {count}")
69
    prefix = api(auth).ipam.prefixes.get(int(prefix_id))
70
    if prefix is None:
71
        raise ValueError(f"No prefix with id {prefix_id}")
72
    ip = keep(
73
        status=status,
74
        dns_name=dns_name,
75
        description=description,
76
        assigned_object_type="dcim.interface" if interface_id else None,
77
        assigned_object_id=interface_id,
78
        tags=[{"slug": s} for s in tags or []],
79
        custom_fields=custom_fields,
80
    )
81
    # NetBox allocates one IP for an object body, one per item for a list.
82
    try:
83
        if count is None or count == 1:
84
            return dict(prefix.available_ips.create(ip))
85
        return [dict(r) for r in prefix.available_ips.create([ip] * count)]
86
    except AllocationError as e:
87
        # pynetbox replaces NetBox's 409 body (which says what is free) with a fixed message.
88
        raise Exception(f"409 {e.req.text}") from None
89