# py312
# requirements:
# pynetbox==7.9.0
from typing import Optional, TypedDict
import pynetbox
class netbox(TypedDict):
url: str
token: str
DynSelect_prefix_id = str
def api(auth: netbox):
# pynetbox adds /api itself; the resource URL may already end with it.
return pynetbox.api(
auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
)
def keep(**fields):
# The run form sends "" / [] / {} for untouched fields: drop them.
return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
def options(endpoint, key="id", **filters):
return [
{"value": str(getattr(r, key)), "label": r.display}
for r in endpoint.filter(brief=1, limit=1000, offset=0, **filters)
]
# Dropdown of the instance's prefixes.
def prefix_id(auth: netbox):
return options(api(auth).ipam.prefixes)
def main(
auth: netbox,
prefix_id: DynSelect_prefix_id,
limit: Optional[int] = None,
):
"""
List Available IPs
List the free IP addresses in a prefix.
"""
prefix = api(auth).ipam.prefixes.get(int(prefix_id))
if prefix is None:
raise ValueError(f"No prefix with id {prefix_id}")
return [dict(ip) for ip in prefix.available_ips.list(**keep(limit=limit))]
Submitted by hugo989 3 hours ago