0

List Available Prefixes

Published 20 days ago

List the free child prefixes in a prefix.

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 TypedDict
7

8
import pynetbox
9

10

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

15

16
DynSelect_prefix_id = str
17

18

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

25

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

43

44
def main(
45
    auth: netbox,
46
    prefix_id: DynSelect_prefix_id,
47
):
48
    """
49
    List Available Prefixes
50
    List the free child prefixes in a prefix.
51
    """
52
    prefix = api(auth).ipam.prefixes.get(int(prefix_id))
53
    if prefix is None:
54
        raise ValueError(f"No prefix with id {prefix_id}")
55
    return [dict(p) for p in prefix.available_prefixes.list()]
56