Skip to content

Netbox Get Connections Task¤

task api name: get_connections

Get Connections Sample Usage¤

NORFAB Netbox Get Connections Command Shell Reference¤

NorFab shell supports these command options for Netbox get_connections task:

nf#man tree netbox.get.connections
root
└── netbox:    Netbox service
    └── get:    Query data from Netbox
        └── connections:    Query Netbox connections data for devices
            ├── timeout:    Job timeout
            ├── workers:    Filter worker to target, default 'any'
            ├── verbose-result:    Control output details, default 'False'
            ├── progress:    Display progress events, default 'True'
            ├── instance:    Netbox instance name to target
            ├── dry-run:    Only return query content, do not run it
            ├── devices:    Device names to query data for
            ├── cache:    How to use cache, default 'True'
            └── add-cables:    Add interfaces directly attached cables details
nf#

Python API Reference¤

Retrieve interface connection details for specified devices from Netbox.

Parameters:

Name Type Description Default
job Job

NorFab Job object containing relevant metadata

required
devices list

List of device names to retrieve connections for.

required
instance str

Netbox instance name for the GraphQL query.

None
dry_run bool

If True, perform a dry run without making actual changes.

False
cables bool

if True includes interfaces' directly attached cables details

False

Returns:

Name Type Description
dict Result

A dictionary containing connection details for each device:

{
    "netbox-worker-1.2": {
        "r1": {
            "Console": {
                "breakout": false,
                "remote_device": "termserv1",
                "remote_interface": "ConsoleServerPort1",
                "remote_termination_type": "consoleserverport",
                "termination_type": "consoleport"
            },
            "eth1": {
                "breakout": false,
                "remote_device": "r2",
                "remote_interface": "eth8",
                "remote_termination_type": "interface",
                "termination_type": "interface"
            }
        }
    }
}

Raises:

Type Description
Exception

If there is an error in the GraphQL query or data retrieval process.

