Skip to content

feat(terraform): add Terraform/HCL support (#187) - #1129

Closed
TPAteeq wants to merge 1 commit into
Graphify-Labs:v8from
TPAteeq:terraform-support
Closed

TPAteeq wants to merge 1 commit into
Graphify-Labs:v8from
TPAteeq:terraform-support

Conversation

@TPAteeq

@TPAteeq TPAteeq commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Closes #187.

What this does

Adds AST extraction for Terraform / HCL files (.tf, .tfvars, .hcl) via tree-sitter-hcl, turning an infrastructure repo into a real dependency graph. Before this, .tf files matched no extension set in detect.py, so they classified as None and were skipped entirely — graphify produced zero nodes/edges for Terraform. Now they become a structured graph.

Graph model

  • Nodes: resource, data source, module, variable, output, provider, and per-key locals. (The terraform {} settings block is intentionally not a node.)
  • Edges:
    • contains — file -> each block it defines
    • references — interpolation references, e.g. aws_instance.web -> var.region, -> data.aws_ami.ubuntu, module.vpc -> local.cidr, output.ip -> aws_instance.web
    • depends_on — explicit dependency edges

Labels use canonical Terraform addresses (aws_instance.web, data.aws_ami.ubuntu, var.region, module.vpc, local.cidr, output.ip).

Key design decision: directory-scoped node IDs

Terraform resources are module (directory)-scoped, not file-scoped — a resource defined in main.tf is referenced from sibling .tf files. Node IDs are therefore scoped by the parent directory rather than the file stem, so a definition in one file and a reference in another resolve to the same node when per-file extractions are merged. (Stem scoping, used by most language extractors, would split a definition from its references.)

Why AST (deterministic, free) is the right engine here

Extraction is byte-identical across runs, costs no tokens/API key, resolves references exactly from the HCL grammar (not guessed), and covers every resource/reference — all properties an LLM pass can't match for IaC.

Verified

  • Real repo (a 9-file Terraform module): 25 nodes, 51 edges (27 contains, 24 references), with cross-file resolution confirmed (azurerm_network_interface.* in one file -> azurerm_resource_group.main in another). Extraction is deterministic (two runs identical).
  • Tests (tests/test_terraform.py, 7): block/edge model, references, depends_on, meta-head filtering (count.index/each.key/path.module are not emitted as refs), leading-comment handling, empty/comment-only files, and cross-file resolution through a real build_from_json merge.
  • Full suite 1810 passed, 1 skipped (no regressions); ruff clean; uv sync --all-extras --frozen consistent; skillgen --check unaffected.

Extract .tf, .tfvars, and .hcl files into an infrastructure dependency
graph via tree-sitter-hcl. Resources, data sources, modules, variables,
outputs, providers, and locals become nodes; interpolation references
(aws_instance.web -> var.region, -> data.aws_ami.ubuntu, ...) and explicit
depends_on become edges.

Node IDs are scoped by directory rather than file stem, because Terraform
resources are module(directory)-scoped: a resource defined in main.tf is
referenced from sibling .tf files. Directory scoping lets those cross-file
references resolve when per-file extractions are merged (stem scoping would
split a definition from its references).

- graphify/extract.py: extract_terraform + .tf/.tfvars/.hcl dispatch
- graphify/detect.py: classify the new extensions as code
- pyproject.toml: tree-sitter-hcl as a core grammar (matches the other
  bundled languages); the extractor degrades gracefully if it is absent
- tests/test_terraform.py: block/edge model, depends_on, meta-head
  filtering, leading-comment handling, and cross-file resolution

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@safishamsi safishamsi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great extractor — the directory-scoped node ID design is correct (verified: cross-module collision doesn't occur, _make_id variadic args work fine), the .id comparison for tree-sitter node identity is the right approach, the depends_on traversal reaches into the tuple correctly, and all 7 tests pass. Three things to fix before merge:

1. Move tree-sitter-hcl to an optional extra (blocking)

Currently placed in core dependencies, which means every graphify user installs it even if they never touch Terraform. The established precedent in this codebase is the opposite: tree-sitter-dm and tree-sitter-sql are both in [project.optional-dependencies], even though their extensions ARE in CODE_EXTENSIONS. extract_terraform already has the correct graceful-degradation path on ImportError, so making it optional is low-effort:

[project.optional-dependencies]
terraform = ["tree-sitter-hcl"]
all = [..., "tree-sitter-hcl"]  # add here too

And add a note to the README row like the existing (requires uv tool install graphifyy[dm]) note. If the maintainer explicitly wants HCL in core (it's a pure wheel, no compile), that's a call to make explicitly — just needs sign-off.

2. README count regression (blocking)

The PR branch predates commit fff1c98 which corrected the grammar count to "27 tree-sitter grammars." The PR's README change reintroduces both errors: "Code (34 languages)" instead of the current correct "Code (27 tree-sitter grammars)" (or 28 after HCL). Please rebase onto current v8 and update the count using the "N tree-sitter grammars" phrasing, not "N languages." This will also surface as a merge conflict on that line.

3. .tfvars silent no-op — add a test (should fix)

.tfvars files contain only key=value assignments (no block structure), so extract_terraform extracts zero nodes from them — only the file node is emitted. The extension is registered and dispatched to this extractor, but the behavior is undocumented and untested. Please add a test asserting the current behavior:

def test_tfvars_is_safe(tmp_path):
    r = extract_terraform(_write(tmp_path, "terraform.tfvars", 'region = "us-east-1"\nenv = "prod"\n'))
    assert r.get("error") is None
    assert len(r["nodes"]) == 1  # only the file node

If you want to extract tfvars assignments as var.* nodes (since they override variables), that would be a nice enhancement — but at minimum document the current behavior.

Minor (not blocking):

  • Non-Terraform .hcl files (Packer, Vault, Nomad job specs) produce zero nodes silently — consistent with the rest of graphify's handling of unparseable content, so acceptable as-is.

safishamsi added a commit that referenced this pull request Jun 5, 2026
…1129)

Adds extract_terraform() for .tf/.tfvars/.hcl files. Nodes: resources,
data sources, modules, variables, outputs, providers, locals. Edges:
contains, references (interpolation), depends_on. Node IDs are
directory-scoped for cross-file resolution. tree-sitter-hcl added as
optional extra (graphify[terraform]) matching sql/dm precedent.
8 tests including .tfvars documented no-op behaviour.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Landed in 200edec with the three fixes applied:

  1. tree-sitter-hcl moved to optional extra — graphify[terraform] (not core), added to all extra, matching the sql/dm precedent. Graceful-degradation path on ImportError was already in place.
  2. README count preserved — kept at '27 tree-sitter grammars' per the corrected count (HCL adds one grammar package but the README wording is now grammar-based not language-based).
  3. .tfvars test added — test_tfvars_key_value_is_safe documents that .tfvars key=value assignments produce only the file node (no block structure to extract), which is the correct behaviour.

All 8 tests pass, full suite 1846 passed 0 failures. Great extractor — the directory-scoped ID design, tree-sitter .id comparison, and depends_on traversal are all correct. Thanks for the clean implementation!

@safishamsi safishamsi closed this Jun 5, 2026
@TPAteeq
TPAteeq deleted the terraform-support branch June 5, 2026 20:46
safishamsi added a commit that referenced this pull request Jun 5, 2026
safishamsi added a commit that referenced this pull request Jun 5, 2026
@kellystuard kellystuard mentioned this pull request Jun 27, 2026
PerryLin-0420 pushed a commit to PerryLin-0420/graphify-decouple that referenced this pull request Aug 13, 2026
…raphify-Labs#1129)

Adds extract_terraform() for .tf/.tfvars/.hcl files. Nodes: resources,
data sources, modules, variables, outputs, providers, locals. Edges:
contains, references (interpolation), depends_on. Node IDs are
directory-scoped for cross-file resolution. tree-sitter-hcl added as
optional extra (graphify[terraform]) matching sql/dm precedent.
8 tests including .tfvars documented no-op behaviour.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
PerryLin-0420 pushed a commit to PerryLin-0420/graphify-decouple that referenced this pull request Aug 13, 2026
PerryLin-0420 pushed a commit to PerryLin-0420/graphify-decouple that referenced this pull request Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Terraform Support

2 participants