Edits history of script submission #23916 for ' Allocate Next Available IP (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
    from pynetbox.core.query import AllocationError
    
    
    class netbox(TypedDict):
        url: str
        token: str
    
    
    DynSelect_prefix_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.
        return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
    
    
    # Dropdown of the instance's prefixes, labelled with their VRF and scope since the same prefix can exist in several.
    # First 1000 only (NetBox MAX_PAGE_SIZE); set the value by expression beyond that.
    def prefix_id(auth: netbox):
        options = []
        for p in api(auth).ipam.prefixes.filter(
            fields="id,prefix,vrf,scope,site", limit=1000, offset=0
        ):
            # Raw dict: a missing attribute on a pynetbox Record triggers a fetch.
            p = dict(p)
            # Scope (4.2+) or site (older) tells apart the same prefix at two sites.
            where = p.get("scope") or p.get("site")
            label = f"{p['prefix']} ({p['vrf']['name'] if p.get('vrf') else 'global'})"
            if where:
                label += f" · {where['display']}"
            options.append({"value": str(p["id"]), "label": label})
        return options
    
    
    def main(
        auth: netbox,
        prefix_id: DynSelect_prefix_id,
        count: Optional[int] = None,
        status: Optional[
            Literal["active", "reserved", "deprecated", "dhcp", "slaac"]
        ] = 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,
    ):
        """
        Allocate Next Available IP
        Reserve the next free IP address(es) in a prefix and create them, optionally assigned to a device interface. Returns the created IP address(es).
        """
        if count is not None and count < 1:
            raise ValueError(f"count must be at least 1, got {count}")
        prefix = api(auth).ipam.prefixes.get(int(prefix_id))
        if prefix is None:
            raise ValueError(f"No prefix with id {prefix_id}")
        ip = keep(
            status=status,
            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,
        )
        # NetBox allocates one IP for an object body, one per item for a list.
        try:
            if count is None or count == 1:
                return dict(prefix.available_ips.create(ip))
            return [dict(r) for r in prefix.available_ips.create([ip] * count)]
        except AllocationError as e:
            # pynetbox replaces NetBox's 409 body (which says what is free) with a fixed message.
            raise Exception(f"409 {e.req.text}") from None
    

    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_prefix_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.
        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 prefixes.
    def prefix_id(auth: netbox):
        return options(api(auth).ipam.prefixes)
    
    
    def main(
        auth: netbox,
        prefix_id: DynSelect_prefix_id,
        count: Optional[int] = None,
        status: Optional[
            Literal["active", "reserved", "deprecated", "dhcp", "slaac"]
        ] = 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,
    ):
        """
        Allocate Next Available IP
        Reserve the next free IP address(es) in a prefix and create them, optionally assigned to a device interface. Returns the created IP address(es).
        """
        prefix = api(auth).ipam.prefixes.get(int(prefix_id))
        if prefix is None:
            raise ValueError(f"No prefix with id {prefix_id}")
        ip = keep(
            status=status,
            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,
        )
        # NetBox allocates one IP for an object body, one per item for a list.
        n = count or 1
        if n == 1:
            return dict(prefix.available_ips.create(ip))
        return [dict(r) for r in prefix.available_ips.create([ip] * n)]
    

    Submitted by hugo989 21 days ago