terraform_ast (tfastdiff) is a Go CLI and library for comparing the Abstract Syntax Tree (AST) and top-level configuration metadata of Terraform modules. It specifically targets enterprise wrappers (such as Google GKE and AWS EKS terraform wrappers) to determine whether a wrapper can be safely updated and pinned to a new upstream version without breaking downstream consumers.
- Single-Pass AST Inspection & Multi-Tier Caching (
pkg/ast): Usesgithub.com/hashicorp/terraform-config-inspectand HCL/JSON parsing (parseAndEnrichModule) to extract variables, outputs, module calls, resources, data sources, provider requirements/aliases/configs,lifecyclepreconditions/postconditions, independentbackend {}andcloud {}configurations, and modern Terraform 1.7+ / OpenTofu blocks (moved,removed,check,import,function,encryption) from.tfand.tf.jsonfiles in a single pass. Includes in-memory overlay inspection (InspectSource) and L1 in-memory / L2 persistent disk caching (--cache-dir). - Terraform Registry Protocol (
pkg/registry): Directly downloads and inspects modules from the Terraform Registry (e.g.terraform-google-modules/kubernetes-engine/google,terraform-aws-modules/eks/aws) with SSRF protection and path-traversal guards. - Deep Structural Object Schema Diffing: Analyzes nested
object({ ... })type constraints attribute-by-attribute (attribute additions, removals,optional()default transitions, and type shifts). - Parallel Blast-Radius & Terragrunt Consumer Analysis (
pkg/blastradius): Uses a bounded worker pool to scan Terraform root modules (.tf,.tf.json) and Terragruntterragrunt.hclconfigurations (--blast-radius ./environments), evaluatingmerge(...),find_in_parent_folders(), andread_terragrunt_config()chains with evidence-gated risk attribution (CRITICAL,HIGH,MEDIUM,LOW). - Evidence-Calibrated Confidence & Safety Scoring: Assigns evidence-backed confidence scores (
[1, 10]) to every finding, computes safety verdicts (SAFE,WARNINGS_ONLY,BREAKING_CHANGES,DOWNGRADE), and recommends the highest contiguous safe-harbor version (SafePinVersion). - ForceNew Destruction Heuristics & Golden Plan Verification (
pkg/recreation): FlagsForceNew(requires_replace) hazards using built-in cloud catalogs (AWS, GCP, AzureRM, Kubernetes, Cloudflare), expanded with Rancher/RKE/k3s/OpenShift, EKS/AKS/GKE addons and extensions, VPC/RDS/S3/Cloud SQL/Storage/Cosmos DB, auto-discoveredterraform providers schema -jsondumps (DynamicHazardRegistry), and Terraform execution plan JSON (--golden-planor automatictfplan.json/golden-plan.jsondiscovery). - State Encryption Helpers (
pkg/encryption): AES-256-GCM encrypt/decrypt helpers for state and module artefacts (OpenTofu-style state encryption) with password-derived keys. - Module Dependency Graph (
pkg/modulegraph): Builds and renders (DOT) module dependency graphs from parsed module calls and input references, with deterministic cycle detection and a topological execution order (--module-graph,--topological-order). - CLI Hook Points (
pkg/hooks): Terragrunt-style hooks with explicitpre-analysis/post-analysisphases (--hook,--post-hook). A failing post-hook never masks the analysis verdict. - Streaming Report Writers (
pkg/report):RenderTextTo/RenderMarkdownTo/RenderJSONTostream reports to anyio.Writerfor large outputs. - OASIS SARIF v2.1.0 Export (
pkg/report): Generates line-exact SARIF v2.1.0 reports (--format sarif), includingTF-RECREATION-HAZARDandTF-POLICY-VIOLATIONrules for GitHub Code Scanning. - Git Optimization & Shared Repository Cache (
pkg/gitops): Implements shallow cloning (--depth 1), Terraform VCS source normalization (git::,github.com/,//subdir?ref=), and a thread-safeRepositoryCachethat clones each repository once per run. - Semantic Versioning & Constraint Range Analysis (
pkg/semverutil): Usesgolang.org/x/mod/semverand interval constraint parsing (ParseConstraintRange) to detect major breaking bumps,0.xminor breaking bumps, upper-bound major narrowings, and downgrade hazards. - Comprehensive Breaking Change Detection (
pkg/diff):- Interface & Type Contracts: Removed inputs/outputs, newly required inputs without defaults, changed defaults, disallowed
null, incompatible type shifts, and output expression changes paired with type/sensitivity shifts. - Resource & Module Cardinality: Unmigrated resource/module removals or address shifts,
countreductions, staticfor_eachkey-set shrinkage (while key-set preservation/widening emitsWARNING), and indexing mode transitions. - Infrastructure & Lifecycle Hazards: Resource-body
ForceNewattribute changes (ResourceForceNew),triggers/keepersdrift, disableddeletion_protectionor enabledforce_destroy,local.*anddata.*selector drift feedingForceNewattributes,precondition/postconditionmodifications onForceNewresources,provider {}block additions/modifications (ProviderConfigRemovedemitted asWARNING), andbackend {}/cloud {}state migrations (StateBackendChange).
- Interface & Type Contracts: Removed inputs/outputs, newly required inputs without defaults, changed defaults, disallowed
- Wrapper Compatibility Audit (
pkg/wrapper):- Validates passed arguments and required inputs across every child
modulecall in the wrapper. - Traces renamed variables and transitive
local.*expressions across input forwarding and output delegations (module.<name>.<output>). - Generates recommended pinning constraints, safe-harbor fallback pins, and actionable remediation steps.
- Validates passed arguments and required inputs across every child
- State Graph, Dependency Visualization & Automated
moved {}Synthesis (pkg/ast,pkg/visualize,pkg/codemod): Tracks canonical Terraform resource instance addresses, exports SVG before/after/transition graphs (--svg-before,--svg-after,--svg-transition) and DOT dependency graphs (--module-graph), generates unified diffs removing dead wrapper inputs (--fix-preview), synthesizes Terraform 1.1+moved {}blocks for address shifts detected by--fix, and emits normalizedimport {}blocks. Resource renames and one-to-many splits can be supplied with--transform(splits require explicit import IDs). - Enterprise Policy Governance & Variable Taint Analysis (
pkg/policy,pkg/eval): Enforces JSON or official OPA SDK Rego v1 policies (--policy,--rego-policy) and traces input variable taint paths across.tfand.tf.jsonlocals, resources, data sources, modules, and outputs (--taint). - Multi-Step Upgrade-Path Planner (
pkg/planner): Evaluates adjacent Git tags or Registry releases across a major-version jump (--upgrade-path) with schema-awareForceNewdetection to identify the furthest contiguous safe version. - Language Server Protocol (
pkg/lsp): Built-in JSON-RPC 2.0 language server (tfastdiff daemon/--lsp) with in-memory buffer overlay diagnostics, hover inspection, and code-action quick fixes. - Enterprise Verification & Test Coverage: 100.0% statement coverage across every package, enforced in CI, backed by Terratest, Golden File regression suites, 31 native Go fuzz targets, and an Independent Python Verification Oracle.
git clone git@github.com:23skdu/terraform_ast.git
cd terraform_ast
go build -o bin/tfastdiff cmd/tfastdiff/main.goImport individual packages from the module path:
go get github.com/23skdu/terraform_astPackage documentation is available on pkg.go.dev.
A hardened, minimal distroless image (~5.7MB, non-root, read-only rootfs compatible) is provided:
# Build the minimal container
docker build -t tfastdiff:latest .
# Run module analysis securely
docker run --rm \
--read-only \
--security-opt no-new-privileges:true \
-v $(pwd):/workspace:ro \
tfastdiff:latest \
--old ./modules/upstream-v19 \
--new ./modules/upstream-v20 \
--format markdownAudit a wrapper module against a target upstream release:
./bin/tfastdiff \
--wrapper ./my-gke-wrapper \
--upstream https://github.com/terraform-google-modules/terraform-google-kubernetes-engine.git \
--new-version v30.0.0 \
--format markdown \
--exit-codeDirectly compare two versions of an upstream module:
./bin/tfastdiff \
--old ./modules/upstream-v19 \
--new ./modules/upstream-v20 \
--old-version v19.0.0 \
--new-version v20.0.0 \
--format textThe published container image can be used directly in CI to run audits; see the Docker quickstart above.
For local checks, add the repository hook to .pre-commit-config.yaml after installing tfastdiff:
repos:
- repo: https://github.com/23skdu/terraform_ast
rev: v0.1.0
hooks:
- id: tfastdiff
args: [--wrapper, ./modules/gke-wrapper, --exit-code]# Terraform Wrapper Compatibility Audit
- **Wrapper Path**: `test/fixtures/gke_wrapper`
- **Target Module**: `gke`
- **Target Version**: `v30.0.0`
- **Recommended Pin**: `version = "30.0.0"`
- **Safest Known Pin**: `v29.0.0` — Keep the currently pinned upstream version until the wrapper compatibility issues are resolved.
- **Verdict**: `BREAKING_CHANGES_DETECTED`
> [!CAUTION]
> **CANNOT SAFELY PIN: Wrapper has 5 breaking issue(s) with upstream v30.0.0. Resolve remediation steps before pinning.**
### Compatibility Issues (6)
| Category | Target | Description | Confidence | Remediation |
| :--- | :--- | :--- | :--- | :--- |
| `BrokenOutputDelegation` | `legacy_network_tag` | Wrapper output 'legacy_network_tag' references module.gke.legacy_network_tag, but output 'legacy_network_tag' was removed in target upstream v30.0.0 | 9/10 | Update or remove output "legacy_network_tag" in wrapper outputs.tf |
| `MissingRequiredInput` | `cluster_autoscaling_profile` | Target upstream v30.0.0 requires input 'cluster_autoscaling_profile' (no default), but wrapper call 'gke' does not provide it | 9/10 | Add argument 'cluster_autoscaling_profile = ...' to module "gke" block in wrapper |
| `MissingRequiredInput` | `grant_registry_access` | Target upstream v30.0.0 requires input 'grant_registry_access' (no default), but wrapper call 'gke' does not provide it | 9/10 | Add argument 'grant_registry_access = ...' to module "gke" block in wrapper |
| `PassedRemovedInput` | `ip_range_services` | Wrapper passes argument 'ip_range_services' to child module 'gke', but 'ip_range_services' is not an accepted input in target upstream v30.0.0 | 9/10 | Remove argument 'ip_range_services' from module "gke" block in wrapper |
| `TypeMismatch` | `ip_range_pods` | Wrapper variable 'ip_range_pods' type 'string' is incompatible with upstream expected type 'list(string)' | 8/10 | Update variable "ip_range_pods" in wrapper to type = list(string) |
| `TypeMismatch` | `zones` | Wrapper variable 'zones' type 'list(string)' differs from upstream 'set(string)': Type converted from list to set (Terraform automatically coerces list to set, but ordering is not preserved) | 8/10 | Align variable "zones" with upstream type |
### Available Upstream Features (1)
| Category | Target | Description | Confidence |
| :--- | :--- | :--- | :--- |
| `OptionalVariableAvailable` | `enable_cost_allocation` | New optional upstream parameter 'enable_cost_allocation' (type bool) can be exposed in wrapper | 9/10 |Full architectural and technical specifications are available under docs/:
- Architecture & Design: Component breakdown, pipelines, and class diagrams.
- Features & Capabilities: Detailed breakdown of core capabilities, enterprise extensions, and outputs.
- CLI Reference & CI/CD Guide: Complete flag reference, exit codes, and GitHub Actions integration.
- Compatibility Rules: Detailed classification taxonomy for breaking changes, warnings, downgrades, and new features.
- Testing Methodology: Unit, fuzz, and Terratest validation, golden file verification, and the 100% coverage gate.
- Quality & Accuracy Gates: Upgrade path accuracy validation, invariant assertions, independent oracle verification, and the pre-commit quality gate.
- Formal Proof: Lean 4 model and machine-checked invariants of the safety verdict (
make lean-verify). - Strategic Roadmap: Current gaps and completed engineering milestones across Passes 1–11.
Every package is held at 100% statement coverage, and the gate is enforced in CI so it cannot silently regress.
Run everything (gofmt, vet, unit tests, coverage gate, fuzz smoke run):
./scripts/verify.sh # default: 10s per fuzz target
./scripts/verify.sh 60 # longer fuzz campaignRun the unit suite and inspect per-package coverage:
go test -cover ./...
go test -coverprofile=coverage.out ./...
go tool cover -func=coverage.out | grep -v '100.0%' # must print nothingNative Go fuzz targets cover every untrusted-input parser. Each one is seeded, runs as part of
go test, and asserts a real invariant rather than "does not crash":
| Target | Package | Invariant |
|---|---|---|
FuzzCLI |
cmd/tfastdiff |
CLI entry point handles arbitrary argument sets safely without unhandled panic |
FuzzInspect |
pkg/ast |
Inspect never panics and re-inspection is stable |
FuzzCheckTypeCompatibility |
pkg/ast |
Compatible is never breaking; any widening/narrowing rules hold |
FuzzParseObjectSchema |
pkg/ast |
Parsed attribute keys always match their recorded names |
FuzzParseModernHCLBlocks |
pkg/ast |
Modern HCL/OpenTofu blocks parse stably or fail gracefully |
FuzzParseMovedLifecycleBackend |
pkg/ast |
moved, lifecycle, backend, and count/for_each enrich cleanly |
FuzzDifferentialValidation |
pkg/ast |
In-memory overlay inspection produces identical ASTs to disk inspection |
FuzzDiscoverCallSites |
pkg/blastradius |
Consumer scanning never panics and always yields a complete call site |
FuzzDiscoverJSONCallSites |
pkg/blastradius |
Terraform JSON scanning never panics |
FuzzTerragruntInputKey |
pkg/blastradius |
Terragrunt keys resolve to a name or cleanly fail |
FuzzPreviewRemovedInputs |
pkg/codemod |
Patch generation never modifies the wrapper it inspects |
FuzzUnifiedReplacement |
pkg/codemod |
Generated patches always carry a valid unified diff header |
FuzzFormatMovedBlocks |
pkg/codemod |
Generated moved {} blocks are syntactically valid |
FuzzCompare |
pkg/diff |
AST module comparison preserves verdict soundness and confidence bounds |
FuzzEvaluateExpression |
pkg/eval |
HCL expression evaluation never panics |
FuzzParseGitSource |
pkg/gitops |
Git module source normalizer never panics on malformed URLs or refs |
FuzzResolveSubDir |
pkg/gitops |
Subdirectory resolution never escapes repository boundaries |
FuzzLSPServe |
pkg/lsp |
LSP JSON-RPC framing handles arbitrary payloads safely |
FuzzAnalyzeUpgradePath |
pkg/planner |
Upgrade path planning preserves contiguous safe-harbor version bounds |
FuzzPolicyDecode |
pkg/policy |
JSON policy unmarshaling never crashes on malformed policy schemas |
FuzzParseRego |
pkg/policy |
Rego parser handles arbitrary rules with fail-closed security |
FuzzParseGoldenPlan |
pkg/recreation |
Plan JSON ingestion normalizes actions and resource changes safely |
FuzzParseProviderSchema |
pkg/recreation |
Dynamic provider schema parsing never panics |
FuzzIsRegistrySource |
pkg/registry |
Local paths and VCS addresses are never treated as Registry sources |
FuzzParseRegistrySource |
pkg/registry |
Registry addresses parse completely or are rejected |
FuzzRenderReports |
pkg/report |
Multi-format report renderer produces valid text, Markdown, JSON, and SARIF |
FuzzNormalizeAndIsValid |
pkg/semverutil |
Normalisation is idempotent and agrees with the semver library |
FuzzDetermineBumpType |
pkg/semverutil |
Bump classification always matches semver ordering |
FuzzSort |
pkg/semverutil |
Sorting preserves every element and enforces strict weak ordering |
FuzzParseConstraintRange |
pkg/semverutil |
Constraint range parser handles arbitrary version constraint strings without panic |
FuzzAnalyzeWrapper |
pkg/wrapper |
Wrapper analysis preserves safety equivalence (TotalBreaking == 0 <=> Safe) |
Run a single target:
go test ./pkg/ast -run '^FuzzInspect$' -fuzz '^FuzzInspect$' -fuzztime 60sRun the decoupled Python verification oracle against golden fixtures and extended compatibility rules:
python3 scripts/oracle_verify.py --skip-upstream -vRun the benchmark suite across pkg/ast, pkg/diff, pkg/blastradius, and pkg/report:
make perfCollect CPU and memory profiles for the hot packages:
make cpuprofile
make memprofileRun all benchmarks:
make benchRuns terraform init/validate/plan against realistic GKE, EKS and object-schema fixtures,
plus a golden-file suite and end-to-end CLI runs against the compiled binary:
go test -v ./test/terratestRegenerate the canonical golden artifacts:
UPDATE_GOLDEN=true go test -v ./test/terratestRun Docker DevSecOps static analysis and container security tests:
go test -v ./test/dockerThis project is released into the public domain under the Unlicense. See LICENSE for details.