"""Archive deployment timing/recaps and enforce the unchanged-rerun gate.""" import json import os import re import subprocess import sys import time from datetime import datetime, timezone from pathlib import Path def main(): record = json.loads(Path(sys.argv[1]).read_text()) operation = sys.argv[2] if operation not in {"deploy", "rerun"}: raise ValueError("Unknown deployment operation") reports = Path("build/delivery/reports") reports.mkdir(parents=True, exist_ok=True) stem = f"ansible-{record['target_env']}-{operation}" started = datetime.now(timezone.utc).isoformat() clock = time.monotonic() process = subprocess.Popen( ["ansible-playbook", *sys.argv[3:]], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=dict(os.environ, ANSIBLE_NOCOLOR="1"), ) lines = [] with (reports / f"{stem}.txt").open("w") as log: for line in process.stdout: print(line, end="", flush=True) log.write(line) lines.append(line) status = process.wait() recaps = [] for line in lines: match = re.match(r"^(\S+)\s+:\s+ok=(\d+)\s+changed=(\d+)\s+unreachable=(\d+)\s+failed=(\d+)", line) if match: recaps.append(dict(zip( ["host", "ok", "changed", "unreachable", "failed"], [match[1], *map(int, match.groups()[1:])], ))) passed = status == 0 and bool(recaps) and all( row["failed"] == 0 and row["unreachable"] == 0 and (operation != "rerun" or row["changed"] == 0) for row in recaps ) report = { "started": started, "completed": datetime.now(timezone.utc).isoformat(), "elapsed_seconds": round(time.monotonic() - clock, 3), "operation": operation, "release": record, "ansible_exit_code": status, "recaps": recaps, "result": "passed" if passed else "blocked", } (reports / f"{stem}.json").write_text(json.dumps(report, indent=2)) if not passed: print("Deployment gate blocked: inspect the archived Ansible recap", file=sys.stderr) return 0 if passed else 1 if __name__ == "__main__": raise SystemExit(main())