feat(ansible): run a playbook against a single Steward host (task 547)
From a host's edit page, an operator can run a playbook against just that host via an ephemeral one-host inventory — no need for the host to exist in a source inventory. - ansible/sources.py: pure host_inventory_content(host) -> '<name> ansible_host=<addr>' - executor.start_run: optional inventory_content written to the temp dir and used as -i (overrides inventory_path); cleaned up with the creds dir - hosts/routes.py: POST /hosts/<id>/run-playbook (operator) — validates source + playbook, builds the ephemeral inventory, starts a user-triggered run, redirects to the live run detail; edit page gets the ansible source list - hosts/form.html: 'Run Ansible playbook against this host' panel (shown when editing an existing host and sources exist) — source + playbook + extra-vars/ tags/dry-run (no --limit; single host) - tests: unit host_inventory_content; integration runs a hosts:all/connection:local playbook against the ephemeral inventory and asserts inventory_hostname Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+89
-1
@@ -1,9 +1,13 @@
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from quart import Blueprint, render_template, request, redirect, url_for, current_app, session
|
||||
from sqlalchemy import and_, case, select, func
|
||||
from steward.ansible import executor, sources as ansible_src
|
||||
from steward.auth.middleware import require_role
|
||||
from steward.core.audit import log_audit
|
||||
from steward.models.ansible import AnsibleRun, AnsibleRunStatus
|
||||
from steward.models.hosts import Host, ProbeType
|
||||
from steward.models.monitors import PingResult, DnsResult, PingStatus
|
||||
from steward.models.users import UserRole
|
||||
@@ -11,6 +15,13 @@ from steward.models.users import UserRole
|
||||
hosts_bp = Blueprint("hosts", __name__, url_prefix="/hosts")
|
||||
|
||||
|
||||
def _ansible_source_names() -> list[str]:
|
||||
try:
|
||||
return [s["name"] for s in ansible_src.get_sources(current_app.config.get("ANSIBLE", {}))]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def _compute_uptime(db) -> dict[str, dict]:
|
||||
"""Return per-host uptime % for 24h, 7d, 30d windows.
|
||||
|
||||
@@ -141,7 +152,9 @@ async def edit_host(host_id: str):
|
||||
host = result.scalar_one_or_none()
|
||||
if host is None:
|
||||
return "Not found", 404
|
||||
return await render_template("hosts/form.html", host=host, probe_types=list(ProbeType))
|
||||
return await render_template(
|
||||
"hosts/form.html", host=host, probe_types=list(ProbeType),
|
||||
ansible_sources=_ansible_source_names())
|
||||
|
||||
|
||||
@hosts_bp.post("/<host_id>")
|
||||
@@ -165,6 +178,81 @@ async def update_host(host_id: str):
|
||||
return redirect(url_for("hosts.list_hosts"))
|
||||
|
||||
|
||||
@hosts_bp.post("/<host_id>/run-playbook")
|
||||
@require_role(UserRole.operator)
|
||||
async def run_playbook(host_id: str):
|
||||
"""Run an Ansible playbook against just this host (ephemeral one-host inventory)."""
|
||||
form = await request.form
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
host = (await db.execute(select(Host).where(Host.id == host_id))).scalar_one_or_none()
|
||||
if host is None:
|
||||
return "Not found", 404
|
||||
|
||||
source_name = (form.get("source_name", "") or "").strip()
|
||||
playbook = (form.get("playbook_path", "") or "").strip()
|
||||
if not source_name or not playbook:
|
||||
return "source and playbook are required", 400
|
||||
try:
|
||||
srcs = ansible_src.get_sources(current_app.config.get("ANSIBLE", {}))
|
||||
except Exception:
|
||||
return "Ansible sources are misconfigured", 400
|
||||
source = next((s for s in srcs if s["name"] == source_name), None)
|
||||
if source is None:
|
||||
return "Source not found", 404
|
||||
if playbook not in ansible_src.discover_playbooks(source["path"]):
|
||||
return f"Playbook '{playbook}' not found in source '{source_name}'", 404
|
||||
|
||||
# Optional params (no --limit — there's exactly one host).
|
||||
extra_vars: list[str] = []
|
||||
for line in (form.get("extra_vars", "") or "").splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
if "=" not in line:
|
||||
return f"Invalid extra var (expected key=value): {line!r}", 400
|
||||
extra_vars.append(line)
|
||||
params: dict = {}
|
||||
if extra_vars:
|
||||
params["extra_vars"] = extra_vars
|
||||
tags = (form.get("tags", "") or "").strip()
|
||||
if tags:
|
||||
params["tags"] = tags
|
||||
if "check" in form:
|
||||
params["check"] = True
|
||||
params_or_none = params or None
|
||||
|
||||
run_id = str(uuid.uuid4())
|
||||
inv_content = ansible_src.host_inventory_content(host)
|
||||
run = AnsibleRun(
|
||||
id=run_id,
|
||||
playbook_path=playbook,
|
||||
inventory_path=f"host: {host.name}",
|
||||
source_name=source_name,
|
||||
triggered_by=session.get("user_id"),
|
||||
status=AnsibleRunStatus.running,
|
||||
params=params_or_none,
|
||||
)
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
db.add(run)
|
||||
|
||||
task = asyncio.create_task(
|
||||
executor.start_run(
|
||||
current_app._get_current_object(), # type: ignore[attr-defined]
|
||||
run_id, playbook, f"host: {host.name}", source["path"],
|
||||
params_or_none, inv_content,
|
||||
)
|
||||
)
|
||||
task.add_done_callback(
|
||||
lambda t: t.exception() and current_app.logger.error(
|
||||
"Host playbook run %s raised: %s", run_id, t.exception()))
|
||||
|
||||
await log_audit(current_app, session.get("user_id"), session.get("username", ""),
|
||||
"ansible.host_run", entity_type="host", entity_id=host.name,
|
||||
detail={"playbook": playbook, "source": source_name})
|
||||
return redirect(url_for("ansible.run_detail", run_id=run_id))
|
||||
|
||||
|
||||
@hosts_bp.post("/<host_id>/delete")
|
||||
@require_role(UserRole.admin)
|
||||
async def delete_host(host_id: str):
|
||||
|
||||
Reference in New Issue
Block a user