feat: add tofu state lock and drift status
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-10-22 18:29:47 -06:00
parent d980c0b044
commit 0eb6d05ab1
5 changed files with 124 additions and 0 deletions

View File

@ -61,6 +61,7 @@ var allowedCommands = map[string]bool{
"doctor-rpi": true, "doctor-cluster": true, "doctor-k8s": true,
"preflight": true, "doctor-preapply": true, "inventory-check": true,
"state-backup": true, "fix-debian-docker-root": true,
"state": true,
"secrets-init": true, "secrets-check": true, "tailnet-policy-check": true,
"ai-index": true, "ai-check": true, "ask": true, "ai-evals": true,
"ai-scheduler": true, "ai-memory": true, "model-observe": true,

View File

@ -123,3 +123,9 @@ func TestGitopsCommandIsRemotelyEnabled(t *testing.T) {
t.Fatal("gitops must be exposed through the remote API")
}
}
func TestStateCommandIsRemotelyEnabled(t *testing.T) {
if !allowedCommands["state"] {
t.Fatal("state must be exposed through the remote API")
}
}

View File

@ -140,6 +140,7 @@ Recovery And State
drill-gitea-restore Run the Gitea restore drill.
drill-pihole-restore Run the Pi-hole restore drill.
state-backup Back up local OpenTofu state files.
state status [STACK] [--json] Inspect OpenTofu locks and drift without changing state.
Focused Doctors
doctor-edge [--all|--details|--verbose|--json]
@ -507,6 +508,13 @@ case "${1:-}" in
state-backup)
backup_tofu_state
;;
state)
if [[ "${2:-}" != "status" ]]; then
echo "Usage: ./jeannie state status [STACK] [--json]" >&2
exit 2
fi
state_status "${@:3}"
;;
fix-debian-docker-root)
fix_debian_docker_root
;;

View File

@ -3276,6 +3276,11 @@ gitops_manage() {
esac
}
state_status() {
require_debian_server "state status"
"${REPO_ROOT}/scripts/state-status" "$@"
}
storage_status() {
require_debian_server "storage"
local kubeconfig="${KUBECONFIG_PATH}"

104
scripts/state-status Executable file
View File

@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Read-only OpenTofu state lock and drift inspection."""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
from pathlib import Path
STACKS = {
"provisioning": "bootstrap/provisioning",
"cluster": "bootstrap/cluster",
"platform": "bootstrap/platform",
"apps": "bootstrap/apps",
"edge": "bootstrap/edge",
}
def inspect_stack(repo: Path, name: str, relative: str) -> dict:
directory = repo / relative
row = {"stack": name, "path": relative, "state": "missing", "lock": "clear", "drift": "unknown"}
state_file = directory / "terraform.tfstate"
lock_file = directory / ".terraform.tfstate.lock.info"
if not state_file.exists():
row["detail"] = "local state file not found"
return row
row["state"] = "present"
if lock_file.exists():
row["lock"] = "locked"
try:
info = json.loads(lock_file.read_text())
row["lock_info"] = {key: info.get(key) for key in ("ID", "Operation", "Who", "Version", "Created", "Path") if info.get(key)}
except (OSError, json.JSONDecodeError):
row["lock_info"] = {"detail": "lock metadata is not valid JSON"}
command = [
"tofu",
f"-chdir={directory}",
"plan",
"-input=false",
"-no-color",
"-refresh-only",
"-detailed-exitcode",
"-lock-timeout=0s",
]
try:
completed = subprocess.run(command, text=True, capture_output=True, timeout=900)
output = (completed.stdout + "\n" + completed.stderr).strip()
except FileNotFoundError:
row.update(drift="unknown", detail="tofu is not installed")
return row
except subprocess.TimeoutExpired:
row.update(drift="unknown", detail="refresh-only plan timed out")
return row
tail = [line.strip() for line in output.splitlines() if line.strip()][-6:]
lock_error = re.search(r"state lock|Error acquiring the state lock|already locked", output, re.IGNORECASE)
if lock_error:
row["lock"] = "locked"
row["drift"] = "unknown"
row["detail"] = "state lock prevented inspection"
elif completed.returncode == 0:
row["drift"] = "clean"
row["detail"] = tail[-1] if tail else "refresh-only plan clean"
elif completed.returncode == 2:
row["drift"] = "detected"
row["detail"] = " | ".join(tail[-3:])
else:
row["drift"] = "unknown"
row["detail"] = " | ".join(tail[-3:]) or "refresh-only plan failed"
return row
def main() -> int:
parser = argparse.ArgumentParser(description="Inspect OpenTofu state locks and drift without changing state")
parser.add_argument("stack", nargs="?", help="provisioning, cluster, platform, apps, edge, or bootstrap path")
parser.add_argument("--json", action="store_true", dest="as_json")
args = parser.parse_args()
if args.stack and args.stack not in STACKS and args.stack not in STACKS.values():
parser.error(f"unknown stack {args.stack!r}; use {', '.join(STACKS)}")
selected = [(args.stack, args.stack)] if args.stack in STACKS.values() else [(args.stack or key, value) for key, value in STACKS.items() if not args.stack or key == args.stack]
repo = Path(__file__).resolve().parents[1]
rows = [inspect_stack(repo, name, path) for name, path in selected]
failures = [item for item in rows if item["lock"] == "locked" or item["drift"] in ("detected", "unknown")]
report = {"title": "OpenTofu State Status", "status": "warn" if failures else "pass", "rows": rows}
if args.as_json:
print(json.dumps(report, indent=2))
else:
print("== OpenTofu State Status ==")
for item in rows:
print(f"{item['stack']}: state={item['state']} lock={item['lock']} drift={item['drift']}")
if item.get("detail"):
print(f" detail: {item['detail']}")
if item.get("lock_info"):
print(f" lock: {json.dumps(item['lock_info'], sort_keys=True)}")
print(f"Overall: {report['status']}")
return 1 if failures else 0
if __name__ == "__main__":
raise SystemExit(main())