auryn-terraform 0.8.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+
12
+ # Test/coverage artifacts
13
+ .coverage
14
+ .pytest_cache/
15
+ *.db
16
+
17
+ # Embedded-graph working dir written by `auryn quickstart` (e.g. quickstart/.auryn/)
18
+ .auryn/
19
+
20
+ # .NET build output (roslyn-extractor tool + C# test fixtures)
21
+ bin/
22
+ obj/
23
+
24
+ # Demo sample repos are generated by their setup.py / run_demo.py
25
+ demo/csharp-git/sample-repo/
26
+
27
+
28
+ # Stray FalkorDB/Redis snapshot (regenerated at runtime; never upload)
29
+ dump.rdb
30
+ *.rdb
31
+
32
+ # Deploy bundles (build artifacts)
33
+ auryn-plsql-deploy.zip
34
+ auryn-deploy.zip
35
+
36
+ # Agent-benchmark run outputs (per-run JSON logs, captured claude-config, transcripts)
37
+ benchmarks/agent/results/
38
+ benchmarks/agent/results-swe/
39
+ benchmarks/agent/results-corpus/
40
+ benchmarks/agent/results-abcd-easy/
41
+ benchmarks/agent/results-abcd-hard/
42
+ benchmarks/hook/results/
43
+ benchmarks/results/
44
+
45
+ # macOS Finder metadata
46
+ .DS_Store
47
+
48
+ # Local operator docs (client/prospect restore & VM setup) — never publish
49
+ RESTORE-*.md
50
+ INSTALL-ON-*.md
51
+
52
+ # Private, non-public hooks / work kept out of the open-source release
53
+ private/
54
+
55
+ # WIP demo not part of the public launch (kept local)
56
+ demo/auryn-tour/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FalkorDB
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.5
2
+ Name: auryn-terraform
3
+ Version: 0.8.3
4
+ Summary: Terraform/OpenTofu plugin for Auryn and the cloud-topology producer of the deployment & infrastructure tier (ADR 0007). Parses HCL (.tf) into Resource nodes (resource/module/data) and DEPENDS_ON edges from interpolation refs, plus the seams: a container image RUNS_IMAGE the shared Image hub, rds -> Database, aws_ecr_repository -> Registry (PROVISIONS). A deploy-terraform enrichment runs the shared image lifecycle. Composes with docker/compose/k8s onto the same hub. Depends on auryn-core + python-hcl2.
5
+ Author-email: Roi Lipman <roi.lipman@falkordb.com>
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: auryn-core
10
+ Requires-Dist: python-hcl2>=4.3
11
+ Description-Content-Type: text/markdown
12
+
13
+ # auryn-terraform
14
+
15
+ Terraform/OpenTofu plugin for Auryn and the cloud-topology producer of the deployment & infrastructure tier (ADR 0007). Parses HCL (`.tf`) into Resource nodes (resource/module/data) and DEPENDS_ON edges from interpolation references, plus the cross-tier seams: a container image in a resource RUNS_IMAGE the shared Image hub; `aws_db_instance`/rds → Database and `aws_ecr_repository` → Registry (PROVISIONS). A `deploy-terraform` enrichment runs the shared image lifecycle. Composes with auryn-docker/auryn-compose/auryn-k8s onto the same hub. Depends on auryn-core and python-hcl2.
16
+
17
+ Part of [Auryn](https://github.com/FalkorDB/Auryn), which turns a codebase into a queryable knowledge graph for AI agents.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install falkordb-auryn # Auryn with every plugin
23
+ pip install "auryn-core[terraform]" # Auryn with only this plugin
24
+ ```
25
+
26
+ ## License
27
+
28
+ MIT. See the [LICENSE](https://github.com/FalkorDB/Auryn/blob/main/packages/terraform/LICENSE).
@@ -0,0 +1,16 @@
1
+ # auryn-terraform
2
+
3
+ Terraform/OpenTofu plugin for Auryn and the cloud-topology producer of the deployment & infrastructure tier (ADR 0007). Parses HCL (`.tf`) into Resource nodes (resource/module/data) and DEPENDS_ON edges from interpolation references, plus the cross-tier seams: a container image in a resource RUNS_IMAGE the shared Image hub; `aws_db_instance`/rds → Database and `aws_ecr_repository` → Registry (PROVISIONS). A `deploy-terraform` enrichment runs the shared image lifecycle. Composes with auryn-docker/auryn-compose/auryn-k8s onto the same hub. Depends on auryn-core and python-hcl2.
4
+
5
+ Part of [Auryn](https://github.com/FalkorDB/Auryn), which turns a codebase into a queryable knowledge graph for AI agents.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install falkordb-auryn # Auryn with every plugin
11
+ pip install "auryn-core[terraform]" # Auryn with only this plugin
12
+ ```
13
+
14
+ ## License
15
+
16
+ MIT. See the [LICENSE](https://github.com/FalkorDB/Auryn/blob/main/packages/terraform/LICENSE).
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "auryn-terraform"
3
+ version = "0.8.3"
4
+ description = "Terraform/OpenTofu plugin for Auryn and the cloud-topology producer of the deployment & infrastructure tier (ADR 0007). Parses HCL (.tf) into Resource nodes (resource/module/data) and DEPENDS_ON edges from interpolation refs, plus the seams: a container image RUNS_IMAGE the shared Image hub, rds -> Database, aws_ecr_repository -> Registry (PROVISIONS). A deploy-terraform enrichment runs the shared image lifecycle. Composes with docker/compose/k8s onto the same hub. Depends on auryn-core + python-hcl2."
5
+ readme = "README.md"
6
+ authors = [{ name = "Roi Lipman", email = "roi.lipman@falkordb.com" }]
7
+ requires-python = ">=3.12"
8
+ license = { text = "MIT" }
9
+ dependencies = [
10
+ "auryn-core",
11
+ "python-hcl2>=4.3",
12
+ ]
13
+
14
+ [project.entry-points."auryn.languages"]
15
+ terraform = "auryn.ingestors.terraform.plugin"
16
+
17
+ [project.entry-points."auryn.enrichments"]
18
+ deploy-terraform = "auryn.ingestors.terraform.enrichment"
19
+
20
+ [build-system]
21
+ requires = ["hatchling"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/auryn"]
26
+
27
+ [tool.uv.sources]
28
+ auryn-core = { workspace = true }
@@ -0,0 +1,84 @@
1
+ """Turn parsed Terraform into the deployment-tier graph (ADR 0007): File -> Resource; resources
2
+ DEPENDS_ON the resources they reference (within the same MODULE -- a directory), a container image in
3
+ a resource RUNS_IMAGE the shared `Image` hub, and an rds/ecr RESOURCE (not a data-source lookup)
4
+ PROVISIONS a `Database`/`Registry`.
5
+
6
+ Emits no cross-artifact edge beyond the shared `Image` hub; the `deploy-terraform` enrichment runs the
7
+ image lifecycle."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import posixpath
12
+ from collections.abc import Iterator
13
+
14
+ from auryn.core.graph_model import GraphEdge, GraphNode
15
+ from auryn.core.image_ref import image_id, image_node
16
+ from auryn.ingestors.terraform import ids
17
+ from auryn.ingestors.terraform.model import ParsedTf
18
+
19
+ _DB_TYPES = frozenset({
20
+ "aws_db_instance", "aws_rds_cluster", "aws_rds_cluster_instance", "aws_dynamodb_table",
21
+ "google_sql_database_instance", "azurerm_postgresql_server", "azurerm_postgresql_flexible_server",
22
+ "azurerm_mysql_server", "azurerm_mysql_flexible_server", "azurerm_cosmosdb_account",
23
+ })
24
+ _REGISTRY_TYPES = frozenset({
25
+ "aws_ecr_repository", "google_artifact_registry_repository", "azurerm_container_registry",
26
+ })
27
+
28
+
29
+ def _category(b) -> str:
30
+ if b.block_type != "resource":
31
+ return b.block_type # "data" | "module"
32
+ if b.rtype in _DB_TYPES:
33
+ return "database"
34
+ if b.rtype in _REGISTRY_TYPES:
35
+ return "registry"
36
+ return "compute"
37
+
38
+
39
+ def build_graph(files: list[tuple[str, ParsedTf]], proj_id: str) -> Iterator[GraphNode | GraphEdge]:
40
+ # Per-MODULE (directory) index: a `${aws_x.y...}` reference resolves to a block in the SAME module,
41
+ # and same-named resources in different modules (`env/dev` vs `env/prod`) stay distinct.
42
+ by_module: dict[str, dict[str, str]] = {}
43
+ for rel, parsed in files:
44
+ md = posixpath.dirname(rel)
45
+ idx = by_module.setdefault(md, {})
46
+ for b in parsed.blocks:
47
+ idx[b.address] = ids.resource_id(proj_id, md, b.address)
48
+
49
+ for rel_path, parsed in files:
50
+ md = posixpath.dirname(rel_path)
51
+ idx = by_module.get(md, {})
52
+ fid = ids.file_id(proj_id, rel_path)
53
+ yield GraphNode("File", {"id": fid}, {"path": rel_path, "name": posixpath.basename(rel_path)})
54
+ yield GraphEdge("HAS_FILE", "Project", {"id": proj_id}, "File", {"id": fid})
55
+
56
+ for b in parsed.blocks:
57
+ rid = ids.resource_id(proj_id, md, b.address)
58
+ yield GraphNode("Resource", {"id": rid}, {
59
+ "block_type": b.block_type, "rtype": b.rtype, "name": b.name,
60
+ "address": b.address, "module": md, "category": _category(b),
61
+ })
62
+ yield GraphEdge("HAS_RESOURCE", "File", {"id": fid}, "Resource", {"id": rid})
63
+
64
+ for ref in b.images:
65
+ yield image_node(ref)
66
+ yield GraphEdge("RUNS_IMAGE", "Resource", {"id": rid}, "Image", {"id": image_id(ref)})
67
+
68
+ # A `data` source is a READ of existing infra -- it does not PROVISION anything.
69
+ if b.block_type == "resource":
70
+ if b.rtype in _DB_TYPES:
71
+ did = ids.database_id(proj_id, md, b.address)
72
+ yield GraphNode("Database", {"id": did}, {"name": b.name, "rtype": b.rtype})
73
+ yield GraphEdge("PROVISIONS", "Resource", {"id": rid}, "Database", {"id": did})
74
+ elif b.rtype in _REGISTRY_TYPES:
75
+ reg = ids.registry_id(proj_id, md, b.address)
76
+ yield GraphNode("Registry", {"id": reg}, {"name": b.name, "rtype": b.rtype})
77
+ yield GraphEdge("PROVISIONS", "Resource", {"id": rid}, "Registry", {"id": reg})
78
+
79
+ for b in parsed.blocks:
80
+ rid = ids.resource_id(proj_id, md, b.address)
81
+ for ref in b.refs:
82
+ target = idx.get(ref) # same-module resolution
83
+ if target and target != rid:
84
+ yield GraphEdge("DEPENDS_ON", "Resource", {"id": rid}, "Resource", {"id": target})
@@ -0,0 +1,13 @@
1
+ """The `deploy-terraform` stitch registration -- the `auryn.enrichments` entry-point target (ADR 0007).
2
+ Import-light: `stitch` pulls in only core graph helpers (no hcl2)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from auryn.core.registry import GraphEnrichment, register_graph_enrichment
7
+ from auryn.ingestors.terraform.stitch import run as _run
8
+
9
+ # order 130 > docker/compose/k8s arms, so BUILDS_IMAGE edges already exist when image `resolved` is
10
+ # recomputed over the shared hub.
11
+ register_graph_enrichment(GraphEnrichment(name="deploy-terraform", run=_run, order=130))
12
+
13
+ __all__ = ["_run"]
@@ -0,0 +1,291 @@
1
+ """Parse Terraform/OpenTofu (`.tf`) -> `ParsedTf` via python-hcl2.
2
+
3
+ hcl2 v4 emits block labels as quoted strings and keeps attribute values in HCL form (`"x"`, `${ref}`),
4
+ with an `__is_block__` marker -- so we unquote labels, scan string values for `${...}` references
5
+ (-> DEPENDS_ON) and for container image refs (-> the hub seam). Best-effort and never fatal: a file
6
+ that fails to parse yields nothing (git_sync logs it)."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import re
12
+
13
+ import hcl2
14
+
15
+ from auryn.ingestors.terraform.model import Block, ParsedTf
16
+
17
+ # A Terraform reference: a resource (`type.name`, type has an underscore), a module (`module.name`),
18
+ # or a data source (`data.type.name`). `var.`/`local.` are intentionally NOT blocks.
19
+ _REF = re.compile(
20
+ r"(?<![\w.])(module\.[A-Za-z_][\w-]*|data\.[A-Za-z_]\w*\.[A-Za-z_][\w-]*|[A-Za-z_]\w*_[A-Za-z_]\w*\.[A-Za-z_][\w-]*)"
21
+ )
22
+ # `image = "x"` / `"image": "x"` inside a serialized blob (e.g. a container_definitions jsonencode).
23
+ # The value may itself be an interpolation (`"${ecr_url}:tag"`) -- keep it whole; the shared
24
+ # `image_node` flags it unresolved. It is bounded by the surrounding quotes, so stop only at a quote
25
+ # or whitespace (an image ref never contains either).
26
+ _IMAGE = re.compile(r'"?image(?:_uri)?"?\s*[:=]\s*"([^"\s]+)"')
27
+
28
+
29
+ def _interpolations(s: str):
30
+ """Yield the CONTENT of each top-level `${...}` in `s`, brace-BALANCED and QUOTE-aware (so a
31
+ `}` inside a quoted argument -- `${lookup(x, "a}b")}` -- does not end the interpolation early)
32
+ and skipping an escaped `$${` (which Terraform treats as a literal `${`). References live only
33
+ here -- a quoted string literal like `"aws_x.y"` is NOT an interpolation and must not fabricate
34
+ a reference (see `_expr_refs`)."""
35
+ i, n = 0, len(s)
36
+ while i < n - 1:
37
+ if s[i] == "$" and s[i + 1] == "{":
38
+ if i > 0 and s[i - 1] == "$": # `$${` -> literal, not an interpolation
39
+ i += 2
40
+ continue
41
+ depth, j, in_str, esc = 1, i + 2, False, False
42
+ while j < n and depth:
43
+ c = s[j]
44
+ if esc:
45
+ esc = False
46
+ elif c == "\\":
47
+ esc = True
48
+ elif in_str:
49
+ in_str = c != '"'
50
+ elif c == '"':
51
+ in_str = True
52
+ elif c == "{":
53
+ depth += 1
54
+ elif c == "}":
55
+ depth -= 1
56
+ j += 1
57
+ yield s[i + 2 : j - 1]
58
+ i = j
59
+ else:
60
+ i += 1
61
+
62
+
63
+ def _split_quoted(s: str):
64
+ """Yield `(segment, is_quoted)` runs of `s`, splitting on double-quoted spans (respecting an
65
+ escaped `\\"`). A quoted segment is the text BETWEEN the quotes; surrounding expression text
66
+ comes back as `is_quoted=False`."""
67
+ i, n, start = 0, len(s), 0
68
+ while i < n:
69
+ if s[i] == '"':
70
+ if i > start:
71
+ yield s[start:i], False
72
+ j = i + 1
73
+ while j < n and s[j] != '"':
74
+ j += 2 if s[j] == "\\" else 1
75
+ yield s[i + 1 : j], True
76
+ i = start = j + 1
77
+ else:
78
+ i += 1
79
+ if start < n:
80
+ yield s[start:], False
81
+
82
+
83
+ def _expr_refs(content: str):
84
+ """Addresses referenced in an interpolation's EXPRESSION. A quoted string literal is not an
85
+ expression -- its literal text (even if it looks like `aws_x.y`) can't be a reference -- but a
86
+ string may embed further `${...}` interpolations, which ARE expressions, so recurse into those."""
87
+ for seg, quoted in _split_quoted(content):
88
+ if quoted:
89
+ for inner in _interpolations(seg): # a nested ${...} inside the string literal
90
+ yield from _expr_refs(inner)
91
+ else:
92
+ yield from _REF.findall(seg)
93
+
94
+
95
+ def _unq(s):
96
+ return s[1:-1] if isinstance(s, str) and len(s) >= 2 and s[0] == '"' and s[-1] == '"' else s
97
+
98
+
99
+ def _meta_key(k) -> bool:
100
+ """hcl2 v4 injects bookkeeping keys (`__is_block__`, `__start_line__`, comments, ...) -- skip any
101
+ `__`-prefixed key so metadata is never scanned as Terraform data."""
102
+ return isinstance(k, str) and k.startswith("__")
103
+
104
+
105
+ def _strings(v):
106
+ """Every string leaf under an attribute value (dicts/lists walked; hcl2 metadata keys skipped)."""
107
+ if isinstance(v, str):
108
+ yield v
109
+ elif isinstance(v, dict):
110
+ for k, x in v.items():
111
+ if not _meta_key(k):
112
+ yield from _strings(x)
113
+ elif isinstance(v, list):
114
+ for x in v:
115
+ yield from _strings(x)
116
+
117
+
118
+ def _address(ref: str) -> str:
119
+ parts = ref.split(".")
120
+ if ref.startswith("module."):
121
+ return f"module.{parts[1]}"
122
+ if ref.startswith("data."):
123
+ return f"data.{parts[1]}.{parts[2]}"
124
+ return f"{parts[0]}.{parts[1]}" # resource: type.name
125
+
126
+
127
+ def _refs(attrs: dict, self_address: str) -> tuple[str, ...]:
128
+ out: dict[str, None] = {}
129
+ for s in _strings(attrs):
130
+ for interp in _interpolations(s): # only ${...} content, not plain string literals
131
+ for m in _expr_refs(interp): # ... and only the EXPRESSION, not quoted literals within
132
+ addr = _address(m)
133
+ if addr != self_address:
134
+ out.setdefault(addr, None)
135
+ return tuple(out)
136
+
137
+
138
+ # Container-RUNTIME resources whose root carries a top-level `image` with no nested container block.
139
+ # An explicit allow-list, NOT an `endswith("_container")` test -- `azurerm_storage_container` and the
140
+ # like manage storage, not workloads, and must not have a `metadata.image` read as a container image.
141
+ _CONTAINER_RESOURCE_TYPES = frozenset({"docker_container", "podman_container"})
142
+
143
+ # Image-ref attributes that are container-specific wherever they appear: Lambda/ECS `image_uri`, App
144
+ # Runner's `source_configuration.image_repository.image_identifier`.
145
+ _IMAGE_ATTRS = frozenset({"image_uri", "image_identifier"})
146
+
147
+ # Nested block keys that open a container context for a bare `image` (Cloud Run `template.containers`,
148
+ # the k8s provider's `spec.container` / `spec.init_container`).
149
+ _CONTAINER_BLOCK_KEYS = frozenset({"container", "containers", "init_container"})
150
+
151
+
152
+ def _is_container_resource(rtype: str) -> bool:
153
+ """Whether a resource TYPE denotes a container runtime whose root attributes ARE a container context
154
+ (the Docker provider's `docker_container` carries a top-level `image` with no nested block)."""
155
+ return rtype in _CONTAINER_RESOURCE_TYPES
156
+
157
+
158
+ def _literal_only(value: str) -> str:
159
+ """`value` with every `${...}` interpolation removed (brace-balanced, quote-aware, skipping an
160
+ escaped `$${`). Non-empty iff the value has a concrete LITERAL part: `"${ecr.url}:1.0"` -> `:1.0`,
161
+ but a pure `"${var.x}"` or a regex-truncated `"${format("` -> ``."""
162
+ out, i, n = [], 0, len(value)
163
+ while i < n:
164
+ if value[i] == "$" and i + 1 < n and value[i + 1] == "{" and not (i > 0 and value[i - 1] == "$"):
165
+ depth, j, in_str, esc = 1, i + 2, False, False
166
+ while j < n and depth:
167
+ c = value[j]
168
+ if esc:
169
+ esc = False
170
+ elif c == "\\":
171
+ esc = True
172
+ elif in_str:
173
+ in_str = c != '"'
174
+ elif c == '"':
175
+ in_str = True
176
+ elif c == "{":
177
+ depth += 1
178
+ elif c == "}":
179
+ depth -= 1
180
+ j += 1
181
+ i = j
182
+ else:
183
+ out.append(value[i])
184
+ i += 1
185
+ return "".join(out)
186
+
187
+
188
+ def _is_materializable_image(img: str) -> bool:
189
+ """Materialize an image only if it has a concrete LITERAL component. A pure interpolation
190
+ (`${var.api_image}`, `${format(...)}`) can never resolve to -- or join -- a concrete hub image, so
191
+ it is dropped (and a regex-truncated blob value like `${format(` is dropped with it); an
192
+ interpolation with literal text (`${ecr.url}:1.0`, tag `:1.0`) IS materialized, flagged unresolved."""
193
+ return bool(_literal_only(img).strip())
194
+
195
+
196
+ def _collect_image_keys(v, out: dict, in_container: bool = False) -> None:
197
+ """Find CONTAINER image refs at any nesting. An `_IMAGE_ATTRS` key (`image_uri`/`image_identifier`)
198
+ is container-specific, so collected anywhere; a bare `image` is collected ONLY inside a container
199
+ context -- a `_CONTAINER_BLOCK_KEYS` block (Cloud Run's `template.containers.image`, the k8s
200
+ provider's `spec.container`/`spec.init_container`) or a container-runtime resource root. So a VM boot
201
+ disk's `boot_disk.initialize_params.image` is NOT mistaken for a container image, and a metadata map
202
+ keyed `container_owner` does NOT turn the context on (the key must BE one of the block keys, not
203
+ merely contain the word). Interpolated (`${...}`) values are KEPT -- `image_node` flags them
204
+ unresolved -- so `image_uri = "${ecr...}:tag"` still yields an Image."""
205
+ if isinstance(v, dict):
206
+ for k, x in v.items():
207
+ if _meta_key(k):
208
+ continue
209
+ if (k in _IMAGE_ATTRS or (k == "image" and in_container)) and isinstance(x, str):
210
+ img = _unq(x)
211
+ if img and _is_materializable_image(img):
212
+ out.setdefault(img, None)
213
+ else:
214
+ child_container = in_container or (isinstance(k, str) and k.lower() in _CONTAINER_BLOCK_KEYS)
215
+ _collect_image_keys(x, out, child_container)
216
+ elif isinstance(v, list):
217
+ for x in v:
218
+ _collect_image_keys(x, out, in_container)
219
+
220
+
221
+ # Attributes that carry a serialized container spec (an ECS `container_definitions = jsonencode([...])`
222
+ # blob). The `_IMAGE` text scan runs ONLY over these -- scanning every string leaf would read an
223
+ # `image = "..."` line inside an unrelated `user_data` script as a container image.
224
+ _BLOB_KEYS = frozenset({"container_definitions"})
225
+
226
+
227
+ def _blob_strings(v):
228
+ """String leaves under a `_BLOB_KEYS` attribute, at any nesting (the blob is usually a top-level
229
+ attribute, but search defensively)."""
230
+ if isinstance(v, dict):
231
+ for k, x in v.items():
232
+ if _meta_key(k):
233
+ continue
234
+ yield from (_strings(x) if isinstance(k, str) and k in _BLOB_KEYS else _blob_strings(x))
235
+ elif isinstance(v, list):
236
+ for x in v:
237
+ yield from _blob_strings(x)
238
+
239
+
240
+ def _images(attrs: dict, rtype: str = "") -> tuple[str, ...]:
241
+ """CONTAINER images a resource runs. Scope boundary (best-effort, not a full HCL evaluator): an
242
+ image is materialized only when it has a LITERAL component -- a plain ref (`"shop/api:1.0"`) or an
243
+ interpolation with literal text (`"${ecr.url}:1.0"`, kept unresolved). A bare variable-only value
244
+ (`image = var.api_image`) is NOT materialized: it has no literal to key on and can never resolve to
245
+ or join a concrete hub image. Deeply nested interpolation-in-quoted-string expressions
246
+ (`${coalesce("${upper("}")}", ...)`) are likewise out of scope for the state-machine scanner."""
247
+ out: dict[str, None] = {}
248
+ _collect_image_keys(attrs, out, _is_container_resource(rtype)) # structured image keys at any depth
249
+ for s in _blob_strings(attrs): # + images inside a container_definitions jsonencode blob
250
+ for m in _IMAGE.findall(s):
251
+ if _is_materializable_image(m):
252
+ out.setdefault(m, None)
253
+ return tuple(out)
254
+
255
+
256
+ def _blocks(doc: dict, block_type: str) -> list[Block]:
257
+ out: list[Block] = []
258
+ for entry in doc.get(block_type, []):
259
+ if not isinstance(entry, dict):
260
+ continue
261
+ if block_type == "module":
262
+ for name, attrs in entry.items():
263
+ attrs = attrs if isinstance(attrs, dict) else {}
264
+ addr = f"module.{_unq(name)}"
265
+ out.append(Block("module", "", _unq(name), addr, _refs(attrs, addr), _images(attrs)))
266
+ else: # resource | data
267
+ for rtype, named in entry.items():
268
+ if not isinstance(named, dict):
269
+ continue
270
+ rtype = _unq(rtype)
271
+ for name, attrs in named.items():
272
+ attrs = attrs if isinstance(attrs, dict) else {}
273
+ name = _unq(name)
274
+ addr = f"{rtype}.{name}" if block_type == "resource" else f"data.{rtype}.{name}"
275
+ out.append(Block(block_type, rtype, name, addr, _refs(attrs, addr), _images(attrs, rtype)))
276
+ return out
277
+
278
+
279
+ def parse_source(data: str | bytes) -> ParsedTf:
280
+ if isinstance(data, bytes):
281
+ data = data.decode("utf-8", errors="replace")
282
+ try:
283
+ doc = hcl2.load(io.StringIO(data))
284
+ except Exception:
285
+ return ParsedTf()
286
+ if not isinstance(doc, dict):
287
+ return ParsedTf()
288
+ blocks: list[Block] = []
289
+ for bt in ("resource", "data", "module"):
290
+ blocks.extend(_blocks(doc, bt))
291
+ return ParsedTf(tuple(blocks))
@@ -0,0 +1,98 @@
1
+ """Git-tracked (and directory) Terraform ingestion: fully recompute the project's Terraform subgraph
2
+ at `target_sha` and diff it onto the graph (graph_sync.stream_apply). v1 is full-recompute. Registered
3
+ as the `terraform` GitLanguage by the import-light plugin.py."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import itertools
8
+ import logging
9
+ import time
10
+ from dataclasses import dataclass
11
+
12
+ from auryn.core.graph_model import GraphNode
13
+ from auryn.core.graph_sync import stream_apply
14
+ from auryn.core.registry import LanguageIngestResult
15
+ from auryn.ingestors.terraform.build import build_graph
16
+ from auryn.ingestors.terraform.file_parser import parse_source
17
+ from auryn.ingestors.terraform.ids import project_id
18
+ from auryn.ingestors.terraform.plugin import EXCLUDED_DIR_NAMES as _EXCLUDED_DIR_NAMES
19
+ from auryn.ingestors.terraform.plugin import MATCH_PATTERNS as _MATCH_PATTERNS
20
+ from auryn.ingestors.terraform.schema import NODE_SCHEMAS, OWNED_LABELS
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass
26
+ class SyncStats:
27
+ nodes_added: int = 0
28
+ nodes_updated: int = 0
29
+ nodes_removed: int = 0
30
+ edges_added: int = 0
31
+ edges_updated: int = 0
32
+ edges_removed: int = 0
33
+ commit_sha: str = ""
34
+ elapsed_seconds: float = 0.0
35
+ files_parsed: int = 0
36
+ files_cached: int = 0
37
+
38
+
39
+ def sync_at(writer, source, target_sha: str, *, project_name: str, repo_uri: str, ref: str | None) -> SyncStats:
40
+ started = time.monotonic()
41
+ proj_id = project_id(project_name)
42
+
43
+ writer.setup_schema(NODE_SCHEMAS)
44
+ prior_sha = writer.get_property("Project", {"id": proj_id}, "commit_sha")
45
+ if prior_sha == target_sha: # tier-wide limitation: ignores source file-selection (see k8s git_sync)
46
+ return SyncStats(commit_sha=target_sha, elapsed_seconds=time.monotonic() - started)
47
+
48
+ all_files = dict(source.list_files_glob(target_sha, _MATCH_PATTERNS, set(_EXCLUDED_DIR_NAMES)))
49
+ # OpenTofu precedence: in a directory a `<name>.tofu` OVERRIDES the sibling `<name>.tf` (the `.tf` is
50
+ # ignored), so drop a `.tf` whenever its `.tofu` twin is present -- otherwise both parse and the same
51
+ # resource address yields a duplicate node.
52
+ tofu_stems = {p.rsplit(".", 1)[0] for p in all_files if p.endswith(".tofu")}
53
+ seen = {p: sha for p, sha in all_files.items()
54
+ if not (p.endswith(".tf") and p.rsplit(".", 1)[0] in tofu_stems)}
55
+
56
+ files = []
57
+ for path, blob_sha in sorted(seen.items()):
58
+ try:
59
+ parsed = parse_source(source.read_blob(blob_sha))
60
+ except Exception:
61
+ logger.warning("failed to parse %s (its nodes are removed this sync)", path, exc_info=True)
62
+ continue
63
+ if parsed.blocks:
64
+ files.append((path, parsed))
65
+
66
+ # (a Project node without a stamp is a sync that died mid-apply, not "never ingested")
67
+ if not files and prior_sha is None and not writer.node_exists("Project", proj_id):
68
+ return SyncStats(commit_sha=target_sha, elapsed_seconds=time.monotonic() - started)
69
+
70
+ project_node = GraphNode(
71
+ "Project", {"id": proj_id},
72
+ {"name": project_name, "repo_uri": repo_uri, "commit_sha": target_sha, "ref": ref},
73
+ )
74
+
75
+ def make_target():
76
+ return itertools.chain(build_graph(files, proj_id), [project_node])
77
+
78
+ stats, _r, _p = stream_apply(writer, proj_id, OWNED_LABELS, make_target)
79
+ elapsed = time.monotonic() - started
80
+ logger.info("terraform: %d .tf file(s), +%dn/%de in %.2fs", len(files), stats.nodes_added, stats.edges_added, elapsed)
81
+ return SyncStats(
82
+ nodes_added=stats.nodes_added, nodes_updated=stats.nodes_updated, nodes_removed=stats.nodes_removed,
83
+ edges_added=stats.edges_added, edges_updated=stats.edges_updated, edges_removed=stats.edges_removed,
84
+ commit_sha=target_sha, elapsed_seconds=elapsed, files_parsed=len(files),
85
+ )
86
+
87
+
88
+ def _git_language_sync(
89
+ writer, source, target_sha: str, *, repo_uri: str, project_name: str,
90
+ solution_name: str | None, ref: str | None, cache_root=None,
91
+ ) -> LanguageIngestResult:
92
+ s = sync_at(writer, source, target_sha, project_name=project_name, repo_uri=repo_uri, ref=ref)
93
+ return LanguageIngestResult(
94
+ nodes_added=s.nodes_added, nodes_updated=s.nodes_updated, nodes_removed=s.nodes_removed,
95
+ edges_added=s.edges_added, edges_updated=s.edges_updated, edges_removed=s.edges_removed,
96
+ files_parsed=s.files_parsed, files_cached=s.files_cached,
97
+ commit_sha=s.commit_sha, elapsed_seconds=s.elapsed_seconds,
98
+ )
@@ -0,0 +1,42 @@
1
+ """Canonical id scheme for the Terraform graph (ADR 0007 §2). A `Resource` is keyed by its Terraform
2
+ address within its MODULE directory (`terraform://<project>/<module-dir>/<address>`, or
3
+ `terraform://<project>/<address>` at the root). The shared `Image` hub keys via `core.image_ref`, so a
4
+ resource that runs an image converges with the other producers."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from auryn.core.image_ref import image_id # re-exported
9
+
10
+ __all__ = ["project_id", "file_id", "resource_id", "database_id", "registry_id", "image_id"]
11
+
12
+
13
+ def project_id(project_name: str) -> str:
14
+ return f"terraform://{project_name}"
15
+
16
+
17
+ def file_id(proj_id: str, rel_path: str) -> str:
18
+ rel = rel_path.replace(chr(92), "/")
19
+ while rel.startswith("./"):
20
+ rel = rel[2:]
21
+ return f"{proj_id}/file/{rel}"
22
+
23
+
24
+ def _module_prefix(proj_id: str, module_dir: str) -> str:
25
+ # A Terraform MODULE is a directory: resources in `env/dev` and `env/prod` are distinct configs, so
26
+ # the module dir is part of the id -- otherwise same-named resources across modules collide.
27
+ return f"{proj_id}/{module_dir}" if module_dir else proj_id
28
+
29
+
30
+ def resource_id(proj_id: str, module_dir: str, address: str) -> str:
31
+ return f"{_module_prefix(proj_id, module_dir)}/{address}"
32
+
33
+
34
+ def database_id(proj_id: str, module_dir: str, address: str) -> str:
35
+ # Keyed off the (unique) resource id with a `#` suffix. A Terraform ADDRESS never contains `#`, so
36
+ # `<resource_id>#database` can never equal some other resource's plain id -- the provisioned node
37
+ # can't collide with a `Resource`, even one in a module dir that itself contains a `#`.
38
+ return f"{resource_id(proj_id, module_dir, address)}#database"
39
+
40
+
41
+ def registry_id(proj_id: str, module_dir: str, address: str) -> str:
42
+ return f"{resource_id(proj_id, module_dir, address)}#registry"
@@ -0,0 +1,26 @@
1
+ """Parsed Terraform/OpenTofu model (engine-agnostic). `file_parser.parse_source` produces these;
2
+ `build.build_graph` turns them into graph nodes/edges."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Block:
11
+ """A `resource` / `module` / `data` block. `address` is its Terraform address
12
+ (`aws_db_instance.db`, `module.net`, `data.aws_ami.ubuntu`) -- the id other blocks reference.
13
+ `refs` are the addresses it interpolates (`${aws_x.y.z}` -> `aws_x.y`), which become DEPENDS_ON.
14
+ `images` are container image refs found in its attributes (the hub seam)."""
15
+
16
+ block_type: str # "resource" | "module" | "data"
17
+ rtype: str # resource/data type, e.g. "aws_db_instance"; "" for a module
18
+ name: str
19
+ address: str
20
+ refs: tuple[str, ...] = ()
21
+ images: tuple[str, ...] = ()
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class ParsedTf:
26
+ blocks: tuple[Block, ...] = ()
@@ -0,0 +1,24 @@
1
+ """Import-light Terraform language registration -- the `auryn.languages` entry-point target. The lazy
2
+ `sync` thunk imports python-hcl2 only when a source contains `.tf` files."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from auryn.core.registry import GitLanguage, match_patterns, register_git_language
7
+
8
+ LANGUAGE = "terraform"
9
+ FILE_SUFFIXES = (".tf",)
10
+ FILE_GLOBS = ("*.tofu",) # OpenTofu, the Terraform fork; identical HCL
11
+ MATCH_PATTERNS = match_patterns(FILE_SUFFIXES, FILE_GLOBS)
12
+ EXCLUDED_DIR_NAMES = frozenset({".git", "node_modules", "vendor", "dist", ".idea", ".vscode", ".terraform"})
13
+
14
+
15
+ def _sync(*args, **kwargs):
16
+ from auryn.ingestors.terraform.git_sync import _git_language_sync
17
+
18
+ return _git_language_sync(*args, **kwargs)
19
+
20
+
21
+ register_git_language(
22
+ GitLanguage(language=LANGUAGE, file_suffixes=FILE_SUFFIXES, file_globs=FILE_GLOBS,
23
+ excluded_dir_names=EXCLUDED_DIR_NAMES, sync=_sync)
24
+ )
@@ -0,0 +1,30 @@
1
+ """Graph schema the Terraform producer writes (ADR 0007). A `.tf` `File` owns the `Resource` blocks it
2
+ declares; resources `DEPENDS_ON` the resources they reference, `RUNS_IMAGE` the shared `Image` hub (a
3
+ container image in the resource), and `PROVISIONS` the `Database`/`Registry` they create.
4
+
5
+ `Image` is the shared hub (MERGE-only; GC'd by the deploy arms). `Database`/`Registry` are declared
6
+ infra the ORM/registry seams can later join to."""
7
+
8
+ from __future__ import annotations
9
+
10
+ from auryn.core.graph_model import EdgeSchema, NodeSchema
11
+
12
+ NODE_SCHEMAS = [
13
+ NodeSchema(label="Project", indexed_properties=("name",)),
14
+ NodeSchema(label="File", indexed_properties=("path",)),
15
+ NodeSchema(label="Resource", indexed_properties=("address",)),
16
+ NodeSchema(label="Image", indexed_properties=("ref",)), # the shared hub
17
+ NodeSchema(label="Database", indexed_properties=("name",)),
18
+ NodeSchema(label="Registry", indexed_properties=("name",)),
19
+ ]
20
+
21
+ # Labels this producer OWNS under `terraform://<project>` and diffs on resync. `Image` is shared.
22
+ OWNED_LABELS = ["Project", "File", "Resource", "Database", "Registry"]
23
+
24
+ EDGE_SCHEMAS = [
25
+ EdgeSchema(rel_type="HAS_FILE"), # Project -> File
26
+ EdgeSchema(rel_type="HAS_RESOURCE"), # File -> Resource
27
+ EdgeSchema(rel_type="DEPENDS_ON"), # Resource -> Resource (interpolation reference)
28
+ EdgeSchema(rel_type="RUNS_IMAGE"), # Resource -> Image
29
+ EdgeSchema(rel_type="PROVISIONS"), # Resource -> Database | Registry
30
+ ]
@@ -0,0 +1,33 @@
1
+ """The `deploy-terraform` stitch (ADR 0007): the Terraform producer emits its own RUNS_IMAGE /
2
+ DEPENDS_ON / PROVISIONS edges, so this arm only runs the shared image lifecycle -- recompute each
3
+ `Image`'s `resolved` (a tf-defined ECS/Lambda running an image that docker also builds flips internal)
4
+ and GC orphan images -- so a Terraform-only repo still gets correct image state."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+
10
+ from auryn.core import deploy
11
+ from auryn.core.graph_client import GraphWriter
12
+
13
+ logger = logging.getLogger("auryn.deploy-terraform")
14
+
15
+
16
+ def run(writer: GraphWriter, repo, target_sha: str) -> dict | None:
17
+ return stitch(writer)
18
+
19
+
20
+ def stitch(writer: GraphWriter) -> dict | None:
21
+ try:
22
+ if not writer.ro_query("MATCH (i:Image) RETURN i.id LIMIT 1").result_set:
23
+ return None
24
+ except Exception as e:
25
+ if "empty key" in str(e).lower():
26
+ return None
27
+ raise
28
+ deploy.recompute_image_resolved(writer)
29
+ orphans = deploy.gc_orphan_images(writer)
30
+ if not orphans:
31
+ return None
32
+ logger.info("deploy-terraform: %d orphan image(s) GC'd", orphans)
33
+ return {"orphans_removed": orphans}