# py312
# requirements:
# pynetbox==7.9.0
from typing import List, Literal, Optional, TypedDict
import pynetbox
class netbox(TypedDict):
url: str
token: str
DynSelect_site_id = str
DynSelect_role_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 so a PATCH never blanks a value.
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 sites: the first 1000 (NetBox MAX_PAGE_SIZE); set the value by expression beyond that.
def site_id(auth: netbox):
return options(api(auth).dcim.sites)
# Dropdown of the instance's device roles.
def role_id(auth: netbox):
return options(api(auth).dcim.device_roles)
def main(
auth: netbox,
device_id: int,
name: Optional[str] = None,
status: Optional[
Literal[
"offline",
"active",
"planned",
"staged",
"failed",
"inventory",
"decommissioning",
]
] = None,
site_id: Optional[DynSelect_site_id] = None,
role_id: Optional[DynSelect_role_id] = None,
platform_id: Optional[int] = None,
serial: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[List[str]] = None,
custom_fields: Optional[dict] = None,
):
"""
Update Device
Patch a device: only the fields you set change. custom_fields merges into the existing values; tags (slugs) replace the current tags when set.
"""
body = keep(
name=name,
status=status,
site=int(site_id) if site_id else None,
role=int(role_id) if role_id else None,
platform=platform_id,
serial=serial,
description=description,
tags=[{"slug": s} for s in tags or []],
custom_fields=custom_fields,
)
# A list body on the collection endpoint is NetBox's PATCH of only these fields.
return dict(api(auth).dcim.devices.update([{"id": device_id, **body}])[0])
Submitted by hugo989 3 hours ago