Edits history of script submission #23938 for ' Update IP Address (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,
        ip_address_id: int,
        address: Optional[str] = None,
        status: Optional[
            Literal["active", "reserved", "deprecated", "dhcp", "slaac"]
        ] = None,
        vrf_id: Optional[int] = None,
        dns_name: Optional[str] = None,
        description: Optional[str] = None,
        interface_id: Optional[int] = None,
        tags: Optional[List[str]] = None,
        custom_fields: Optional[dict] = None,
    ):
        """
        Update IP Address
        Patch an IP address: status, VRF, DNS name, description, interface assignment, tags or custom fields. Only the fields you set change.
        """
        body = keep(
            address=address,
            status=status,
            vrf=vrf_id,
            dns_name=dns_name,
            description=description,
            assigned_object_type="dcim.interface" if interface_id else None,
            assigned_object_id=interface_id,
            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).ipam.ip_addresses.update([{"id": ip_address_id, **body}])[0])
    

    Submitted by hugo989 3 hours ago