0

Create IP Address

by
Published today

Create an IP address (CIDR, e.g. 10.0.0.5/24), optionally assigned to a device interface.

Script netbox Verified

The script

Submitted by hugo989 Python3
Verified 3 hours 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
def api(auth: netbox):
17
    # pynetbox adds /api itself; the resource URL may already end with it.
18
    return pynetbox.api(
19
        auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
20
    )
21

22

23
def keep(**fields):
24
    # The run form sends "" / [] / {} for untouched fields: drop them.
25
    return {k: v for k, v in fields.items() if v not in (None, "", [], {})}
26

27

28
def main(
29
    auth: netbox,
30
    address: str,
31
    status: Optional[
32
        Literal["active", "reserved", "deprecated", "dhcp", "slaac"]
33
    ] = None,
34
    vrf_id: Optional[int] = None,
35
    dns_name: Optional[str] = None,
36
    description: Optional[str] = None,
37
    interface_id: Optional[int] = None,
38
    tags: Optional[List[str]] = None,
39
    custom_fields: Optional[dict] = None,
40
):
41
    """
42
    Create IP Address
43
    Create an IP address (CIDR, e.g. 10.0.0.5/24), optionally assigned to a device interface.
44
    """
45
    body = keep(
46
        address=address,
47
        status=status,
48
        vrf=vrf_id,
49
        dns_name=dns_name,
50
        description=description,
51
        assigned_object_type="dcim.interface" if interface_id else None,
52
        assigned_object_id=interface_id,
53
        tags=[{"slug": s} for s in tags or []],
54
        custom_fields=custom_fields,
55
    )
56
    return dict(api(auth).ipam.ip_addresses.create(body))
57