Capstone: assess a fleet without changing it
Build a tested fleet assessment from inventory, policy and per-host exports, keeping coverage gaps and proposed changes explicit.
Your brief: a morning fleet assessment
The operations team needs a repeatable answer to three questions: which systems need attention, which observations are unavailable, and which service settings differ from policy? Build one script that reads the supplied exports and writes five reviewable reports. This capstone combines validation, file handling, reusable functions and careful error reporting.
Start with inventory and policy, then collect only the selected systems. A missing export is an unavailable observation, not a healthy host. Stale collection data also remains unavailable. Capacity and backup uncertainty within a recent valid snapshot produces attention rather than inventing a measurement.
Keep proposed changes separate from execution
Compare desired service state with observed state and write a plan. A known mismatch is a change proposal; a missing service observation is a review item. The script never starts a service, changes an account or contacts a machine. Reviewers still need current evidence and authorization before taking action elsewhere.
The supplied ops_rules.py contains the rules developed throughout the course. You can compose those functions or implement equivalent behavior. Keep file reading, classification and report writing in separate functions where that helps you understand and test the script.
A report should explain its limits
The complete contract appears below and in the supplied brief.txt, which you can read from the lab. It defines every output column, error reason and time boundary. The fixture has a healthy host, an attention host and a missing snapshot. Checks add empty fleets, malformed records, duplicate identifiers, Unicode names and boundary timestamps.
Write all reports with a fixed order and replace them on successful reruns. Include headers and zero counts even when no host is selected. A deterministic report can be compared with a previous assessment without confusing old rows or accidental ordering changes with real differences.
Complete task contract
Build assess_fleet(root="fleet", output="output", now="2026-11-17T12:00:00Z") returning summary.json's object. Use ops_rules.py helpers if useful. No live OS calls or commands are required.
Inputs and policy
- root/inventory.csv requires host,active,environment,owner. Strip/casefold host and environment; strip owner, which may be empty. Host must match [a-z0-9][a-z0-9-]*. Active is case-insensitive true/false. Logical CSV records start at 2. Invalid rows become errors (reason "invalid record"); first valid normalized host wins, including inactive/out-of-scope hosts, and later duplicates become "duplicate host" errors. Only active hosts in policy environments are assessed.
- root/policy.json uses validate_policy's min_free_percent,backup_max_age_hours,environments and a required services list (possibly empty). Each service has nonempty string service,status,startup. Normalize service identifiers with strip().casefold(); duplicates are invalid. Status/startup comparisons are exact strings.
- Each selected host uses root/snapshots/<host>.json: exact normalized host, aware collected_at, services list under the same validation rules, optional disk {total,free}, optional backup_at. Missing files: "missing snapshot"; JSON/UTF-8 errors: "invalid JSON"; wrong identity, invalid/naive/future collection time or invalid/duplicate services: "invalid snapshot". A structurally valid snapshot strictly older than 24 hours: "stale snapshot". Each produces one error and one evidence_unavailable issue; no service plans. Invalid snapshot structure takes precedence over staleness.
- now must be aware. Missing required inventory/policy raises FileNotFoundError; malformed policy/header raises ValueError. Finish validation and assessment before writing outputs. Unexpected I/O errors propagate. Output must be outside root; reject root itself or a descendant with ValueError. Do not change inputs.
Assessment and outputs (UTF-8; overwrite on every successful run)
- systems.csv columns host,owner,environment,status,free_percent,backup_status; sort by host. Unavailable snapshots have status unavailable, blank free_percent, backup_status unknown. Otherwise use capacity_status and backup_status: unknown capacity/backup needs attention; disk low is strictly below policy before rounding; backup stale is strictly older than maximum age. A backup at the boundary is ok; future/invalid/missing backup is unknown. Healthy means no issue; otherwise attention.
- service_plan.csv columns host,service,action,before_status,before_startup,status,startup; sort by host/service. Compare desired service pairs using service_plan. Known mismatches are change; missing observations are review with blank before fields. Skip equal and unrelated services. These are proposals only.
- issues.csv columns host,code,detail; one row per host/code, sorted by host/code, even if several services have the same problem. Codes/details: disk_low = Free space is below policy; disk_unknown = Capacity evidence is unavailable; backup_stale = Backup exceeds maximum age; backup_unknown = Backup evidence is unavailable; service_change = Observed service differs from policy; service_review = Desired service has no observation; evidence_unavailable = the snapshot error reason.
- errors.csv columns source,record,reason; source is inventory.csv or snapshots/<host>.json. Inventory errors use the logical record number; snapshot errors use 0. Sort by source, numeric record, reason.
- summary.json keys assessed_at (now normalized to UTC ISO ending Z), systems,healthy,attention,unavailable,issues,errors,service_changes. All counts are integers including zeros; service_changes counts all plan rows including review.
- Empty runs still write all four CSV headers and a zero-count summary. Repeated identical inputs produce the same reports. A successful rerun replaces previous rows. This is not a transactional multi-file commit; no guarantee is made for a mid-write I/O failure.
from pathlib import Path
import json
print(json.loads(Path("fleet/policy.json").read_text(encoding="utf-8")))
print(Path("brief.txt").read_text(encoding="utf-8"))
Put it into practice.
Build assess_fleet(root="fleet", output="output", now="2026-11-17T12:00:00Z") to validate inventory/policy and assess selected hosts from supplied snapshots. Write systems.csv, issues.csv, service_plan.csv, errors.csv and summary.json; return the summary. Use the exact schemas, error reasons, ordering and boundaries in brief.txt (print(open("brief.txt", encoding="utf-8").read()) in the terminal to read the full contract). Missing/stale exports are unavailable; uncertain measurements need attention. Service changes are proposals only. Preserve inputs and replace reports on repeat runs.
See an explained solution
import csv, json, re
from datetime import timedelta
from pathlib import Path
from ops_rules import validate_policy, parse_utc, capacity_status, backup_status, service_plan
def assess_fleet(root="fleet", output="output", now="2026-11-17T12:00:00Z"):
source, destination = Path(root), Path(output)
if destination.resolve().is_relative_to(source.resolve()):
raise ValueError("Output must be outside the input directory")
current = parse_utc(now)
raw_policy = json.loads((source / "policy.json").read_text(encoding="utf-8"))
policy = validate_policy(raw_policy)
desired = raw_policy.get("services")
def valid_services(rows):
if not isinstance(rows, list):
raise ValueError("Services must be a list")
seen = set()
for row in rows:
if not isinstance(row, dict) or any(not isinstance(row.get(k), str) or not row[k].strip() for k in ("service", "status", "startup")):
raise ValueError("Invalid service record")
name = row["service"].strip().casefold()
if name in seen:
raise ValueError("Duplicate service")
seen.add(name)
valid_services(desired)
systems, issues, plans, errors, selected, seen = [], [], [], [], [], set()
with (source / "inventory.csv").open(encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle)
if not {"host", "active", "environment", "owner"}.issubset(reader.fieldnames or []):
raise ValueError("Inventory header is incomplete")
for number, row in enumerate(reader, 2):
try:
host = row["host"].strip().casefold()
active = row["active"].strip().casefold()
environment = row["environment"].strip().casefold()
owner = row["owner"].strip()
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", host) or active not in ("true", "false") or not environment:
raise ValueError("Invalid inventory")
except (ValueError, AttributeError):
errors.append({"source":"inventory.csv", "record":number, "reason":"invalid record"})
continue
if host in seen:
errors.append({"source":"inventory.csv", "record":number, "reason":"duplicate host"})
continue
seen.add(host)
if active == "true" and environment in policy["environments"]:
selected.append({"host":host, "owner":owner, "environment":environment})
details = {"disk_low":"Free space is below policy", "disk_unknown":"Capacity evidence is unavailable",
"backup_stale":"Backup exceeds maximum age", "backup_unknown":"Backup evidence is unavailable",
"service_change":"Observed service differs from policy", "service_review":"Desired service has no observation"}
for system in sorted(selected, key=lambda row: row["host"]):
host = system["host"]
relative = "snapshots/" + host + ".json"
problem = None
try:
snapshot = json.loads((source / relative).read_text(encoding="utf-8"))
except FileNotFoundError:
problem = "missing snapshot"
except (ValueError, UnicodeError):
problem = "invalid JSON"
else:
try:
if not isinstance(snapshot, dict) or snapshot.get("host") != host:
raise ValueError("Invalid snapshot identity")
collected = parse_utc(snapshot.get("collected_at"))
valid_services(snapshot.get("services"))
if collected > current:
raise ValueError("Future collection")
if current - collected > timedelta(hours=24):
problem = "stale snapshot"
except (TypeError, ValueError):
problem = "invalid snapshot"
if problem:
errors.append({"source":relative,"record":0,"reason":problem})
issues.append({"host":host,"code":"evidence_unavailable","detail":problem})
systems.append(dict(system,status="unavailable",free_percent=None,backup_status="unknown"))
continue
disk = snapshot.get("disk")
if not isinstance(disk, dict):
disk = {}
capacity = capacity_status(disk.get("total"), disk.get("free"), policy["min_free_percent"])
backup = backup_status(snapshot.get("backup_at"), now, policy["backup_max_age_hours"])
codes = []
if capacity["status"] != "ok":
codes.append("disk_" + capacity["status"])
if backup != "ok":
codes.append("backup_" + backup)
changes = service_plan([dict(row,host=host) for row in snapshot["services"]], [dict(row,host=host) for row in desired])
for change in changes:
before = change["before"] or {}
plans.append({"host":host,"service":change["service"],"action":change["action"],"before_status":before.get("status", ""),"before_startup":before.get("startup", ""),"status":change["after"]["status"],"startup":change["after"]["startup"]})
codes.append("service_" + change["action"])
for code in sorted(set(codes)):
issues.append({"host":host,"code":code,"detail":details[code]})
systems.append(dict(system,status="attention" if codes else "healthy",free_percent=capacity["free_percent"],backup_status=backup))
issues.sort(key=lambda row:(row["host"],row["code"]))
errors.sort(key=lambda row:(row["source"],row["record"],row["reason"]))
plans.sort(key=lambda row:(row["host"],row["service"]))
summary = {"assessed_at":current.isoformat().replace("+00:00","Z"),"systems":len(systems),
**{status:sum(row["status"] == status for row in systems) for status in ("healthy","attention","unavailable")},
"issues":len(issues),"errors":len(errors),"service_changes":len(plans)}
destination.mkdir(parents=True,exist_ok=True)
for name, rows, columns in [
("systems.csv",systems,["host","owner","environment","status","free_percent","backup_status"]),
("issues.csv",issues,["host","code","detail"]),
("service_plan.csv",plans,["host","service","action","before_status","before_startup","status","startup"]),
("errors.csv",errors,["source","record","reason"])]:
with (destination/name).open("w",encoding="utf-8",newline="") as handle:
writer=csv.DictWriter(handle,fieldnames=columns)
writer.writeheader()
writer.writerows(rows)
(destination/"summary.json").write_text(json.dumps(summary,ensure_ascii=False,sort_keys=True)+"\n",encoding="utf-8")
return summary
if __name__ == "__main__":
print(assess_fleet())
The solution validates inputs before producing reports, preserves first-valid inventory identity, and separates unavailable evidence from actionable observations. It proposes service changes without executing them and produces repeatable reports that expose both findings and coverage limitations.