Skip to content

Commit 847dd05

Browse files
thangphan205claude
andcommitted
fix: regenerate nornir inventory from DB at backend startup
groups.yaml only got rewritten as a side effect of group CRUD, while hosts.yaml rewrites on switch CRUD. The inventory dir is gitignored and not a Docker volume, so a fresh/recreated container has neither file until someone happens to touch Groups — until then any switch sync crashes with KeyError on a missing platform group (e.g. arista_eos). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent c6c4c4e commit 847dd05

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

backend/app/crud/create_nornir.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,27 @@ def create_groups(groups_db: any):
110110
group_dict_nornir["arista_eos"] = {"platform": "eos"}
111111

112112
_write_yaml_atomic(f"{_INVENTORY_DIR}/groups.yaml", group_dict_nornir)
113+
114+
115+
def regenerate_inventory() -> None:
116+
"""Rebuild hosts.yaml and groups.yaml from the DB.
117+
118+
The inventory dir is gitignored and not a Docker volume, so every
119+
container recreate starts with it empty. hosts.yaml is normally
120+
rewritten as a side effect of switch CRUD, and groups.yaml as a side
121+
effect of group CRUD — until either happens, InitNornir crashes with
122+
a KeyError on a missing platform group. Call this at app startup so
123+
a fresh container is never in that half-populated state.
124+
"""
125+
from sqlmodel import Session, select
126+
127+
from app.core.db import engine
128+
from app.models import Credential, Group, Switch
129+
130+
with Session(engine) as session:
131+
switches_db = session.exec(
132+
select(Switch, Credential).where(Switch.credential_id == Credential.id)
133+
).all()
134+
create_hosts(switches_db)
135+
groups_db = session.exec(select(Group)).all()
136+
create_groups(groups_db)

backend/app/main.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from app.api.main import api_router
1010
from app.core.config import settings
1111
from app.core.scheduler import health_check_all_switches, scheduler, sync_all_switches
12+
from app.crud.create_nornir import regenerate_inventory
1213

1314

1415
def custom_generate_unique_id(route: APIRoute) -> str:
@@ -21,6 +22,7 @@ def custom_generate_unique_id(route: APIRoute) -> str:
2122

2223
@asynccontextmanager
2324
async def lifespan(_app: FastAPI) -> AsyncGenerator[None, None]:
25+
regenerate_inventory()
2426
scheduler.add_job(
2527
sync_all_switches,
2628
"interval",

0 commit comments

Comments
 (0)