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 | # Dropdown of the instance's prefixes, labelled with their VRF and scope since the same prefix can exist in several. |
32 | # First 1000 only (NetBox MAX_PAGE_SIZE); set the value by expression beyond that. |
33 | def prefix_id(auth: netbox): |
34 | options = [] |
35 | for p in api(auth).ipam.prefixes.filter( |
36 | fields="id,prefix,vrf,scope,site", limit=1000, offset=0 |
37 | ): |
38 | # Raw dict: a missing attribute on a pynetbox Record triggers a fetch. |
39 | p = dict(p) |
40 | # Scope (4.2+) or site (older) tells apart the same prefix at two sites. |
41 | where = p.get("scope") or p.get("site") |
42 | label = f"{p['prefix']} ({p['vrf']['name'] if p.get('vrf') else 'global'})" |
43 | if where: |
44 | label += f" · {where['display']}" |
45 | options.append({"value": str(p["id"]), "label": label}) |
46 | return options |
47 |
|
48 |
|
49 | def main( |
50 | auth: netbox, |
51 | prefix_id: DynSelect_prefix_id, |
52 | limit: Optional[int] = None, |
53 | ): |
54 | """ |
55 | List Available IPs |
56 | List the free IP addresses in a prefix. |
57 | """ |
58 | prefix = api(auth).ipam.prefixes.get(int(prefix_id)) |
59 | if prefix is None: |
60 | raise ValueError(f"No prefix with id {prefix_id}") |
61 | return [dict(ip) for ip in prefix.available_ips.list(**keep(limit=limit))] |
62 | |