Source code in norfab\workers\netbox_worker.py
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
@Task(fastapi={"methods": ["GET"]})
def get_connections(
    self,
    job: Job,
    devices: list,
    instance: Union[None, str] = None,
    dry_run: bool = False,
    cables: bool = False,
    cache: Union[bool, str] = None,
) -> Result:
    """
    Retrieve interface connection details for specified devices from Netbox.

    Args:
        job: NorFab Job object containing relevant metadata
        devices (list): List of device names to retrieve connections for.
        instance (str, optional): Netbox instance name for the GraphQL query.
        dry_run (bool, optional): If True, perform a dry run without making actual changes.
        cables (bool, optional): if True includes interfaces' directly attached cables details

    Returns:
        dict: A dictionary containing connection details for each device:

            ```
            {
                "netbox-worker-1.2": {
                    "r1": {
                        "Console": {
                            "breakout": false,
                            "remote_device": "termserv1",
                            "remote_interface": "ConsoleServerPort1",
                            "remote_termination_type": "consoleserverport",
                            "termination_type": "consoleport"
                        },
                        "eth1": {
                            "breakout": false,
                            "remote_device": "r2",
                            "remote_interface": "eth8",
                            "remote_termination_type": "interface",
                            "termination_type": "interface"
                        }
                    }
                }
            }
            ```

    Raises:
        Exception: If there is an error in the GraphQL query or data retrieval process.
    """
    instance = instance or self.default_instance
    ret = Result(
        task=f"{self.name}:get_connections",
        result={d: {} for d in devices},
        resources=[instance],
    )

    # form lists of fields to request from netbox
    cable_fields = """
        cable {
            type
            status
            tenant {name}
            label
            tags {name}
            length
            length_unit
            custom_fields
        }
    """
    if self.nb_version[instance][0] == 4:
        interfaces_fields = [
            "name",
            "device {name}",
            """connected_endpoints {
            __typename 
            ... on InterfaceType {name device {name}}
            ... on ProviderNetworkType {name}
            }""",
        ]
    elif self.nb_version[instance][0] == 3:
        interfaces_fields = [
            "name",
            "device {name}",
            """connected_endpoints {
            __typename 
            ... on InterfaceType {name device {name}}
            }""",
        ]
    interfaces_fields.append(
        """
        link_peers {
            __typename
            ... on InterfaceType {name device {name}}
            ... on FrontPortType {name device {name}}
            ... on RearPortType {name device {name}}
        }
    """
    )
    console_ports_fields = [
        "name",
        "device {name}",
        """connected_endpoints {
          __typename 
          ... on ConsoleServerPortType {name device {name}}
        }""",
        """link_peers {
          __typename
          ... on ConsoleServerPortType {name device {name}}
          ... on FrontPortType {name device {name}}
          ... on RearPortType {name device {name}}
        }""",
    ]
    console_server_ports_fields = [
        "name",
        "device {name}",
        """connected_endpoints {
          __typename 
          ... on ConsolePortType {name device {name}}
        }""",
        """link_peers {
          __typename
          ... on ConsolePortType {name device {name}}
          ... on FrontPortType {name device {name}}
          ... on RearPortType {name device {name}}
        }""",
    ]

    # check if need to include cables info
    if cables is True:
        interfaces_fields.append(cable_fields)
        console_ports_fields.append(cable_fields)
        console_server_ports_fields.append(cable_fields)

    # form query dictionary with aliases to get data from Netbox
    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 = {
        "interface": {
            "obj": "interface_list",
            "filters": dfilt,
            "fields": interfaces_fields,
        },
        "consoleport": {
            "obj": "console_port_list",
            "filters": dfilt,
            "fields": console_ports_fields,
        },
        "consoleserverport": {
            "obj": "console_server_port_list",
            "filters": dfilt,
            "fields": console_server_ports_fields,
        },
    }

    # retrieve full list of devices interface with all cables
    query_result = self.graphql(
        job=job, queries=queries, instance=instance, dry_run=dry_run
    )

    # return dry run result
    if dry_run:
        return query_result

    all_ports = query_result.result

    # extract interfaces
    for port_type, ports in all_ports.items():
        for port in ports:
            endpoints = port["connected_endpoints"]
            # skip ports that have no remote device connected
            if not endpoints or not all(i for i in endpoints):
                continue

            # extract required parameters
            cable = port.get("cable", {})
            device_name = port["device"]["name"]
            port_name = port["name"]
            link_peers = port["link_peers"]
            remote_termination_type = endpoints[0]["__typename"].lower()
            remote_termination_type = remote_termination_type.replace("type", "")

            # form initial connection dictionary
            connection = {
                "breakout": len(endpoints) > 1,
                "remote_termination_type": remote_termination_type,
                "termination_type": port_type,
            }

            # add remote connection details
            if remote_termination_type == "providernetwork":
                connection["remote_device"] = None
                connection["remote_interface"] = None
                connection["provider"] = endpoints[0]["name"]
            else:
                remote_interface = endpoints[0]["name"]
                if len(endpoints) > 1:
                    remote_interface = list(sorted([i["name"] for i in endpoints]))
                connection["remote_interface"] = remote_interface
                connection["remote_device"] = endpoints[0]["device"]["name"]

            # add cable and its peer details
            if cables:
                peer_termination_type = link_peers[0]["__typename"].lower()
                peer_termination_type = peer_termination_type.replace("type", "")
                cable["peer_termination_type"] = peer_termination_type
                cable["peer_device"] = link_peers[0].get("device", {}).get("name")
                cable["peer_interface"] = link_peers[0].get("name")
                if len(link_peers) > 1:  # handle breakout cable
                    cable["peer_interface"] = [i["name"] for i in link_peers]
                connection["cable"] = cable

            ret.result[device_name][port_name] = connection

    return ret