Edits history of script submission #23936 for ' Update Device (netbox)'

  • python3
    One script reply has been approved by the moderators
    Ap­pro­ved
    # 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,
        rack_id: Optional[int] = None,
        position: Optional[float] = None,
        face: Optional[Literal["front", "rear"]] = 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,
        clear_rack: bool = False,
        clear_platform: bool = False,
    ):
        """
        Update Device
        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.
        """
        if clear_rack and (rack_id is not None or position is not None or face):
            raise ValueError("Set rack_id/position/face or clear_rack, not both")
        if clear_platform and platform_id is not None:
            raise ValueError("Set platform_id or clear_platform, not both")
        body = keep(
            name=name,
            status=status,
            site=int(site_id) if site_id else None,
            role=int(role_id) if role_id else None,
            rack=rack_id,
            position=position,
            face=face,
            platform=platform_id,
            serial=serial,
            description=description,
            tags=[{"slug": s} for s in tags or []],
            custom_fields=custom_fields,
        )
        # keep() drops empty values, so clearing a field is explicit: these send null.
        nb = api(auth)
        if rack_id is not None or site_id:
            device = nb.dcim.devices.get(device_id)
            if device is None:
                raise ValueError(f"No device with id {device_id}")
            if rack_id is not None and (device.rack and device.rack.id) != rack_id:
                rack = nb.dcim.racks.get(rack_id)
                if rack is None:
                    raise ValueError(f"No rack with id {rack_id}")
                # A racked device's site and location must be its rack's.
                if site_id and int(site_id) != rack.site.id:
                    raise ValueError(
                        f"Rack {rack_id} is in site {rack.site.id}, not {site_id}: leave site_id empty to follow the rack"
                    )
                body["site"] = rack.site.id
                body["location"] = rack.location.id if rack.location else None
                if position is None:
                    # The old position (and face) would carry over into the new rack.
                    body["position"] = None
                    body.setdefault("face", None)
            elif site_id and int(site_id) != device.site.id:
                if rack_id is not None:
                    raise ValueError(
                        f"Rack {rack_id} is in site {device.site.id}, not {site_id}: leave site_id empty to follow the rack"
                    )
                if device.rack and not clear_rack:
                    raise ValueError(
                        "The device is racked: set rack_id to a rack in the new site, or clear_rack"
                    )
                # The old location belongs to the old site.
                body["location"] = None
        if clear_rack:
            body |= {"rack": None, "position": None, "face": None}
        if clear_platform:
            body["platform"] = None
        # A list body on the collection endpoint is NetBox's PATCH of only these fields.
        return dict(nb.dcim.devices.update([{"id": device_id, **body}])[0])
    

    Submitted by hugo989 20 days ago

  • python3
    # 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 21 days ago