"""CRUD routes for Ansible inventory: groups and targets.""" from __future__ import annotations import uuid import yaml from quart import Blueprint, current_app, redirect, render_template, request, session, url_for from sqlalchemy import select from sqlalchemy.orm import selectinload from steward.ansible import guards from steward.ansible.inventory_gen import ansible_group_name from steward.auth.middleware import require_role from steward.core.audit import audit_request as _audit from steward.models.ansible_inventory import AnsibleGroup, AnsibleTarget from steward.models.ansible_schedule import AnsibleSchedule from steward.models.hosts import Host from steward.models.users import UserRole inventory_bp = Blueprint("ansible_inventory", __name__, url_prefix="/ansible/inventory") def _parse_ansible_vars(raw: str) -> dict: """Parse a YAML/JSON string into a dict. Raises ValueError on invalid input.""" raw = raw.strip() if not raw: return {} try: parsed = yaml.safe_load(raw) except yaml.YAMLError as exc: raise ValueError(f"Invalid YAML: {exc}") from exc if parsed is None: return {} if not isinstance(parsed, dict): raise ValueError("ansible_vars must be a YAML mapping (key: value pairs)") return parsed def _vars_refusal(new: dict, old: dict | None = None) -> str | None: """Why this editor may not make this vars change, or None (ansible/guards.py).""" return guards.check_vars_for_role(guards.changed_vars(new, old), UserRole(session.get("user_role", "viewer"))) def _add(kind: str, error: str, values: dict) -> dict: """An Add dialog to reopen on the Inventory page: which, why, what was typed.""" return {"kind": kind, "error": error, "values": values} async def _name_taken(model, name: str) -> bool: async with current_app.db_sessionmaker() as db: return (await db.execute(select(model.id).where(model.name == name))).first() is not None # --------------------------------------------------------------------------- # The Inventory tab (#5333): targets and groups on one page # --------------------------------------------------------------------------- async def _scope_users(db) -> dict[str, list[AnsibleSchedule]]: """{inventory scope: [schedule, …]}: which schedules run against a target or group, so its page can say what deleting it would leave pointing at nothing.""" out: dict[str, list[AnsibleSchedule]] = {} for sch in (await db.execute(select(AnsibleSchedule).order_by(AnsibleSchedule.name))).scalars(): out.setdefault(sch.inventory_scope, []).append(sch) return out @inventory_bp.get("/") @require_role(UserRole.viewer) async def inventory(add: dict | None = None, status: int = 200): """Every target with its address, the Steward host it is linked to and its groups; then every group with its members. The row opens the target or group, where it is edited and deleted. `add` reopens an Add dialog with the error and what was typed (a failed create), or ?add=target|group opens one empty.""" async with current_app.db_sessionmaker() as db: targets = (await db.execute( select(AnsibleTarget).options(selectinload(AnsibleTarget.groups)) .order_by(AnsibleTarget.name))).scalars().all() groups = (await db.execute( select(AnsibleGroup).options(selectinload(AnsibleGroup.targets)) .order_by(AnsibleGroup.name))).scalars().all() host_ids = [t.host_id for t in targets if t.host_id] hosts = {h.id: h for h in (await db.execute( select(Host).where(Host.id.in_(host_ids)))).scalars()} if host_ids else {} users = await _scope_users(db) if add is None and request.args.get("add") in ("target", "group"): add = {"kind": request.args["add"], "error": None, "values": {}} verdict = { "targets": len(targets), "groups": len(groups), "unlinked": sum(1 for t in targets if t.host_id not in hosts), "ungrouped": sum(1 for t in targets if not t.groups), } body = await render_template( "ansible/inventory/index.html", targets=targets, groups=groups, hosts=hosts, users=users, verdict=verdict, add=add) return body, status # --------------------------------------------------------------------------- # Groups # --------------------------------------------------------------------------- @inventory_bp.post("/groups") @require_role(UserRole.operator) async def groups_create(): form = await request.form name = form.get("name", "").strip() values = {"name": name} if not name: return await inventory(_add("group", "A group needs a name.", values), 400) try: ansible_vars = _parse_ansible_vars(form.get("ansible_vars", "")) except ValueError as exc: return await inventory(_add("group", str(exc), values), 400) err = _vars_refusal(ansible_vars) if err: return await inventory(_add("group", err, values), 400) if await _name_taken(AnsibleGroup, name): return await inventory(_add("group", f"There is already a group named {name}.", values), 400) group = AnsibleGroup(id=str(uuid.uuid4()), name=name, ansible_vars=ansible_vars) async with current_app.db_sessionmaker() as db: async with db.begin(): db.add(group) await _audit("ansible.group.created", "ansible_group", group.id, {"name": name, "vars": sorted(ansible_vars)}) return redirect(url_for("ansible_inventory.group_detail", group_id=group.id)) @inventory_bp.get("/groups/") @require_role(UserRole.viewer) async def group_detail(group_id: str): async with current_app.db_sessionmaker() as db: result = await db.execute( select(AnsibleGroup) .where(AnsibleGroup.id == group_id) .options(selectinload(AnsibleGroup.targets)) ) group = result.scalar_one_or_none() if group is None: return "Group not found", 404 all_targets = ( await db.execute(select(AnsibleTarget).order_by(AnsibleTarget.name)) ).scalars().all() used = (await _scope_users(db)).get(f"steward:group:{group.id}", []) member_ids = {t.id for t in group.targets} ansible_vars_yaml = yaml.dump(group.ansible_vars) if group.ansible_vars else "" return await render_template( "ansible/inventory/group_detail.html", group=group, ansible_name=ansible_group_name(group.name), used=used, all_targets=all_targets, member_ids=member_ids, ansible_vars_yaml=ansible_vars_yaml, ) @inventory_bp.post("/groups/") @require_role(UserRole.operator) async def group_update(group_id: str): form = await request.form try: ansible_vars = _parse_ansible_vars(form.get("ansible_vars", "")) except ValueError as exc: return str(exc), 400 async with current_app.db_sessionmaker() as db: async with db.begin(): result = await db.execute( select(AnsibleGroup) .where(AnsibleGroup.id == group_id) .options(selectinload(AnsibleGroup.targets)) ) group = result.scalar_one_or_none() if group is None: return "Group not found", 404 err = _vars_refusal(ansible_vars, group.ansible_vars) if err: return err, 400 name = form.get("name", group.name).strip() if name: group.name = name group.ansible_vars = ansible_vars new_ids = set(form.getlist("target_ids")) all_targets = ( await db.execute(select(AnsibleTarget)) ).scalars().all() target_map = {t.id: t for t in all_targets} group.targets = [target_map[tid] for tid in new_ids if tid in target_map] detail = {"name": group.name, "vars": sorted(ansible_vars), "targets": sorted(t.name for t in group.targets)} await _audit("ansible.group.updated", "ansible_group", group_id, detail) return redirect(url_for("ansible_inventory.group_detail", group_id=group_id)) @inventory_bp.post("/groups//delete") @require_role(UserRole.operator) async def group_delete(group_id: str): async with current_app.db_sessionmaker() as db: async with db.begin(): result = await db.execute( select(AnsibleGroup).where(AnsibleGroup.id == group_id) ) group = result.scalar_one_or_none() if group is None: return redirect(url_for("ansible_inventory.inventory")) name = group.name await db.delete(group) await _audit("ansible.group.deleted", "ansible_group", group_id, {"name": name}) return redirect(url_for("ansible_inventory.inventory")) # --------------------------------------------------------------------------- # Targets # --------------------------------------------------------------------------- @inventory_bp.post("/targets") @require_role(UserRole.operator) async def targets_create(): form = await request.form name = form.get("name", "").strip() address = form.get("address", "").strip() values = {"name": name, "address": address} if not name or not address: return await inventory(_add("target", "A target needs a name and an address.", values), 400) try: ansible_vars = _parse_ansible_vars(form.get("ansible_vars", "")) except ValueError as exc: return await inventory(_add("target", str(exc), values), 400) err = _vars_refusal(ansible_vars) if err: return await inventory(_add("target", err, values), 400) if await _name_taken(AnsibleTarget, name): return await inventory(_add("target", f"There is already a target named {name}.", values), 400) target = AnsibleTarget( id=str(uuid.uuid4()), name=name, address=address, ansible_vars=ansible_vars ) async with current_app.db_sessionmaker() as db: async with db.begin(): db.add(target) await _audit("ansible.target.created", "ansible_target", target.id, {"name": name, "address": address, "vars": sorted(ansible_vars)}) return redirect(url_for("ansible_inventory.target_detail", target_id=target.id)) @inventory_bp.get("/targets/") @require_role(UserRole.viewer) async def target_detail(target_id: str): async with current_app.db_sessionmaker() as db: result = await db.execute( select(AnsibleTarget) .where(AnsibleTarget.id == target_id) .options(selectinload(AnsibleTarget.groups)) ) target = result.scalar_one_or_none() if target is None: return "Target not found", 404 all_groups = ( await db.execute(select(AnsibleGroup).order_by(AnsibleGroup.name)) ).scalars().all() host = await db.get(Host, target.host_id) if target.host_id else None used = (await _scope_users(db)).get(f"steward:target:{target.id}", []) member_group_ids = {g.id for g in target.groups} ansible_vars_yaml = yaml.dump(target.ansible_vars) if target.ansible_vars else "" return await render_template( "ansible/inventory/target_detail.html", target=target, host=host, used=used, all_groups=all_groups, member_group_ids=member_group_ids, ansible_vars_yaml=ansible_vars_yaml, ) @inventory_bp.post("/targets/") @require_role(UserRole.operator) async def target_update(target_id: str): form = await request.form try: ansible_vars = _parse_ansible_vars(form.get("ansible_vars", "")) except ValueError as exc: return str(exc), 400 async with current_app.db_sessionmaker() as db: async with db.begin(): result = await db.execute( select(AnsibleTarget) .where(AnsibleTarget.id == target_id) .options(selectinload(AnsibleTarget.groups)) ) target = result.scalar_one_or_none() if target is None: return "Target not found", 404 err = _vars_refusal(ansible_vars, target.ansible_vars) if err: return err, 400 name = form.get("name", target.name).strip() address = form.get("address", target.address).strip() if name: target.name = name if address: target.address = address target.ansible_vars = ansible_vars new_group_ids = set(form.getlist("group_ids")) all_groups_result = await db.execute(select(AnsibleGroup)) group_map = {g.id: g for g in all_groups_result.scalars().all()} target.groups = [group_map[gid] for gid in new_group_ids if gid in group_map] detail = {"name": target.name, "address": target.address, "vars": sorted(ansible_vars), "groups": sorted(g.name for g in target.groups)} await _audit("ansible.target.updated", "ansible_target", target_id, detail) return redirect(url_for("ansible_inventory.target_detail", target_id=target_id)) @inventory_bp.post("/targets//delete") @require_role(UserRole.operator) async def target_delete(target_id: str): async with current_app.db_sessionmaker() as db: async with db.begin(): result = await db.execute( select(AnsibleTarget).where(AnsibleTarget.id == target_id) ) target = result.scalar_one_or_none() if target is None: return redirect(url_for("ansible_inventory.inventory")) name = target.name await db.delete(target) await _audit("ansible.target.deleted", "ansible_target", target_id, {"name": name}) return redirect(url_for("ansible_inventory.inventory"))