1 | # py312 |
2 | # requirements: |
3 | # pynetbox==7.9.0 |
4 |
|
5 |
|
6 | from typing import List, 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 | q: Optional[str] = None, |
37 | status: Optional[ |
38 | List[Literal["planned", "staging", "active", "decommissioning", "retired"]] |
39 | ] = None, |
40 | tag: Optional[List[str]] = None, |
41 | limit: Optional[int] = None, |
42 | offset: Optional[int] = None, |
43 | ): |
44 | """ |
45 | List Sites |
46 | List sites, optionally filtered by search text, status or tag. |
47 | """ |
48 | records = api(auth).dcim.sites.filter( |
49 | **keep(q=q, status=status, tag=tag), |
50 | # limit=0 means NetBox's MAX_PAGE_SIZE, which also caps an explicit 1000. |
51 | limit=50 if limit is None else limit or 1000, |
52 | offset=offset or 0, |
53 | ) |
54 | return page(records) |
55 |
|