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_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 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 options(endpoint, key="id", **filters): |
32 | return [ |
33 | {"value": str(getattr(r, key)), "label": r.display} |
34 | for r in endpoint.filter(brief=1, limit=1000, offset=0, **filters) |
35 | ] |
36 |
|
37 |
|
38 | # Dropdown of the instance's prefixes. |
39 | def prefix_id(auth: netbox): |
40 | return options(api(auth).ipam.prefixes) |
41 |
|
42 |
|
43 | def main( |
44 | auth: netbox, |
45 | prefix_id: DynSelect_prefix_id, |
46 | limit: Optional[int] = None, |
47 | ): |
48 | """ |
49 | List Available IPs |
50 | List the free IP addresses in a prefix. |
51 | """ |
52 | prefix = api(auth).ipam.prefixes.get(int(prefix_id)) |
53 | if prefix is None: |
54 | raise ValueError(f"No prefix with id {prefix_id}") |
55 | return [dict(ip) for ip in prefix.available_ips.list(**keep(limit=limit))] |
56 | |