Skip to content

Netbox Get Interfaces Task¤

task api name: get_interfaces

Get Interfaces Sample Usage¤

NORFAB Netbox Get Interfaces Command Shell Reference¤

NorFab shell supports these command options for Netbox get_interfaces task:

nf#man tree netbox.get.interfaces
root
└── netbox:    Netbox service
    └── get:    Query data from Netbox
        └── interfaces:    Query Netbox device interfaces data
            ├── instance:    Netbox instance name to target
            ├── workers:    Filter worker to target, default 'any'
            ├── timeout:    Job timeout
            ├── *devices:    Devices to retrieve interface for
            ├── ip-addresses:    Retrieves interface IP addresses
            ├── inventory-items:    Retrieves interface inventory items
            └── dry-run:    Only return query content, do not run it
nf#

Python API Reference¤

Retrieve device interfaces from Netbox using GraphQL API.

Parameters:

Name Type Description Default
job Job

NorFab Job object containing relevant metadata

required
instance str

Netbox instance name.

None
devices list

List of devices to retrieve interfaces for.

None
ip_addresses bool

If True, retrieves interface IPs. Defaults to False.

False
inventory_items bool

If True, retrieves interface inventory items. Defaults to False.

False
dry_run bool

If True, only return query content, do not run it. Defaults to False.

False

Returns:

Name Type Description
dict Result

Dictionary keyed by device name with interface details.

Raises:

Type Description
Exception

If no interfaces data is returned for the specified devices.

Source code in norfab\workers\netbox_worker.py
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
@Task()
def get_interfaces(
    self,
    job: Job,
    instance: Union[None, str] = None,
    devices: Union[None, list] = None,
    ip_addresses: bool = False,
    inventory_items: bool = False,
    dry_run: bool = False,
    cache: Union[bool, str] = None,
) -> Result:
    """
    Retrieve device interfaces from Netbox using GraphQL API.

    Args:
        job: NorFab Job object containing relevant metadata
        instance (str, optional): Netbox instance name.
        devices (list, optional): List of devices to retrieve interfaces for.
        ip_addresses (bool, optional): If True, retrieves interface IPs. Defaults to False.
        inventory_items (bool, optional): If True, retrieves interface inventory items. Defaults to False.
        dry_run (bool, optional): If True, only return query content, do not run it. Defaults to False.

    Returns:
        dict: Dictionary keyed by device name with interface details.

    Raises:
        Exception: If no interfaces data is returned for the specified devices.
    """
    instance = instance or self.default_instance
    devices = devices or []
    ret = Result(
        task=f"{self.name}:get_interfaces",
        result={d: {} for d in devices},
        resources=[instance],
    )

    intf_fields = [
        "name",
        "enabled",
        "description",
        "mtu",
        "parent {name}",
        "mode",
        "untagged_vlan {vid name}",
        "vrf {name}",
        "tagged_vlans {vid name}",
        "tags {name}",
        "custom_fields",
        "last_updated",
        "bridge {name}",
        "child_interfaces {name}",
        "bridge_interfaces {name}",
        "member_interfaces {name}",
        "wwn",
        "duplex",
        "speed",
        "id",
        "device {name}",
    ]
    if self.nb_version[instance] >= (4, 2, 0):
        intf_fields.append("mac_addresses {mac_address}")
    else:
        intf_fields.append("mac_address")

    # add IP addresses to interfaces fields
    if ip_addresses:
        intf_fields.append(
            "ip_addresses {address status role dns_name description custom_fields last_updated tenant {name} tags {name}}"
        )

    # form interfaces query dictionary
    if self.nb_version[instance] >= (4, 3, 0):
        dlist = str(devices).replace("'", '"')  # swap quotes
        dfilt = "{device: {name: {in_list: " + dlist + "}}}"
    else:
        dfilt = {"device": devices}
    queries = {
        "interfaces": {
            "obj": "interface_list",
            "filters": dfilt,
            "fields": intf_fields,
        }
    }

    # add query to retrieve inventory items
    if inventory_items:
        if self.nb_version[instance] >= (4, 3, 0):
            dlist = str(devices).replace("'", '"')  # swap quotes
            inv_filters = (
                "{device: {name: {in_list: "
                + dlist
                + '}}, component_type: {app_label: {exact: "dcim"}}}'
            )
        else:
            inv_filters = {"device": devices, "component_type": "dcim.interface"}
        inv_fields = [
            "name",
            "component {... on InterfaceType {id}}",
            "role {name}",
            "manufacturer {name}",
            "custom_fields",
            "label",
            "description",
            "tags {name}",
            "asset_tag",
            "serial",
            "part_id",
        ]
        queries["inventor_items"] = {
            "obj": "inventory_item_list",
            "filters": inv_filters,
            "fields": inv_fields,
        }

    query_result = self.graphql(
        job=job, instance=instance, queries=queries, dry_run=dry_run
    )

    # return dry run result
    if dry_run:
        return query_result

    interfaces_data = query_result.result

    # exit if no Interfaces returned
    if interfaces_data is None or not interfaces_data.get("interfaces"):
        raise Exception(
            f"{self.name} - no interfaces data in '{interfaces_data}' returned by '{instance}' "
            f"for devices {', '.join(devices)}"
        )

    # process query results
    interfaces = interfaces_data.pop("interfaces")

    # process inventory items
    if inventory_items:
        inventory_items_list = interfaces_data.pop("inventor_items")
        # transform inventory items list to a dictionary keyed by intf_id
        inventory_items_dict = {}
        while inventory_items_list:
            inv_item = inventory_items_list.pop()
            # skip inventory items that does not assigned to components
            if inv_item.get("component") is None:
                continue
            intf_id = str(inv_item.pop("component").pop("id"))
            inventory_items_dict.setdefault(intf_id, [])
            inventory_items_dict[intf_id].append(inv_item)
        # iterate over interfaces and add inventory items
        for intf in interfaces:
            intf["inventory_items"] = inventory_items_dict.pop(intf["id"], [])

    # transform interfaces list to dictionary keyed by device and interfaces names
    while interfaces:
        intf = interfaces.pop()
        _ = intf.pop("id")
        device_name = intf.pop("device").pop("name")
        intf_name = intf.pop("name")
        if device_name in ret.result:  # Netbox issue #16299
            ret.result[device_name][intf_name] = intf

    return ret