1 | # py312 |
2 | # requirements: |
3 | # pynetbox==7.9.0 |
4 |
|
5 |
|
6 | from typing import Literal, 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 | device_id: Optional[int] = None, |
37 | name: Optional[str] = None, |
38 | enabled: Optional[Literal["any", "true", "false"]] = None, |
39 | q: Optional[str] = None, |
40 | limit: Optional[int] = None, |
41 | offset: Optional[int] = None, |
42 | ): |
43 | """ |
44 | List Interfaces |
45 | List interfaces, optionally of one device, by name or enabled state. |
46 | """ |
47 | records = api(auth).dcim.interfaces.filter( |
48 | **keep( |
49 | device_id=device_id, |
50 | name=name, |
51 | enabled=None if enabled == "any" else enabled, |
52 | q=q, |
53 | ), |
54 | # limit=0 means NetBox's MAX_PAGE_SIZE, which also caps an explicit 1000. |
55 | limit=50 if limit is None else limit or 1000, |
56 | offset=offset or 0, |
57 | ) |
58 | return page(records) |
59 |
|