0

List Device Roles

by
Published today

List device roles (e.g. access, core, firewall).

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

8
import pynetbox
9

10

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

15

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

22

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

27

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

33

34
def main(
35
    auth: netbox,
36
    q: Optional[str] = None,
37
    limit: Optional[int] = None,
38
    offset: Optional[int] = None,
39
):
40
    """
41
    List Device Roles
42
    List device roles (e.g. access, core, firewall).
43
    """
44
    records = api(auth).dcim.device_roles.filter(
45
        **keep(q=q),
46
        # limit=0 means NetBox's MAX_PAGE_SIZE, which also caps an explicit 1000.
47
        limit=50 if limit is None else limit or 1000,
48
        offset=offset or 0,
49
    )
50
    return page(records)
51