plan_noop_check.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #!/usr/bin/env python3
  2. """Fail unless a saved OpenTofu plan is a no-op over every known resource.
  3. The stage 2 settings work edits code that two live stacks already run. This
  4. check is the acceptance test for such an edit: with the default values the plan
  5. must change nothing. It reads the JSON of a saved plan (`tofu plan -out=plan`
  6. then `tofu show -json plan`) and a golden file that lists every resource
  7. address the stack has today, and fails when:
  8. - any managed resource change is not exactly ["no-op"] ("update" counts as a
  9. failure; so do create, delete, replace and anything else), or a data source
  10. has an action other than "no-op" or "read";
  11. - any output change is not ["no-op"] or has an unknown value;
  12. - an address in the plan is missing from the golden list, or an address in
  13. the golden list is missing from the plan;
  14. - a force-new attribute differs between before and after, is unknown after
  15. apply, is missing, or differs from the literal the golden file pins;
  16. - a resource was moved (previous_address) and --allow-moves was not given, or
  17. was moved from or to an address the golden file does not list under "moves".
  18. It reads files only and never prints an attribute value (user_data holds
  19. connector tokens). A failure names the address and the attribute.
  20. CI cannot run a real plan: that needs the live state and credentials. CI proves
  21. this checker against mocked plan JSON (tests/test_plan_noop_check.py). The real
  22. gate is the tracked-run plan the maintainer reads in Spacelift before
  23. confirming; this script is for a plan JSON that exists (a local saved plan, or
  24. one a run exposes).
  25. Golden file format (docs/golden-addresses/<stack>.json):
  26. {
  27. "stack": "stacks/10-access",
  28. "addresses": {
  29. "<address>": {"type": "<resource type>", "force_new": {"<attr>": <expected>}}
  30. },
  31. "data": ["<data source address>"],
  32. "moves": {"<previous address>": "<current address>"}
  33. }
  34. <expected> is a literal that must equal the attribute, or "@unchanged", which
  35. only requires before and after to be equal (for ids and sensitive values).
  36. A list of strings is compared as a set.
  37. Usage:
  38. python -I scripts/plan_noop_check.py --plan plan.json --golden docs/golden-addresses/10-access.json [--allow-moves]
  39. Exit codes: 0 no-op, 1 the plan changes something or disagrees with the
  40. golden file, 2 an input file is missing or has a shape this script refuses.
  41. """
  42. from __future__ import annotations
  43. import argparse
  44. import json
  45. import sys
  46. from pathlib import Path
  47. UNCHANGED = "@unchanged"
  48. MAX_BYTES = 256 * 1024 * 1024
  49. class InputError(ValueError):
  50. """An input file is unreadable or has a shape this script refuses."""
  51. def load_json(path: Path, what: str) -> dict:
  52. try:
  53. if path.stat().st_size > MAX_BYTES:
  54. raise InputError(f"{what}: file is larger than {MAX_BYTES} bytes")
  55. data = json.loads(path.read_text(encoding="utf-8"))
  56. except OSError as exc:
  57. raise InputError(f"{what}: cannot read {path} ({exc.strerror})") from exc
  58. except json.JSONDecodeError as exc:
  59. raise InputError(f"{what}: {path} is not JSON ({exc.msg})") from exc
  60. if not isinstance(data, dict):
  61. raise InputError(f"{what}: the top level must be an object")
  62. return data
  63. def validate_golden(golden: dict) -> None:
  64. """Fail closed on a golden file with an unknown shape."""
  65. allowed = {"stack", "note", "addresses", "data", "moves"}
  66. extra = set(golden) - allowed
  67. if extra:
  68. raise InputError(f"golden: unknown keys {sorted(extra)}")
  69. if not isinstance(golden.get("stack"), str):
  70. raise InputError("golden: 'stack' must be a string")
  71. addresses = golden.get("addresses")
  72. if not isinstance(addresses, dict) or not addresses:
  73. raise InputError("golden: 'addresses' must be a non-empty object")
  74. for address, spec in addresses.items():
  75. if not isinstance(spec, dict) or set(spec) != {"type", "force_new"}:
  76. raise InputError(f"golden: {address}: needs exactly 'type' and 'force_new'")
  77. if not isinstance(spec["type"], str) or not isinstance(spec["force_new"], dict):
  78. raise InputError(f"golden: {address}: bad 'type' or 'force_new'")
  79. if not spec["force_new"]:
  80. raise InputError(f"golden: {address}: 'force_new' lists no attribute")
  81. data = golden.get("data", [])
  82. if not isinstance(data, list) or not all(isinstance(a, str) for a in data):
  83. raise InputError("golden: 'data' must be a list of addresses")
  84. moves = golden.get("moves", {})
  85. if not isinstance(moves, dict) or not all(
  86. isinstance(k, str) and isinstance(v, str) for k, v in moves.items()
  87. ):
  88. raise InputError("golden: 'moves' must map addresses to addresses")
  89. for new in moves.values():
  90. if new not in addresses:
  91. raise InputError(f"golden: move target {new} is not a listed address")
  92. def validate_plan(plan: dict) -> list[dict]:
  93. if plan.get("errored") is True:
  94. raise InputError("plan: the plan is marked errored")
  95. changes = plan.get("resource_changes")
  96. if not isinstance(changes, list):
  97. raise InputError("plan: no 'resource_changes' list (not `tofu show -json` of a plan?)")
  98. for entry in changes:
  99. if not isinstance(entry, dict):
  100. raise InputError("plan: a resource change is not an object")
  101. change = entry.get("change")
  102. if (
  103. not isinstance(entry.get("address"), str)
  104. or not isinstance(change, dict)
  105. or not isinstance(change.get("actions"), list)
  106. ):
  107. raise InputError("plan: a resource change has no address or actions")
  108. return changes
  109. def normalize(value):
  110. """Order-insensitive form for lists of strings (tags, sets)."""
  111. if isinstance(value, list) and all(isinstance(v, str) for v in value):
  112. return sorted(value)
  113. return value
  114. def attribute_problems(address: str, spec: dict, change: dict) -> list[str]:
  115. problems: list[str] = []
  116. before = change.get("before")
  117. after = change.get("after")
  118. if not isinstance(before, dict) or not isinstance(after, dict):
  119. return [f"{address}: the plan has no before and after values to compare"]
  120. unknown = change.get("after_unknown")
  121. unknown = unknown if isinstance(unknown, dict) else {}
  122. for attr, expected in spec["force_new"].items():
  123. if attr not in before or attr not in after:
  124. problems.append(f"{address}: force-new attribute {attr} is missing from the plan")
  125. continue
  126. if unknown.get(attr):
  127. problems.append(f"{address}: force-new attribute {attr} is unknown after apply")
  128. continue
  129. if normalize(before[attr]) != normalize(after[attr]):
  130. problems.append(f"{address}: force-new attribute {attr} differs between before and after")
  131. continue
  132. if expected != UNCHANGED and normalize(expected) != normalize(after[attr]):
  133. problems.append(f"{address}: force-new attribute {attr} is not the golden value")
  134. return problems
  135. def output_problems(plan: dict) -> list[str]:
  136. """Any output that would change. Stack 10 reads the foundation outputs."""
  137. outputs = plan.get("output_changes", {})
  138. if not isinstance(outputs, dict):
  139. raise InputError("plan: 'output_changes' is not an object")
  140. problems: list[str] = []
  141. for name, change in sorted(outputs.items()):
  142. if not isinstance(change, dict) or not isinstance(change.get("actions"), list):
  143. raise InputError(f"plan: output {name} has no actions")
  144. if change["actions"] != ["no-op"]:
  145. problems.append(f"output {name}: action is {change['actions']}, expected [\"no-op\"]")
  146. if change.get("after_unknown"):
  147. problems.append(f"output {name}: value is unknown after apply")
  148. return problems
  149. def check(plan: dict, golden: dict, allow_moves: bool = False) -> list[str]:
  150. """Every reason the plan is not a clean no-op over the golden addresses."""
  151. validate_golden(golden)
  152. changes = validate_plan(plan)
  153. addresses = golden["addresses"]
  154. data = set(golden.get("data", []))
  155. moves = golden.get("moves", {})
  156. problems: list[str] = []
  157. seen: set[str] = set()
  158. for entry in changes:
  159. address = entry["address"]
  160. change = entry["change"]
  161. actions = change["actions"]
  162. if address in seen:
  163. problems.append(f"{address}: appears twice in the plan")
  164. continue
  165. seen.add(address)
  166. previous = entry.get("previous_address")
  167. if previous and previous != address:
  168. if not allow_moves:
  169. problems.append(f"{address}: moved from another address (use --allow-moves for the bootstrap moves)")
  170. elif moves.get(previous) != address:
  171. problems.append(f"{address}: moved from an address the golden file does not allow")
  172. if entry.get("mode") == "data":
  173. if address not in data:
  174. problems.append(f"{address}: data source is not in the golden list")
  175. if actions not in (["no-op"], ["read"]):
  176. problems.append(f"{address}: data source action is {actions}, expected no-op or read")
  177. continue
  178. if address not in addresses:
  179. problems.append(f"{address}: in the plan but not in the golden list")
  180. continue
  181. if actions != ["no-op"]:
  182. problems.append(f"{address}: action is {actions}, expected [\"no-op\"]")
  183. spec = addresses[address]
  184. resource_type = entry.get("type")
  185. if resource_type is not None and resource_type != spec["type"]:
  186. problems.append(f"{address}: type is not the golden type")
  187. problems.extend(attribute_problems(address, spec, change))
  188. for address in sorted(set(addresses) - seen):
  189. problems.append(f"{address}: in the golden list but missing from the plan")
  190. problems.extend(output_problems(plan))
  191. # A data source read at plan time may be absent from resource_changes. It is
  192. # not a managed resource, so the golden "data" list is not required to appear.
  193. return problems
  194. def main(argv: list[str] | None = None) -> int:
  195. parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
  196. parser.add_argument("--plan", required=True, help="JSON from `tofu show -json <planfile>`")
  197. parser.add_argument("--golden", required=True, help="docs/golden-addresses/<stack>.json")
  198. parser.add_argument(
  199. "--allow-moves",
  200. action="store_true",
  201. help="accept the moves listed in the golden file (the bootstrap `moved` blocks)",
  202. )
  203. args = parser.parse_args(argv)
  204. try:
  205. golden = load_json(Path(args.golden), "golden")
  206. plan = load_json(Path(args.plan), "plan")
  207. problems = check(plan, golden, args.allow_moves)
  208. except InputError as exc:
  209. print(f"plan no-op check ERROR: {exc}", file=sys.stderr)
  210. return 2
  211. if problems:
  212. print("plan no-op check FAILED (attribute values are never printed):")
  213. for problem in problems:
  214. print(f" {problem}")
  215. return 1
  216. count = len(golden["addresses"])
  217. print(f"plan no-op check passed: {count} addresses, all no-op, force-new attributes unchanged")
  218. return 0
  219. if __name__ == "__main__":
  220. sys.exit(main())