feat(ansible): in-app playbook authoring/editor
Adds create/edit/delete of playbooks from the UI (admin only), so a homelab user without a git workflow can author automation in-app. A new always-present writable local source "steward-local" (/data/ansible/playbooks, env-overridable, created on first save) is editable alongside operator local-dir sources; the bundled and git sources stay read-only (git is GitOps, clobbered on pull). sources.py: write_playbook / delete_playbook (traversal-guarded, .yml/.yaml only) + validate_playbook_yaml (YAML + play-list check) + is_editable_source. routes.py: /playbooks/new, /edit, /save, /delete (admin). Browse gains a "New playbook" button and per-playbook + view-page Edit/Delete for editable sources. Plain textarea editor with save-time YAML validation. Unit tests for write/delete/guard/validate. Task #579 — completes milestone #37 (Ansible automation). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -14,6 +14,12 @@ INVENTORY_NAMES = {"hosts", "inventory", "inventory.yml", "inventory.ini"}
|
||||
# inside the app (maintenance tasks, host-agent install). Not operator-editable.
|
||||
BUILTIN_SOURCE_NAME = "steward-builtin"
|
||||
|
||||
# Always-present, WRITABLE local source where the in-app editor saves playbooks,
|
||||
# so a homelab user with no git workflow can author automation. Lives on the
|
||||
# persistent /data volume; created lazily on first save.
|
||||
LOCAL_SOURCE_NAME = "steward-local"
|
||||
USER_PLAYBOOK_DIR = os.environ.get("STEWARD_PLAYBOOK_DIR", "/data/ansible/playbooks")
|
||||
|
||||
|
||||
def _builtin_source() -> dict:
|
||||
return {
|
||||
@@ -27,6 +33,24 @@ def _builtin_source() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _local_source() -> dict:
|
||||
return {
|
||||
"name": LOCAL_SOURCE_NAME,
|
||||
"type": "local",
|
||||
"path": USER_PLAYBOOK_DIR,
|
||||
"url": None,
|
||||
"branch": "main",
|
||||
"pull_interval_seconds": 0,
|
||||
"http_token": "",
|
||||
}
|
||||
|
||||
|
||||
def is_editable_source(source: dict) -> bool:
|
||||
"""Editable in the in-app editor: local dir sources except the read-only
|
||||
bundled one. Git sources are GitOps (clobbered on pull) so not editable."""
|
||||
return source.get("type") == "local" and source.get("name") != BUILTIN_SOURCE_NAME
|
||||
|
||||
|
||||
def get_sources(ansible_cfg: dict) -> list[dict]:
|
||||
"""Return resolved source list from ansible config section.
|
||||
|
||||
@@ -49,8 +73,8 @@ def get_sources(ansible_cfg: dict) -> list[dict]:
|
||||
"""
|
||||
sources = ansible_cfg.get("sources", [])
|
||||
cache_dir = ansible_cfg.get("cache_dir", "/var/cache/steward/ansible")
|
||||
# Always expose the bundled first-party playbooks as a source.
|
||||
result = [_builtin_source()]
|
||||
# Always expose the bundled (read-only) + local (writable) first-party sources.
|
||||
result = [_builtin_source(), _local_source()]
|
||||
for src in sources:
|
||||
src_type = src.get("type", "local")
|
||||
if src_type == "git":
|
||||
@@ -119,6 +143,65 @@ def read_playbook(source_path: str, relative_path: str) -> str | None:
|
||||
return target.read_text(errors="replace")
|
||||
|
||||
|
||||
def _resolve_writable(source_path: str, relative_path: str) -> tuple[Path | None, str | None]:
|
||||
"""Resolve relative_path under source_path, guarding traversal + extension.
|
||||
|
||||
Returns (target_path, None) on success or (None, error). The root need not
|
||||
exist yet (steward-local is created on first save)."""
|
||||
rel = relative_path.strip().lstrip("/")
|
||||
if not rel:
|
||||
return None, "Filename is required"
|
||||
if not rel.endswith((".yml", ".yaml")):
|
||||
return None, "Playbook filename must end in .yml or .yaml"
|
||||
root = Path(source_path).resolve()
|
||||
target = (root / rel).resolve()
|
||||
try:
|
||||
target.relative_to(root)
|
||||
except ValueError:
|
||||
return None, "Invalid path"
|
||||
return target, None
|
||||
|
||||
|
||||
def write_playbook(source_path: str, relative_path: str, content: str) -> tuple[bool, str | None]:
|
||||
"""Write a playbook into a source, creating parent dirs. Traversal-guarded."""
|
||||
target, err = _resolve_writable(source_path, relative_path)
|
||||
if err:
|
||||
return False, err
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(content, encoding="utf-8")
|
||||
except OSError as exc:
|
||||
return False, f"Could not write file: {exc}"
|
||||
return True, None
|
||||
|
||||
|
||||
def delete_playbook(source_path: str, relative_path: str) -> tuple[bool, str | None]:
|
||||
"""Delete a playbook from a source. Traversal-guarded; no-op if absent."""
|
||||
target, err = _resolve_writable(source_path, relative_path)
|
||||
if err:
|
||||
return False, err
|
||||
try:
|
||||
if target.exists():
|
||||
target.unlink()
|
||||
except OSError as exc:
|
||||
return False, f"Could not delete file: {exc}"
|
||||
return True, None
|
||||
|
||||
|
||||
def validate_playbook_yaml(content: str) -> tuple[bool, str | None]:
|
||||
"""Cheap save-time validation: parses as YAML and is a non-empty play list."""
|
||||
import yaml
|
||||
try:
|
||||
data = yaml.safe_load(content)
|
||||
except yaml.YAMLError as exc:
|
||||
return False, f"YAML error: {exc}"
|
||||
if data is None:
|
||||
return False, "Playbook is empty"
|
||||
if not isinstance(data, list):
|
||||
return False, "A playbook must be a list of plays (top-level YAML list)"
|
||||
return True, None
|
||||
|
||||
|
||||
async def git_pull(source: dict) -> None:
|
||||
"""Clone the git repo if absent; pull if already present.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user