0

List Available Prefixes

by
Published today

List the free child prefixes in a prefix.

Script netbox Verified

The script

Submitted by hugo989 Python3
Verified 5 hours 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
def options(endpoint, key="id", **filters):
27
    return [
28
        {"value": str(getattr(r, key)), "label": r.display}
29
        for r in endpoint.filter(brief=1, limit=1000, offset=0, **filters)
30
    ]
31

32

33
# Dropdown of the instance's prefixes.
34
def prefix_id(auth: netbox):
35
    return options(api(auth).ipam.prefixes)
36

37

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