0

Update Device

Published 20 days ago

Patch a device: only the fields you set change. To move a racked device to another site, set rack_id to a rack there (the site follows the rack) or set site_id with clear_rack. Moving it to another rack takes that rack's site and location, and without position leaves it in the rack without a position (and without a face unless face is set), since its old U may be taken or out of range; moving site without a rack clears the location; with position, the device keeps its current face unless face is set (an unracked device has none, so set face). clear_rack unracks it (rack, position and face set to null); clear_platform unsets the platform. A clear_* switch together with a value for the same field is refused. custom_fields merges into the existing values; tags (slugs) replace the current tags when set.

Script netbox Verified

The script

Submitted by hugo989 Python3
Verified 20 days ago
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
DynSelect_site_id = str
17
DynSelect_role_id = str
18

19

20
def api(auth: netbox):
21
    # pynetbox adds /api itself; the resource URL may already end with it.
22
    return pynetbox.api(
23
        auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
24
    )
25

26

27
def keep(**fields):
28
    # The run form sends "" / [] / {} for untouched fields: drop them so a PATCH never blanks a value.
29
    return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
30

31

32
def options(endpoint, key="id", **filters):
33
    return [
34
        {"value": str(getattr(r, key)), "label": r.display}
35
        for r in endpoint.filter(brief=1, limit=1000, offset=0, **filters)
36
    ]
37

38

39
# Dropdown of the instance's sites: the first 1000 (NetBox MAX_PAGE_SIZE); set the value by expression beyond that.
40
def site_id(auth: netbox):
41
    return options(api(auth).dcim.sites)
42

43

44
# Dropdown of the instance's device roles.
45
def role_id(auth: netbox):
46
    return options(api(auth).dcim.device_roles)
47

48

49
def main(
50
    auth: netbox,
51
    device_id: int,
52
    name: Optional[str] = None,
53
    status: Optional[
54
        Literal[
55
            "offline",
56
            "active",
57
            "planned",
58
            "staged",
59
            "failed",
60
            "inventory",
61
            "decommissioning",
62
        ]
63
    ] = None,
64
    site_id: Optional[DynSelect_site_id] = None,
65
    rack_id: Optional[int] = None,
66
    position: Optional[float] = None,
67
    face: Optional[Literal["front", "rear"]] = None,
68
    role_id: Optional[DynSelect_role_id] = None,
69
    platform_id: Optional[int] = None,
70
    serial: Optional[str] = None,
71
    description: Optional[str] = None,
72
    tags: Optional[List[str]] = None,
73
    custom_fields: Optional[dict] = None,
74
    clear_rack: bool = False,
75
    clear_platform: bool = False,
76
):
77
    """
78
    Update Device
79
    Patch a device: only the fields you set change. To move a racked device to another site, set rack_id to a rack there (the site follows the rack) or set site_id with clear_rack. Moving it to another rack takes that rack's site and location, and without position leaves it in the rack without a position (and without a face unless face is set), since its old U may be taken or out of range; moving site without a rack clears the location; with position, the device keeps its current face unless face is set (an unracked device has none, so set face). clear_rack unracks it (rack, position and face set to null); clear_platform unsets the platform. A clear_* switch together with a value for the same field is refused. custom_fields merges into the existing values; tags (slugs) replace the current tags when set.
80
    """
81
    if clear_rack and (rack_id is not None or position is not None or face):
82
        raise ValueError("Set rack_id/position/face or clear_rack, not both")
83
    if clear_platform and platform_id is not None:
84
        raise ValueError("Set platform_id or clear_platform, not both")
85
    body = keep(
86
        name=name,
87
        status=status,
88
        site=int(site_id) if site_id else None,
89
        role=int(role_id) if role_id else None,
90
        rack=rack_id,
91
        position=position,
92
        face=face,
93
        platform=platform_id,
94
        serial=serial,
95
        description=description,
96
        tags=[{"slug": s} for s in tags or []],
97
        custom_fields=custom_fields,
98
    )
99
    # keep() drops empty values, so clearing a field is explicit: these send null.
100
    nb = api(auth)
101
    if rack_id is not None or site_id:
102
        device = nb.dcim.devices.get(device_id)
103
        if device is None:
104
            raise ValueError(f"No device with id {device_id}")
105
        if rack_id is not None and (device.rack and device.rack.id) != rack_id:
106
            rack = nb.dcim.racks.get(rack_id)
107
            if rack is None:
108
                raise ValueError(f"No rack with id {rack_id}")
109
            # A racked device's site and location must be its rack's.
110
            if site_id and int(site_id) != rack.site.id:
111
                raise ValueError(
112
                    f"Rack {rack_id} is in site {rack.site.id}, not {site_id}: leave site_id empty to follow the rack"
113
                )
114
            body["site"] = rack.site.id
115
            body["location"] = rack.location.id if rack.location else None
116
            if position is None:
117
                # The old position (and face) would carry over into the new rack.
118
                body["position"] = None
119
                body.setdefault("face", None)
120
        elif site_id and int(site_id) != device.site.id:
121
            if rack_id is not None:
122
                raise ValueError(
123
                    f"Rack {rack_id} is in site {device.site.id}, not {site_id}: leave site_id empty to follow the rack"
124
                )
125
            if device.rack and not clear_rack:
126
                raise ValueError(
127
                    "The device is racked: set rack_id to a rack in the new site, or clear_rack"
128
                )
129
            # The old location belongs to the old site.
130
            body["location"] = None
131
    if clear_rack:
132
        body |= {"rack": None, "position": None, "face": None}
133
    if clear_platform:
134
        body["platform"] = None
135
    # A list body on the collection endpoint is NetBox's PATCH of only these fields.
136
    return dict(nb.dcim.devices.update([{"id": device_id, **body}])[0])
137