diff --git a/backend/app/services/device_discovery.py b/backend/app/services/device_discovery.py index 1c760c6..9e35b68 100644 --- a/backend/app/services/device_discovery.py +++ b/backend/app/services/device_discovery.py @@ -488,13 +488,22 @@ async def discover_via_ssh( return result # Step 2: SSH into each rack, parse config, upsert devices - # Build mapping of external_id -> Rack ID for device assignment - rack_id_mapping = {} + # Build mapping of external_id -> Rack.id for device assignment. + # If a rack with that name doesn't exist yet in our racks table, create it now. from app.models.rack import Rack - all_racks = (await db.execute(select(Rack).where(Rack.object_id == obj.id))).scalars().all() - for rack in all_racks: - if rack.external_id: - rack_id_mapping[rack.external_id] = rack.id + rack_id_mapping: dict[str, int] = {} + for ext_id, _, _ in rack_hosts: + existing_rack_row = (await db.execute( + select(Rack).where(Rack.object_id == obj.id, Rack.name == ext_id) + )).scalar_one_or_none() + if existing_rack_row: + rack_id_mapping[ext_id] = existing_rack_row.id + else: + new_rack = Rack(object_id=obj.id, name=ext_id) + db.add(new_rack) + await db.flush() # get the new PK + rack_id_mapping[ext_id] = new_rack.id + logger.info(f"[ssh_discovery] Created rack entry '{ext_id}' (id={new_rack.id})") for external_id, rack_host, rack_name in rack_hosts: # Resolve config_path override from the embedded device's connection_params