# py312
# requirements:
# pynetbox==7.9.0
from typing import List, Literal, 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,
count: Optional[int] = None,
status: Optional[
Literal["active", "reserved", "deprecated", "dhcp", "slaac"]
] = None,
dns_name: Optional[str] = None,
description: Optional[str] = None,
interface_id: Optional[int] = None,
tags: Optional[List[str]] = None,
custom_fields: Optional[dict] = None,
):
"""
Allocate Next Available IP
Reserve the next free IP address(es) in a prefix and create them, optionally assigned to a device interface. Returns the created IP address(es).
"""
prefix = api(auth).ipam.prefixes.get(int(prefix_id))
if prefix is None:
raise ValueError(f"No prefix with id {prefix_id}")
ip = keep(
status=status,
dns_name=dns_name,
description=description,
assigned_object_type="dcim.interface" if interface_id else None,
assigned_object_id=interface_id,
tags=[{"slug": s} for s in tags or []],
custom_fields=custom_fields,
)
# NetBox allocates one IP for an object body, one per item for a list.
n = count or 1
if n == 1:
return dict(prefix.available_ips.create(ip))
return [dict(r) for r in prefix.available_ips.create([ip] * n)]
Submitted by hugo989 3 hours ago