Edits history of script submission #23937 for ' Update Interface (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
    
    
    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 main(
        auth: netbox,
        interface_id: int,
        enabled: Optional[Literal["keep", "true", "false"]] = None,
        description: Optional[str] = None,
        label: Optional[str] = None,
        mtu: Optional[int] = None,
        mode: Optional[Literal["access", "tagged", "tagged-all", "q-in-q"]] = None,
        untagged_vlan_id: Optional[int] = None,
        tagged_vlan_ids: Optional[List[int]] = None,
        custom_fields: Optional[dict] = None,
    ):
        """
        Update Interface
        Patch an interface: enable/disable it, change its description, MTU or 802.1Q mode and VLANs. Only the fields you set change.
        """
        body = keep(
            enabled=None if enabled in (None, "", "keep") else enabled == "true",
            description=description,
            label=label,
            mtu=mtu,
            mode=mode,
            untagged_vlan=untagged_vlan_id,
            tagged_vlans=tagged_vlan_ids,
            custom_fields=custom_fields,
        )
        # A list body on the collection endpoint is NetBox's PATCH of only these fields.
        return dict(api(auth).dcim.interfaces.update([{"id": interface_id, **body}])[0])
    

    Submitted by hugo989 3 hours ago