acupedia-ops/acupedia_ops/ansible/runner.py

110 lines
3.5 KiB
Python

from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Mapping
from acupedia_ops.common.paths import ansible_root
@dataclass(frozen=True, slots=True)
class AnsibleRunResult:
status: str
rc: int
playbook: Path
inventory: Path
artifact_dir: Path | None
stats: Mapping[str, Any]
def _resolve_inventory(inventory: str | Path) -> Path:
candidate = Path(inventory).expanduser()
if candidate.exists():
return candidate.resolve()
candidate = ansible_root() / "inventories" / str(inventory)
if candidate.exists():
return candidate.resolve()
raise FileNotFoundError(f"Inventory not found: {candidate}")
def run_playbook(
*,
playbook: str | Path,
inventory: str | Path,
extra_vars: Mapping[str, Any] | None = None,
limit: str | None = None,
tags: str | None = None,
skip_tags: str | None = None,
check: bool = False,
verbosity: int = 0,
artifact_dir: Path | None = None,
envvars: Mapping[str, str] | None = None,
quiet: bool = False,
event_handler: Callable[[dict[str, Any]], bool | None] | None = None,
status_handler: Callable[[str, dict[str, Any]], None] | None = None,
) -> AnsibleRunResult:
try:
import ansible_runner
except ImportError as exc:
raise RuntimeError(
'Install deployment support with: pip install -e ".[deployment]"'
) from exc
root = ansible_root().resolve()
inventory_path = _resolve_inventory(inventory)
playbook_path = Path(playbook)
if not playbook_path.is_absolute():
playbook_path = root / "playbooks" / playbook_path
playbook_path = playbook_path.resolve()
if not playbook_path.exists():
raise FileNotFoundError(f"Playbook not found: {playbook_path}")
cmdline_parts: list[str] = []
if limit:
cmdline_parts += ["--limit", limit]
if tags:
cmdline_parts += ["--tags", tags]
if skip_tags:
cmdline_parts += ["--skip-tags", skip_tags]
if check:
cmdline_parts.append("--check")
if verbosity:
cmdline_parts.append("-" + "v" * min(verbosity, 4))
kwargs: dict[str, Any] = {
"private_data_dir": str(root),
"inventory": str(inventory_path),
"playbook": str(playbook_path),
"extravars": dict(extra_vars or {}),
"envvars": dict(envvars or {}),
"quiet": quiet,
}
if cmdline_parts:
kwargs["cmdline"] = " ".join(cmdline_parts)
if artifact_dir is not None:
artifact_dir.mkdir(parents=True, exist_ok=True)
kwargs["artifact_dir"] = str(artifact_dir)
if event_handler is not None:
kwargs["event_handler"] = event_handler
if status_handler is not None:
kwargs["status_handler"] = status_handler
result = ansible_runner.run(**kwargs)
rc = int(result.rc or 0)
status = str(result.status or ("successful" if rc == 0 else "failed"))
resolved_artifact_dir = Path(result.artifact_dir) if getattr(result, "artifact_dir", None) else artifact_dir
run_result = AnsibleRunResult(
status=status,
rc=rc,
playbook=playbook_path,
inventory=inventory_path,
artifact_dir=resolved_artifact_dir,
stats=dict(getattr(result, "stats", {}) or {}),
)
if rc != 0:
suffix = f"; artifacts: {resolved_artifact_dir}" if resolved_artifact_dir else ""
raise RuntimeError(
f"Ansible playbook failed with exit code {rc}: {playbook_path}{suffix}"
)
return run_result