Skip to content

Commit 45424d1

Browse files
authored
Update netbox_connection.py
Refactor Netbox connection handling and improve error logging
1 parent a945b96 commit 45424d1

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

netbox_connection.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,28 @@ def connect_to_netbox(url, token):
1111
1212
Returns:
1313
- netbox (pynetbox.core.api.Api): The Netbox API object configured to use the provided URL and token.
14+
15+
Raises:
16+
- Exception: If the connection to Netbox fails.
1417
"""
1518
# Create a custom requests session with SSL verification disabled
1619
session = requests.Session()
1720
session.verify = False # Disabling SSL verification for the session
1821

19-
# Create a Netbox API object without specifying any session
20-
netbox = pynetbox.api(url, token)
21-
22-
# Set the custom session for the Netbox API object's requests session
23-
netbox.http_session = session
22+
# Test the connection by making a direct request to /api/status/
23+
try:
24+
headers = {"Authorization": f"Token {token}"}
25+
response = session.get(f"{url}/api/status/", headers=headers)
26+
response.raise_for_status() # Raise an error for HTTP status codes 4xx/5xx
2427

25-
return netbox
28+
# Check if the response contains the "netbox-version" key
29+
status_data = response.json()
30+
if "netbox-version" in status_data:
31+
# Create and return the Netbox API object
32+
netbox = pynetbox.api(url, token)
33+
netbox.http_session = session
34+
return netbox
35+
else:
36+
raise Exception("Unexpected response from Netbox /api/status/ endpoint.")
37+
except Exception as e:
38+
raise Exception(f"Failed to connect to Netbox: {e}")

0 commit comments

Comments
 (0)