Files
tomas.kracmar df3cda9843 feat(compare): offer a drift check after the full tenant export
After menu item 23 finishes it offers to compare with the newest earlier
export of the same tenant (assignments included) and writes the report to
<root>/_drift/<old>-to-<new>/. Compare-Tenants.py now also accepts a
folder that holds a single export folder (e.g. a dated folder containing
Exports/).
2026-11-24 12:27:16 +01:00

338 lines
16 KiB
Python

#!/usr/bin/env python3
"""Compare two IntuneManagement export folders (offline, no Graph calls).
Works for every exported category (Settings Catalog, device configuration,
compliance, Autopilot, ESP, roles, ...) by flattening each JSON object into
path -> value pairs and ignoring what is expected to differ between tenants:
ids, timestamps, scope tags, OData metadata, names and (by default) assignments.
Policies are matched per category:
1. exact - same name after stripping the tenant prefix (--strip-a/--strip-b)
2. fuzzy - similar names (--fuzzy-threshold)
3. content - different names but near-identical settings (--content-threshold)
GUID values are resolved to names through the exported Groups / AssignmentFilters
folders; unresolved GUIDs are masked so they do not show up as differences.
Outputs (in --output-dir): tenant-comparison.md and tenant-comparison.csv
"""
from __future__ import annotations
import argparse
import csv
import difflib
import hashlib
import json
import re
from pathlib import Path
from typing import Any
GUID_RE = re.compile(r"^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$")
SKIP_CATEGORIES = {"Groups", "ADMXFiles"}
LOOKUP_CATEGORIES = ("Groups", "AssignmentFilters")
NAME_KEYS = ("displayName", "name")
ASSIGNMENT_KEYS = {"assignments", "roleAssignments", "groupAssignments"}
VOLATILE = {
"id", "createdDateTime", "lastModifiedDateTime", "modifiedDateTime", "version",
"roleScopeTagIds", "supportsScopeTags", "settingCount", "creationSource",
"isAssigned", "deviceStatuses", "userStatuses", "deviceStatusOverview",
"userStatusOverview", "deviceSettingStateSummaries", "organizationId",
"createdByAppId", "securityIdentifier", "mailNickname", "renewedDateTime",
"largeIcon", "uploadState", "publishingState", "dependentAppCount",
"supersedingAppCount", "supersededAppCount", "committedContentVersion",
"size", "description", "isBuiltInRoleDefinition",
}
# Order matters: first match identifies a list element across tenants
IDENT_PATHS = (
("settingInstance", "settingDefinitionId"), ("settingDefinitionId",),
("definitionId",), ("definition", "displayName"), ("omaUri",),
("displayName",), ("name",), ("@odata.type",),
)
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--root-a", required=True, type=Path, help="Export folder of tenant A (contains category folders)")
p.add_argument("--root-b", required=True, type=Path, help="Export folder of tenant B")
p.add_argument("--label-a", default="A")
p.add_argument("--label-b", default="B")
p.add_argument("--strip-a", default="", help="Regex removed from tenant A names, e.g. '^SSD\\s*-\\s*'")
p.add_argument("--strip-b", default="", help="Regex removed from tenant B names, e.g. '^SSE\\s*-\\s*'")
p.add_argument("--categories", nargs="*", help="Only compare these category folders (default: all common)")
p.add_argument("--include-assignments", action="store_true", help="Also compare assignments (group names, filters, intent)")
p.add_argument("--fuzzy-threshold", type=float, default=0.85, help="Name similarity 0-1 for fuzzy matching")
p.add_argument("--content-threshold", type=float, default=0.9, help="Settings similarity 0-1 for content matching")
p.add_argument("--no-fuzzy", action="store_true", help="Exact name matching only")
p.add_argument("--max-diffs", type=int, default=40, help="Max setting differences per policy in the Markdown report")
p.add_argument("--output-dir", type=Path, default=Path("."))
return p.parse_args()
def norm_name(raw: str, strip: str) -> str:
if strip:
raw = re.sub(strip, "", raw, count=1, flags=re.IGNORECASE)
return re.sub(r"[^a-z0-9]+", " ", raw.lower()).strip()
def clean_name(raw: str, strip: str) -> str:
return re.sub(strip, "", raw, count=1, flags=re.IGNORECASE).strip() if strip else raw
def resolve_root(root: Path) -> Path:
"""Accept either the export root or its parent (e.g. a dated folder holding a single 'Export' folder)."""
def has_categories(p: Path) -> bool:
return any(d.is_dir() and any(d.rglob("*.json")) for d in p.iterdir())
if not root.is_dir() or any(f.suffix == ".json" for f in root.glob("MigrationTable.json")) or \
any(d.name in LOOKUP_CATEGORIES or d.name == "SettingsCatalog" for d in root.iterdir() if d.is_dir()):
return root
inner = [d for d in root.iterdir() if d.is_dir() and has_categories(d)]
if len(inner) == 1:
print(f"Using {inner[0]} as export root")
return inner[0]
return root
def load_json(path: Path) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
class Tenant:
def __init__(self, root: Path, strip: str, label: str):
self.root, self.strip, self.label = root, strip, label
self.names: dict[str, str] = {}
for cat in LOOKUP_CATEGORIES:
for f in (root / cat).rglob("*.json") if (root / cat).is_dir() else []:
d = load_json(f)
if isinstance(d, dict) and d.get("id") and d.get("displayName"):
self.names[d["id"].lower()] = d["displayName"]
mig = load_json(root / "MigrationTable.json")
for o in (mig or {}).get("Objects", []) if isinstance(mig, dict) else []:
if o.get("Id") and o.get("DisplayName"):
self.names.setdefault(o["Id"].lower(), o["DisplayName"])
def categories(self) -> set[str]:
return {d.name for d in self.root.iterdir() if d.is_dir() and d.name not in SKIP_CATEGORIES}
def scalar(self, v: Any) -> str:
if isinstance(v, str):
if GUID_RE.match(v):
name = self.names.get(v.lower())
return clean_name(name, self.strip) if name else "<guid>"
if len(v) > 200:
return f"<sha1:{hashlib.sha1(v.encode()).hexdigest()[:10]} len={len(v)}>"
return v
return json.dumps(v)
def ident(self, item: dict) -> str:
for path in IDENT_PATHS:
cur: Any = item
for k in path:
cur = cur.get(k) if isinstance(cur, dict) else None
if cur not in (None, ""):
return self.scalar(cur)
return ""
def flatten(self, obj: Any, path: str, out: dict, top: bool = False) -> None:
if isinstance(obj, dict):
for k, v in obj.items():
if "@odata" in k or k.startswith("#") or k in VOLATILE or k in ASSIGNMENT_KEYS or k.endswith("DateTime"):
continue
if top and k in NAME_KEYS:
continue
self.flatten(v, f"{path}.{k}" if path else k, out)
elif isinstance(obj, list):
if obj and all(not isinstance(x, (dict, list)) for x in obj):
out[path] = frozenset(self.scalar(x) for x in obj)
return
seen: dict[str, int] = {}
for i, item in enumerate(obj):
key = self.ident(item) if isinstance(item, dict) else ""
key = key or str(i)
seen[key] = seen.get(key, 0) + 1
if seen[key] > 1:
key = f"{key}#{seen[key]}"
self.flatten(item, f"{path}[{key}]", out)
elif obj not in (None, ""):
out[path] = self.scalar(obj)
def assignments(self, obj: dict) -> frozenset:
res = set()
for key in ASSIGNMENT_KEYS:
for a in obj.get(key) or []:
if not isinstance(a, dict):
continue
t = a.get("target")
if t:
kind = str(t.get("@odata.type", "")).split(".")[-1].replace("AssignmentTarget", "")
s = f"{kind}: {self.scalar(t['groupId']) if t.get('groupId') else '-'}"
if t.get("deviceAndAppManagementAssignmentFilterId"):
ftype = t.get("deviceAndAppManagementAssignmentFilterType", "")
s += f" [filter {ftype}: {self.scalar(t['deviceAndAppManagementAssignmentFilterId'])}]"
if a.get("intent"):
s += f" intent={a['intent']}"
else: # role assignment
members = sorted(self.scalar(m) for m in a.get("members", []))
scopes = sorted(self.scalar(m) for m in a.get("resourceScopes", []))
s = f"role assignment '{clean_name(a.get('displayName', ''), self.strip)}' members={members} scopes={scopes}"
res.add(s)
return frozenset(res)
def load_category(self, cat: str, with_assignments: bool) -> dict[str, dict]:
"""Return {unique key: entry} for one category."""
files = sorted((self.root / cat).rglob("*.json"))
companions = {f.name[: -len("_Settings.json")]: f for f in files if f.name.endswith("_Settings.json")}
entries: dict[str, dict] = {}
for f in files:
if f.name.endswith("_Settings.json"):
continue
d = load_json(f)
if not isinstance(d, dict):
continue
comp = companions.get(f.stem)
if comp:
d["_settings"] = load_json(comp)
raw = next((d[k] for k in NAME_KEYS if d.get(k)), f.stem)
key = norm_name(raw, self.strip) or f.stem.lower()
n = 1
while key in entries:
n += 1
key = f"{norm_name(raw, self.strip)} #{n}"
flat: dict[str, Any] = {}
self.flatten(d, "", flat, top=True)
if with_assignments:
flat["(assignments)"] = self.assignments(d)
entries[key] = {"name": clean_name(raw, self.strip), "raw": raw, "flat": flat}
return entries
def show(v: Any) -> str:
s = "" if v is None else (", ".join(sorted(v)) if isinstance(v, frozenset) else str(v))
return s if len(s) <= 300 else s[:297] + "..."
def diff_flat(a: dict, b: dict) -> list[tuple[str, str, str]]:
rows = []
for k in sorted(set(a) | set(b)):
va, vb = a.get(k), b.get(k)
if va == vb:
continue
if isinstance(va, frozenset) and isinstance(vb, frozenset):
rows.append((k, "only here: " + show(va - vb), "only here: " + show(vb - va)))
else:
rows.append((k, show(va), show(vb)))
return rows
def jaccard(a: dict, b: dict) -> float:
sa = {(k, str(v)) for k, v in a.items() if k != "(assignments)"}
sb = {(k, str(v)) for k, v in b.items() if k != "(assignments)"}
if min(len(sa), len(sb)) < 3:
return 0.0
return len(sa & sb) / len(sa | sb)
def match_category(ea: dict, eb: dict, args: argparse.Namespace) -> list[tuple]:
"""Return [(keyA|None, keyB|None, how, score)]."""
pairs = [(k, k, "exact", 1.0) for k in ea if k in eb]
ra = [k for k in ea if k not in eb]
rb = [k for k in eb if k not in ea]
if not args.no_fuzzy:
for how, scorer, thr in (
("fuzzy", lambda x, y: difflib.SequenceMatcher(None, x, y).ratio(), args.fuzzy_threshold),
("content", lambda x, y: jaccard(ea[x]["flat"], eb[y]["flat"]), args.content_threshold),
):
cands = sorted(((scorer(x, y), x, y) for x in ra for y in rb), reverse=True)
used_a, used_b = set(), set()
for score, x, y in cands:
if score < thr:
break
if x in used_a or y in used_b:
continue
used_a.add(x); used_b.add(y)
pairs.append((x, y, how, round(score, 2)))
ra = [k for k in ra if k not in used_a]
rb = [k for k in rb if k not in used_b]
pairs += [(k, None, "", 0.0) for k in ra] + [(None, k, "", 0.0) for k in rb]
return pairs
def main() -> None:
args = parse_args()
for r in (args.root_a, args.root_b):
if not r.is_dir():
raise SystemExit(f"Not a folder: {r}")
args.root_a, args.root_b = resolve_root(args.root_a), resolve_root(args.root_b)
ta = Tenant(args.root_a, args.strip_a, args.label_a)
tb = Tenant(args.root_b, args.strip_b, args.label_b)
cats = sorted(ta.categories() & tb.categories())
if args.categories:
cats = [c for c in cats if c in set(args.categories)]
if not cats:
raise SystemExit("No common category folders found. Point --root-a/--root-b at folders containing e.g. SettingsCatalog/")
la, lb = args.label_a, args.label_b
csv_rows, summary, sections = [], [], []
for cat in cats:
ea = ta.load_category(cat, args.include_assignments)
eb = tb.load_category(cat, args.include_assignments)
counts = {"identical": 0, "differs": 0, f"only {la}": 0, f"only {lb}": 0, "fuzzy/content": 0}
lines = []
for ka, kb, how, score in sorted(match_category(ea, eb, args), key=lambda p: (p[0] or p[1])):
pa, pb = ea.get(ka), eb.get(kb)
if not pb:
counts[f"only {la}"] += 1
csv_rows.append([cat, pa["raw"], "", "", "", f"only {la}", "", "", ""])
lines.append(f"- **only {la}**: {pa['name']}")
continue
if not pa:
counts[f"only {lb}"] += 1
csv_rows.append([cat, "", pb["raw"], "", "", f"only {lb}", "", "", ""])
lines.append(f"- **only {lb}**: {pb['name']}")
continue
diffs = diff_flat(pa["flat"], pb["flat"])
status = "differs" if diffs else "identical"
counts[status] += 1
if how in ("fuzzy", "content"):
counts["fuzzy/content"] += 1
tag = f" _({how} match {score})_" if how != "exact" else ""
if diffs or how != "exact":
head = f"- **{status}**: {pa['name']}" + (f" ↔ {pb['name']}" if pa["name"] != pb["name"] else "") + tag
lines.append(head)
for k, va, vb in diffs[: args.max_diffs]:
lines.append(f" - `{k}`: {la}=`{va}` / {lb}=`{vb}`")
if len(diffs) > args.max_diffs:
lines.append(f" - … {len(diffs) - args.max_diffs} more (see CSV)")
for k, va, vb in diffs or [("", "", "")]:
csv_rows.append([cat, pa["raw"], pb["raw"], how, score, status, k, va, vb])
summary.append((cat, counts))
if lines:
sections.append(f"## {cat}\n\n" + "\n".join(lines))
args.output_dir.mkdir(parents=True, exist_ok=True)
with open(args.output_dir / "tenant-comparison.csv", "w", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
w.writerow(["Category", f"Policy {la}", f"Policy {lb}", "Match", "Score", "Status", "Setting", f"Value {la}", f"Value {lb}"])
w.writerows(csv_rows)
cols = ["identical", "differs", f"only {la}", f"only {lb}", "fuzzy/content"]
md = [f"# Tenant comparison: {la} vs {lb}", "",
f"- {la}: `{args.root_a}`", f"- {lb}: `{args.root_b}`",
f"- Assignments compared: {'yes' if args.include_assignments else 'no'}", "",
"| Category | " + " | ".join(cols) + " |", "|---|" + "---|" * len(cols)]
for cat, c in summary:
md.append(f"| {cat} | " + " | ".join(str(c[x]) for x in cols) + " |")
md += ["", "`fuzzy/content` counts matches that were not an exact name match; check them below.", ""]
(args.output_dir / "tenant-comparison.md").write_text("\n".join(md) + "\n" + "\n\n".join(sections) + "\n", encoding="utf-8")
tot = {x: sum(c[x] for _, c in summary) for x in cols}
print(f"Compared {len(cats)} categories: " + ", ".join(f"{v} {k}" for k, v in tot.items()))
print(f"Wrote {args.output_dir / 'tenant-comparison.md'} and tenant-comparison.csv")
if __name__ == "__main__":
main()