0

List VLANs

by
Published today

List VLANs, filtered by site, VLAN id, group or search text.

Script netbox Verified

The script

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

5

6
from typing import Optional, TypedDict
7

8
import pynetbox
9

10

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

15

16
DynSelect_site_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 keep(**fields):
27
    # The run form sends "" / [] / {} for untouched fields: drop them.
28
    return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
29

30

31
def page(records):
32
    # One page (limit/offset), as NetBox's count plus the raw records.
33
    results = [dict(r) for r in records]
34
    return {"count": len(records), "results": results}
35

36

37
def options(endpoint, key="id", **filters):
38
    return [
39
        {"value": str(getattr(r, key)), "label": r.display}
40
        for r in endpoint.filter(brief=1, limit=1000, offset=0, **filters)
41
    ]
42

43

44
# Dropdown of the instance's sites: the first 1000 (NetBox MAX_PAGE_SIZE); set the value by expression beyond that.
45
def site_id(auth: netbox):
46
    return options(api(auth).dcim.sites)
47

48

49
def main(
50
    auth: netbox,
51
    site_id: Optional[DynSelect_site_id] = None,
52
    vid: Optional[int] = None,
53
    group_id: Optional[int] = None,
54
    q: Optional[str] = None,
55
    limit: Optional[int] = None,
56
    offset: Optional[int] = None,
57
):
58
    """
59
    List VLANs
60
    List VLANs, filtered by site, VLAN id, group or search text.
61
    """
62
    records = api(auth).ipam.vlans.filter(
63
        **keep(site_id=site_id, vid=vid, group_id=group_id, q=q),
64
        # limit=0 means NetBox's MAX_PAGE_SIZE, which also caps an explicit 1000.
65
        limit=50 if limit is None else limit or 1000,
66
        offset=offset or 0,
67
    )
68
    return page(records)
69