1 | # py312 |
2 | # requirements: |
3 | # pynetbox==7.9.0 |
4 |
|
5 |
|
6 | from typing import List, Literal, Optional, TypedDict |
7 |
|
8 | import pynetbox |
9 |
|
10 |
|
11 | class netbox(TypedDict): |
12 | url: str |
13 | token: str |
14 |
|
15 |
|
16 | def api(auth: netbox): |
17 | # pynetbox adds /api itself; the resource URL may already end with it. |
18 | return pynetbox.api( |
19 | auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"] |
20 | ) |
21 |
|
22 |
|
23 | def keep(**fields): |
24 | # The run form sends "" / [] / {} for untouched fields: drop them so a PATCH never blanks a value. |
25 | return {k: v for k, v in fields.items() if v not in (None, "", [], {})} |
26 |
|
27 |
|
28 | def main( |
29 | auth: netbox, |
30 | ip_address_id: int, |
31 | address: Optional[str] = None, |
32 | status: Optional[ |
33 | Literal["active", "reserved", "deprecated", "dhcp", "slaac"] |
34 | ] = None, |
35 | vrf_id: Optional[int] = None, |
36 | dns_name: Optional[str] = None, |
37 | description: Optional[str] = None, |
38 | interface_id: Optional[int] = None, |
39 | tags: Optional[List[str]] = None, |
40 | custom_fields: Optional[dict] = None, |
41 | clear_interface: bool = False, |
42 | clear_vrf: bool = False, |
43 | ): |
44 | """ |
45 | Update IP Address |
46 | Patch an IP address: status, VRF, DNS name, description, interface assignment, tags or custom fields. Only the fields you set change. clear_interface unassigns the IP from its interface (NetBox refuses this while the IP is its device's primary or OOB IP: unset that on the device first); clear_vrf moves it to the global table (VRF null). A clear_* switch together with a value for the same field is refused. |
47 | """ |
48 | if clear_interface and interface_id is not None: |
49 | raise ValueError("Set interface_id or clear_interface, not both") |
50 | if clear_vrf and vrf_id is not None: |
51 | raise ValueError("Set vrf_id or clear_vrf, not both") |
52 | body = keep( |
53 | address=address, |
54 | status=status, |
55 | vrf=vrf_id, |
56 | dns_name=dns_name, |
57 | description=description, |
58 | assigned_object_type="dcim.interface" if interface_id else None, |
59 | assigned_object_id=interface_id, |
60 | tags=[{"slug": s} for s in tags or []], |
61 | custom_fields=custom_fields, |
62 | ) |
63 | # keep() drops empty values, so clearing a field is explicit: these send null. |
64 | if clear_interface: |
65 | body |= {"assigned_object_type": None, "assigned_object_id": None} |
66 | if clear_vrf: |
67 | body["vrf"] = None |
68 | # A list body on the collection endpoint is NetBox's PATCH of only these fields. |
69 | return dict(api(auth).ipam.ip_addresses.update([{"id": ip_address_id, **body}])[0]) |
70 | |