@intentius/chant-lexicon-terraform 0.124.88 → 0.124.90
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.
- package/dist/engine-runner.d.ts +86 -0
- package/dist/engine-runner.d.ts.map +1 -0
- package/dist/engine-runner.js +134 -0
- package/dist/integrity.json +2 -2
- package/dist/live-roots.d.ts +50 -0
- package/dist/live-roots.d.ts.map +1 -1
- package/dist/live-roots.js +99 -1
- package/dist/manifest.json +1 -1
- package/dist/op/command-hook.d.ts +10 -0
- package/dist/op/command-hook.d.ts.map +1 -1
- package/dist/reach.d.ts +76 -0
- package/dist/reach.d.ts.map +1 -0
- package/dist/reach.js +193 -0
- package/dist/terragrunt/run.d.ts +23 -0
- package/dist/terragrunt/run.d.ts.map +1 -1
- package/dist/terragrunt/run.js +107 -3
- package/package.json +2 -2
- package/src/engine-runner.test.ts +261 -0
- package/src/engine-runner.ts +191 -0
- package/src/live-record-store.test.ts +76 -0
- package/src/live-roots.ts +104 -1
- package/src/op/command-hook.ts +7 -0
- package/src/reach.test.ts +72 -0
- package/src/reach.ts +196 -0
- package/src/terragrunt/run.ts +128 -4
package/dist/reach.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a change reaches (#4984), beside ./changed-roots.ts: the roots,
|
|
3
|
+
* Terragrunt units, Atmos instances or synthesized roots a change from
|
|
4
|
+
* `from` to `to` reaches, read from git alone. Moved from terragucci's
|
|
5
|
+
* `reachedRoots`, `reachedUnits`, `reachedInstances` and
|
|
6
|
+
* `reachedSynthesized` (comment-apply.ts), for a product's reach line
|
|
7
|
+
* (`productPlan.reach`, #4979): the lock job and the decision before merge
|
|
8
|
+
* run it at the target branch's commit, so none of the change's code runs.
|
|
9
|
+
*
|
|
10
|
+
* Each follows what reads a reached target: a root that reads a reached
|
|
11
|
+
* root's state, a unit that names a reached unit in a `dependency` or
|
|
12
|
+
* `dependencies` block, an instance that depends on a reached one, followed
|
|
13
|
+
* through. The product hands the reads it knows (terragucci's
|
|
14
|
+
* `terraform_remote_state` edges and `waves.after`, Atmos's dependencies);
|
|
15
|
+
* the Terragrunt unit reads are parsed here, at both ends of the range.
|
|
16
|
+
* Markdown files reach nothing. When a change can reach anything, or git
|
|
17
|
+
* cannot diff the range, every target is reached and `every` says why.
|
|
18
|
+
*/
|
|
19
|
+
import { posix } from "node:path";
|
|
20
|
+
import { changedRoots } from "./changed-roots.js";
|
|
21
|
+
/** Changed files that reach nothing: documentation. */
|
|
22
|
+
export const READS_NOTHING = /\.md$/i;
|
|
23
|
+
/** The files the change from `from` to `to` changes (`git diff --name-only from...to`), or undefined when git cannot say. */
|
|
24
|
+
export function changedFilesBetween(git, from, to) {
|
|
25
|
+
const diff = git(["diff", "--name-only", "--no-renames", `${from}...${to}`]);
|
|
26
|
+
if (diff.status !== 0)
|
|
27
|
+
return undefined;
|
|
28
|
+
return diff.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
29
|
+
}
|
|
30
|
+
/** Add to `selected` every target that reads a selected one, followed through. */
|
|
31
|
+
export function followReads(selected, reads) {
|
|
32
|
+
if (!reads)
|
|
33
|
+
return;
|
|
34
|
+
for (let grew = true; grew;) {
|
|
35
|
+
grew = false;
|
|
36
|
+
for (const [target, from] of reads) {
|
|
37
|
+
if (!selected.has(target) && [...from].some((d) => selected.has(d))) {
|
|
38
|
+
selected.add(target);
|
|
39
|
+
grew = true;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const sorted = (xs) => [...new Set(xs)].sort();
|
|
45
|
+
/**
|
|
46
|
+
* The plain roots a change reaches: the roots whose files it changes, by
|
|
47
|
+
* chant's path rules (./changed-roots.ts: a root's directory, the local
|
|
48
|
+
* modules it calls, its var files), and every root that reads one of those.
|
|
49
|
+
* Every root when git cannot diff the range.
|
|
50
|
+
*/
|
|
51
|
+
export function reachedRoots(repo, git, from, to, roots, reads) {
|
|
52
|
+
const all = sorted(roots);
|
|
53
|
+
const files = changedFilesBetween(git, from, to);
|
|
54
|
+
if (files === undefined)
|
|
55
|
+
return { targets: all, every: "git could not list the files it changes" };
|
|
56
|
+
const selected = new Set(changedRoots(repo, Object.fromEntries(all.map((r) => [r, { dir: r }])), files));
|
|
57
|
+
followReads(selected, reads);
|
|
58
|
+
return { targets: [...selected].filter((r) => all.includes(r)).sort() };
|
|
59
|
+
}
|
|
60
|
+
/** The body of each top-level `<keyword> ... {` block in HCL text, braces matched, strings skipped. */
|
|
61
|
+
function hclBlocks(text, keyword) {
|
|
62
|
+
const out = [];
|
|
63
|
+
const head = new RegExp(`^\\s*${keyword}\\b[^{\\n]*\\{`, "gm");
|
|
64
|
+
for (let m = head.exec(text); m; m = head.exec(text)) {
|
|
65
|
+
let depth = 1;
|
|
66
|
+
let i = m.index + m[0].length;
|
|
67
|
+
const start = i;
|
|
68
|
+
for (let quoted = false; i < text.length && depth > 0; i++) {
|
|
69
|
+
const c = text[i];
|
|
70
|
+
if (quoted) {
|
|
71
|
+
if (c === "\\")
|
|
72
|
+
i++;
|
|
73
|
+
else if (c === '"')
|
|
74
|
+
quoted = false;
|
|
75
|
+
}
|
|
76
|
+
else if (c === '"')
|
|
77
|
+
quoted = true;
|
|
78
|
+
else if (c === "{")
|
|
79
|
+
depth++;
|
|
80
|
+
else if (c === "}")
|
|
81
|
+
depth--;
|
|
82
|
+
}
|
|
83
|
+
out.push(text.slice(start, i - 1));
|
|
84
|
+
head.lastIndex = i;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The paths a unit's `terragrunt.hcl` names in its `dependency` blocks'
|
|
90
|
+
* `config_path` and its `dependencies` block's `paths`, when each is a plain
|
|
91
|
+
* string. A path built with a function or an interpolation is not read:
|
|
92
|
+
* only Terragrunt can evaluate it, and no Terragrunt runs on a change's
|
|
93
|
+
* files before a review.
|
|
94
|
+
*/
|
|
95
|
+
export function literalTerragruntDependencies(text) {
|
|
96
|
+
const clean = text.replace(/(^|[^:"$])(#|\/\/).*$/gm, "$1");
|
|
97
|
+
const plain = /^"([^"$]*)"$/;
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const b of hclBlocks(clean, "dependency")) {
|
|
100
|
+
const m = /^\s*config_path\s*=\s*("[^"\n]*")\s*$/m.exec(b);
|
|
101
|
+
const p = m && plain.exec(m[1]);
|
|
102
|
+
if (p)
|
|
103
|
+
out.push(p[1]);
|
|
104
|
+
}
|
|
105
|
+
for (const b of hclBlocks(clean, "dependencies")) {
|
|
106
|
+
const m = /\bpaths\s*=\s*\[([^\]]*)\]/.exec(b);
|
|
107
|
+
for (const item of m ? m[1].split(",").map((x) => x.trim()).filter(Boolean) : []) {
|
|
108
|
+
const p = plain.exec(item);
|
|
109
|
+
if (p)
|
|
110
|
+
out.push(p[1]);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The Terragrunt units a change reaches. A unit is reached when a file
|
|
117
|
+
* under its directory changes (the deepest unit holding the file), and so
|
|
118
|
+
* is every unit that names a reached one with a plain path, at either end
|
|
119
|
+
* of the range. A changed file under no unit's directory (`root.hcl`, a
|
|
120
|
+
* module, a stack template) may change any unit, so it reaches every one.
|
|
121
|
+
*/
|
|
122
|
+
export function reachedUnits(git, from, to, units) {
|
|
123
|
+
const all = sorted(units);
|
|
124
|
+
const files0 = changedFilesBetween(git, from, to);
|
|
125
|
+
if (files0 === undefined)
|
|
126
|
+
return { targets: all, every: "git could not list the files it changes" };
|
|
127
|
+
const files = files0.filter((f) => !READS_NOTHING.test(f));
|
|
128
|
+
const deepest = [...all].sort((a, b) => b.length - a.length);
|
|
129
|
+
const selected = new Set();
|
|
130
|
+
for (const f of files) {
|
|
131
|
+
const u = deepest.find((d) => f.startsWith(`${d}/`));
|
|
132
|
+
if (!u)
|
|
133
|
+
return { targets: all, every: `it changes \`${f}\`, which is in no unit's directory` };
|
|
134
|
+
selected.add(u);
|
|
135
|
+
}
|
|
136
|
+
const reads = new Map();
|
|
137
|
+
for (const u of all) {
|
|
138
|
+
const deps = new Set();
|
|
139
|
+
for (const ref of [from, to]) {
|
|
140
|
+
const shown = git(["show", `${ref}:${u}/terragrunt.hcl`]);
|
|
141
|
+
if (shown.status !== 0)
|
|
142
|
+
continue;
|
|
143
|
+
for (const p of literalTerragruntDependencies(shown.stdout))
|
|
144
|
+
deps.add(posix.normalize(posix.join(u, p)).replace(/\/+$/, ""));
|
|
145
|
+
}
|
|
146
|
+
reads.set(u, deps);
|
|
147
|
+
}
|
|
148
|
+
followReads(selected, reads);
|
|
149
|
+
return { targets: [...selected].sort() };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The Atmos instances a change reaches. `componentOf` names each instance's
|
|
153
|
+
* component directory. A changed file under one reaches that component's
|
|
154
|
+
* instances; any other file (a stack manifest, a catalog, `atmos.yaml`) can
|
|
155
|
+
* change any instance's vars or backend, so it reaches every instance.
|
|
156
|
+
* Instances that read a reached one follow.
|
|
157
|
+
*/
|
|
158
|
+
export function reachedInstances(git, from, to, instances, componentOf, reads) {
|
|
159
|
+
const all = sorted(instances);
|
|
160
|
+
const files0 = changedFilesBetween(git, from, to);
|
|
161
|
+
if (files0 === undefined)
|
|
162
|
+
return { targets: all, every: "git could not list the files it changes" };
|
|
163
|
+
const files = files0.filter((f) => !READS_NOTHING.test(f));
|
|
164
|
+
const selected = new Set();
|
|
165
|
+
for (const f of files) {
|
|
166
|
+
const owners = all.filter((r) => {
|
|
167
|
+
const c = componentOf.get(r)?.replace(/\/+$/, "");
|
|
168
|
+
return c !== undefined && f.startsWith(`${c}/`);
|
|
169
|
+
});
|
|
170
|
+
if (owners.length === 0)
|
|
171
|
+
return { targets: all, every: `it changes \`${f}\`, which can change any Atmos instance` };
|
|
172
|
+
for (const r of owners)
|
|
173
|
+
selected.add(r);
|
|
174
|
+
}
|
|
175
|
+
followReads(selected, reads);
|
|
176
|
+
return { targets: [...selected].sort() };
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The roots a change reaches when a command writes them (`synth`, CDK
|
|
180
|
+
* Terrain's stacks). The roots are not in git, so no diff names them, and
|
|
181
|
+
* the command is the change's own code: any changed file that is not
|
|
182
|
+
* Markdown can change any root.
|
|
183
|
+
*/
|
|
184
|
+
export function reachedSynthesized(git, from, to, roots) {
|
|
185
|
+
const all = sorted(roots);
|
|
186
|
+
const files = changedFilesBetween(git, from, to);
|
|
187
|
+
if (files === undefined)
|
|
188
|
+
return { targets: all, every: "git could not list the files it changes" };
|
|
189
|
+
const file = files.find((f) => !READS_NOTHING.test(f));
|
|
190
|
+
if (file === undefined)
|
|
191
|
+
return { targets: [] };
|
|
192
|
+
return { targets: all, every: `it changes \`${file}\`, and the synth command writes every root from the repo's files` };
|
|
193
|
+
}
|
package/dist/terragrunt/run.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* acceptance test runs the real binary.
|
|
7
7
|
*/
|
|
8
8
|
import type { ChangeSetPart, ChangeSetPlanner } from "@intentius/chant/change-set";
|
|
9
|
+
import type { TerraformCommandHook } from "../op/command-hook.js";
|
|
9
10
|
import { type TerragruntFindOptions, type TerragruntUnit } from "./units.js";
|
|
10
11
|
import { type TerragruntMockRead } from "./mocks.js";
|
|
11
12
|
import { type TerragruntUnitResult } from "./wave.js";
|
|
@@ -75,7 +76,29 @@ export interface TerragruntWaveRunInput extends TerragruntRunOptions {
|
|
|
75
76
|
* the plan, which fails the unit with its report row as before.
|
|
76
77
|
*/
|
|
77
78
|
initTurn?: <T>(fn: () => Promise<T>) => Promise<T>;
|
|
79
|
+
/**
|
|
80
|
+
* The product's hook around each unit's plan (chant#4954), the
|
|
81
|
+
* `TerraformCommandHook` `terraform-apply` takes as `onCommand`, such as
|
|
82
|
+
* `engineTimings().onCommand`. Terragrunt runs the binary itself, so the
|
|
83
|
+
* hook is asked for every unit of the wave before `run --all`, as a `plan`
|
|
84
|
+
* command for that unit (`root` is the unit's path, `method` is `plan`).
|
|
85
|
+
* The variables it answers reach that unit's plan alone, through a
|
|
86
|
+
* `TG_TF_PATH` wrapper that matches the `-out` path Terragrunt gives it.
|
|
87
|
+
* Once the wave ends, each unit's `after` gets its time (`at`) and result
|
|
88
|
+
* from the run report. Needs `binary`: without it Terragrunt picks the
|
|
89
|
+
* binary per unit, and the hook is not called.
|
|
90
|
+
*/
|
|
91
|
+
onCommand?: TerraformCommandHook;
|
|
78
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* The `TG_TF_PATH` wrapper for one wave (chant#4954): a shell script that
|
|
95
|
+
* runs `binary` with the variables of the unit whose plan it runs.
|
|
96
|
+
* Terragrunt hands each unit's plan `-out=<out-dir>/<unit>/tfplan.tfplan`,
|
|
97
|
+
* which names the unit; every other call (init, show, output, version) runs
|
|
98
|
+
* the binary as it is. `outDirs` are the wave's plan directory as given and
|
|
99
|
+
* as its real path. Lifted from terragucci's `unitWrapper` (report/stage.ts).
|
|
100
|
+
*/
|
|
101
|
+
export declare function terragruntUnitWrapper(binary: string, outDirs: readonly string[], units: ReadonlyMap<string, Record<string, string>>): string;
|
|
79
102
|
/**
|
|
80
103
|
* Thrown when a wave's plans would read `mock_outputs` (#3416). Nothing in
|
|
81
104
|
* the wave was planned, so there is nothing to gate. `reads` names each unit,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/terragrunt/run.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/terragrunt/run.ts"],"names":[],"mappings":"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"}
|
package/dist/terragrunt/run.js
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* acceptance test runs the real binary.
|
|
7
7
|
*/
|
|
8
8
|
import { execFile } from "node:child_process";
|
|
9
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
10
|
-
import { dirname, join, resolve } from "node:path";
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
11
11
|
import { plannerForBinary } from "../change-set.js";
|
|
12
12
|
import { parseTerragruntFind, terragruntFindArgs, terragruntVersionProblem, unitPathFilter, } from "./units.js";
|
|
13
13
|
import { describeMockRefusal, failMockedParts, hasExpandedDependency, markProvisional, parseRenderedDependencies, parseTerragruntOutputs, PROVISIONAL_MARKER, terragruntMockReads, terragruntMockWarnings, terragruntOutputArgs, terragruntOutputUpstreams, terragruntRenderArgs, } from "./mocks.js";
|
|
@@ -92,6 +92,100 @@ export function terraformBinaryWarnings(dir, units, binary) {
|
|
|
92
92
|
export function terragruntPlanner(binary) {
|
|
93
93
|
return plannerForBinary(binary ?? "tofu");
|
|
94
94
|
}
|
|
95
|
+
/** A word single-quoted for `sh`. */
|
|
96
|
+
const shq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
97
|
+
/**
|
|
98
|
+
* The `TG_TF_PATH` wrapper for one wave (chant#4954): a shell script that
|
|
99
|
+
* runs `binary` with the variables of the unit whose plan it runs.
|
|
100
|
+
* Terragrunt hands each unit's plan `-out=<out-dir>/<unit>/tfplan.tfplan`,
|
|
101
|
+
* which names the unit; every other call (init, show, output, version) runs
|
|
102
|
+
* the binary as it is. `outDirs` are the wave's plan directory as given and
|
|
103
|
+
* as its real path. Lifted from terragucci's `unitWrapper` (report/stage.ts).
|
|
104
|
+
*/
|
|
105
|
+
export function terragruntUnitWrapper(binary, outDirs, units) {
|
|
106
|
+
const lines = [
|
|
107
|
+
"#!/bin/sh",
|
|
108
|
+
"# chant: each unit's plan runs with the variables its command hook answered. Written for one wave.",
|
|
109
|
+
'out=""',
|
|
110
|
+
'prev=""',
|
|
111
|
+
'for a in "$@"; do',
|
|
112
|
+
' case "$a" in -out=*|--out=*) out="${a#*=}" ;; esac',
|
|
113
|
+
' if [ "$prev" = "-out" ] || [ "$prev" = "--out" ]; then out="$a"; fi',
|
|
114
|
+
' prev="$a"',
|
|
115
|
+
"done",
|
|
116
|
+
'case "$out" in',
|
|
117
|
+
];
|
|
118
|
+
for (const [unit, vars] of units) {
|
|
119
|
+
const set = Object.entries(vars).filter(([k]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(k));
|
|
120
|
+
if (set.length === 0)
|
|
121
|
+
continue;
|
|
122
|
+
const patterns = [...new Set(outDirs.map((d) => join(d, unit, "tfplan.tfplan")))].map(shq).join(" | ");
|
|
123
|
+
lines.push(` ${patterns}) export ${set.map(([k, v]) => `${k}=${shq(v)}`).join(" ")} ;;`);
|
|
124
|
+
}
|
|
125
|
+
lines.push("esac", `exec ${shq(binary)} "$@"`);
|
|
126
|
+
return lines.join("\n") + "\n";
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Ask `hook` for each unit's plan before the wave runs (chant#4954), and
|
|
130
|
+
* write the wrapper that hands each its variables when any has some.
|
|
131
|
+
* Answers the variables the run adds and what to call once the run report
|
|
132
|
+
* is read.
|
|
133
|
+
*/
|
|
134
|
+
async function unitCommandRuns(hook, input, work, outDir, waveArgs) {
|
|
135
|
+
const units = [...new Set(input.units)].sort();
|
|
136
|
+
const args = waveArgs.slice(waveArgs.indexOf("--") + 1);
|
|
137
|
+
const runs = new Map();
|
|
138
|
+
for (const unit of units) {
|
|
139
|
+
const command = {
|
|
140
|
+
root: unit,
|
|
141
|
+
method: "plan",
|
|
142
|
+
binary: input.binary,
|
|
143
|
+
name: "plan",
|
|
144
|
+
args: [...args],
|
|
145
|
+
line: [input.binary, ...args].map((w) => (/^[\w@%+=:,./-]+$/.test(w) ? w : shq(w))).join(" "),
|
|
146
|
+
cwd: resolve(input.dir, unit),
|
|
147
|
+
env: {},
|
|
148
|
+
};
|
|
149
|
+
runs.set(unit, (await hook(command)) ?? {});
|
|
150
|
+
}
|
|
151
|
+
const vars = new Map([...runs].map(([unit, run]) => [unit, run.env ?? {}]));
|
|
152
|
+
let env = {};
|
|
153
|
+
if ([...vars.values()].some((v) => Object.keys(v).length > 0)) {
|
|
154
|
+
let real = outDir;
|
|
155
|
+
try {
|
|
156
|
+
real = join(realpathSync(work), "plans");
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
// The path as given is matched alone.
|
|
160
|
+
}
|
|
161
|
+
const bin = join(work, "unit-bin");
|
|
162
|
+
mkdirSync(bin, { recursive: true });
|
|
163
|
+
// The wrapper carries the binary's name, which Terragrunt prefixes its log lines with.
|
|
164
|
+
const wrapper = join(bin, basename(input.binary) || "tofu");
|
|
165
|
+
writeFileSync(wrapper, terragruntUnitWrapper(input.binary, [outDir, real], vars));
|
|
166
|
+
chmodSync(wrapper, 0o755);
|
|
167
|
+
env = { TG_TF_PATH: wrapper };
|
|
168
|
+
}
|
|
169
|
+
const done = async (report) => {
|
|
170
|
+
for (const [unit, run] of runs) {
|
|
171
|
+
if (!run.after)
|
|
172
|
+
continue;
|
|
173
|
+
const row = report.get(unit);
|
|
174
|
+
const start = row?.started ? Date.parse(row.started) : NaN;
|
|
175
|
+
const end = row?.ended ? Date.parse(row.ended) : NaN;
|
|
176
|
+
const timed = Number.isFinite(start) && Number.isFinite(end) && end >= start;
|
|
177
|
+
const why = row && row.result !== "succeeded" ? [row.result, row.reason, row.cause].filter(Boolean).join(": ") : "";
|
|
178
|
+
await run.after({
|
|
179
|
+
code: row ? (row.result === "succeeded" ? 0 : 1) : null,
|
|
180
|
+
seconds: timed ? (end - start) / 1000 : 0,
|
|
181
|
+
stdout: "",
|
|
182
|
+
stderr: row ? why : "not in Terragrunt's run report, so it did not run",
|
|
183
|
+
...(timed ? { at: { start, end } } : {}),
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
return { env, done };
|
|
188
|
+
}
|
|
95
189
|
/**
|
|
96
190
|
* Thrown when a wave's plans would read `mock_outputs` (#3416). Nothing in
|
|
97
191
|
* the wave was planned, so there is nothing to gate. `reads` names each unit,
|
|
@@ -242,8 +336,18 @@ export async function planTerragruntWave(input) {
|
|
|
242
336
|
...(input.destroy ? { destroy: true } : {}),
|
|
243
337
|
...(input.parallelism !== undefined ? { parallelism: input.parallelism } : {}),
|
|
244
338
|
});
|
|
245
|
-
|
|
339
|
+
// chant#4954: each unit's plan goes through the product's hook, its variables through a TG_TF_PATH wrapper.
|
|
340
|
+
const units = input.onCommand && input.binary ? await unitCommandRuns(input.onCommand, { ...input, binary: input.binary }, work, outDir, args) : undefined;
|
|
341
|
+
let r;
|
|
342
|
+
try {
|
|
343
|
+
r = await exec(tg, args, { cwd: input.dir, env: { ...terragruntEnv(input.binary), ...(units?.env ?? {}) } });
|
|
344
|
+
}
|
|
345
|
+
catch (err) {
|
|
346
|
+
await units?.done(new Map());
|
|
347
|
+
throw err;
|
|
348
|
+
}
|
|
246
349
|
const report = existsSync(reportFile) ? parseTerragruntReport(readFileSync(reportFile, "utf8")) : new Map();
|
|
350
|
+
await units?.done(report);
|
|
247
351
|
const planFor = (unit) => {
|
|
248
352
|
const f = join(jsonOutDir, unit, "tfplan.json");
|
|
249
353
|
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intentius/chant-lexicon-terraform",
|
|
3
|
-
"version": "0.124.
|
|
3
|
+
"version": "0.124.90",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"src/",
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
"access": "public"
|
|
94
94
|
},
|
|
95
95
|
"peerDependencies": {
|
|
96
|
-
"@intentius/chant": "^0.124.
|
|
96
|
+
"@intentius/chant": "^0.124.90",
|
|
97
97
|
"zod": "^4.3.6"
|
|
98
98
|
},
|
|
99
99
|
"description": "terraform lexicon for chant, existing Terraform root modules as declarable entities",
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One runner of the engine for a product (chant#4954): a plan stage's own
|
|
3
|
+
* commands and each Terragrunt unit's plan reach the same `onCommand` as
|
|
4
|
+
* `terraform-apply`'s, the trace parent per command is the lexicon's, and
|
|
5
|
+
* every run (async, blocking, Terragrunt, the script chant's step runs)
|
|
6
|
+
* leaves the forge's tokens out. Fake binaries are small `sh` scripts in a
|
|
7
|
+
* temporary directory; nothing reaches a cloud, a forge or a collector.
|
|
8
|
+
*/
|
|
9
|
+
import { spawnSync } from "node:child_process";
|
|
10
|
+
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
13
|
+
import { describe, expect, test } from "vitest";
|
|
14
|
+
import { OtlpTrace } from "@intentius/chant/otlp";
|
|
15
|
+
import { commandTrace, commandTraceEnv, engineRunner, withTerraformCommandHook, type TerraformCommand, type TerraformCommandResult } from "./engine-runner";
|
|
16
|
+
import { engineTimings } from "./engine-timings";
|
|
17
|
+
import type { BinaryExec } from "./state/exec";
|
|
18
|
+
import { planTerragruntWave, terragruntUnitWrapper, type TerragruntExec } from "./terragrunt/run";
|
|
19
|
+
|
|
20
|
+
const tmp = (): string => mkdtempSync(join(tmpdir(), "chant-engine-runner-"));
|
|
21
|
+
|
|
22
|
+
/** An executable `sh` script at `path`. */
|
|
23
|
+
function script(path: string, body: string): string {
|
|
24
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
25
|
+
writeFileSync(path, `#!/bin/sh\n${body}\n`);
|
|
26
|
+
chmodSync(path, 0o755);
|
|
27
|
+
return path;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const JOB = { PATH: process.env.PATH ?? "/usr/bin:/bin", GITHUB_TOKEN: "ghs_forge", TG_TOKEN: "tg-secret", COPY: "tg-secret", TF_VAR_token: "tg-secret", KEEP: "yes" };
|
|
31
|
+
|
|
32
|
+
describe("the plan stage's own commands", () => {
|
|
33
|
+
test("go through the command hook of the call they run in, as commands for its root", async () => {
|
|
34
|
+
const seen: TerraformCommand[] = [];
|
|
35
|
+
const ran: Array<{ args: string[]; env: NodeJS.ProcessEnv }> = [];
|
|
36
|
+
const fake: BinaryExec = async (_b, args, _d, env) => {
|
|
37
|
+
ran.push({ args, env });
|
|
38
|
+
return { code: args[0] === "plan" ? 2 : 0, stdout: "out", out: "outerr" };
|
|
39
|
+
};
|
|
40
|
+
const results: TerraformCommandResult[] = [];
|
|
41
|
+
const runner = engineRunner({ tokens: ["TG_TOKEN"], exec: fake });
|
|
42
|
+
await withTerraformCommandHook(
|
|
43
|
+
(c) => {
|
|
44
|
+
seen.push(c);
|
|
45
|
+
// A hook that names a token gets it taken out all the same.
|
|
46
|
+
return { env: { HOOKED: c.name, GITHUB_TOKEN: "put-back" }, after: (r) => void results.push(r) };
|
|
47
|
+
},
|
|
48
|
+
{ root: "roots/a", method: "plan" },
|
|
49
|
+
async () => {
|
|
50
|
+
await runner.exec("tofu", ["init", "-input=false"], "/w/roots/a", { ...JOB });
|
|
51
|
+
await runner.exec("tofu", ["plan", "-detailed-exitcode"], "/w/roots/a", { ...JOB });
|
|
52
|
+
},
|
|
53
|
+
);
|
|
54
|
+
expect(seen.map((c) => [c.root, c.method, c.name])).toEqual([
|
|
55
|
+
["roots/a", "plan", "init"],
|
|
56
|
+
["roots/a", "plan", "plan"],
|
|
57
|
+
]);
|
|
58
|
+
expect(ran[1]!.env.HOOKED).toBe("plan");
|
|
59
|
+
expect(ran[1]!.env.GITHUB_TOKEN).toBeUndefined();
|
|
60
|
+
expect(ran[1]!.env.TG_TOKEN).toBeUndefined();
|
|
61
|
+
expect(ran[1]!.env.COPY).toBeUndefined();
|
|
62
|
+
expect(ran[1]!.env.TF_VAR_token).toBe("tg-secret");
|
|
63
|
+
expect(results.map((r) => r.code)).toEqual([0, 2]);
|
|
64
|
+
expect(results[1]).toMatchObject({ stdout: "out", stderr: "err" });
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("outside a hook's call the binary just runs, its tokens left out", async () => {
|
|
68
|
+
const ran: NodeJS.ProcessEnv[] = [];
|
|
69
|
+
const runner = engineRunner({ tokens: ["TG_TOKEN"], exec: async (_b, _a, _d, env) => (ran.push(env), { code: 0, stdout: "", out: "" }) });
|
|
70
|
+
await runner.exec("tofu", ["version"], "/w", { ...JOB });
|
|
71
|
+
expect(ran[0]!.KEEP).toBe("yes");
|
|
72
|
+
expect(ran[0]!.TG_TOKEN).toBeUndefined();
|
|
73
|
+
expect(runner.tokens).toEqual(expect.arrayContaining(["TG_TOKEN", "GITHUB_TOKEN"]));
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe("the blocking, Terragrunt and script runs", () => {
|
|
78
|
+
test("execSync runs the binary in its directory with TF_IN_AUTOMATION and no tokens", () => {
|
|
79
|
+
const dir = tmp();
|
|
80
|
+
const bin = script(join(dir, "bin/tofu"), 'echo "args=$*"\necho "tok=${GITHUB_TOKEN:-none} copy=${COPY:-none} tfvar=${TF_VAR_token:-none} auto=$TF_IN_AUTOMATION"\necho oops >&2\nexit 3');
|
|
81
|
+
const r = engineRunner({ tokens: ["TG_TOKEN"] }).execSync(bin, ["plan"], "/w/roots/a", { ...JOB });
|
|
82
|
+
expect(r.code).toBe(3);
|
|
83
|
+
expect(r.stdout).toContain("args=-chdir=/w/roots/a plan");
|
|
84
|
+
expect(r.stdout).toContain("tok=none copy=none tfvar=tg-secret auto=1");
|
|
85
|
+
expect(r.out).toContain("oops");
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("execSync answers 127 for a binary that is not there", () => {
|
|
89
|
+
const r = engineRunner().execSync(join(tmp(), "missing"), ["version"], "/w", { ...JOB });
|
|
90
|
+
expect(r.code).toBe(127);
|
|
91
|
+
expect(r.out).toMatch(/ENOENT/);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("terragrunt runs with the job's environment under the call's, less the tokens", async () => {
|
|
95
|
+
const dir = tmp();
|
|
96
|
+
const tg = script(join(dir, "terragrunt"), 'echo "pwd=$(pwd) tok=${GITHUB_TOKEN:-none} copy=${COPY:-none} call=$CALL"');
|
|
97
|
+
const saved = { ...process.env };
|
|
98
|
+
Object.assign(process.env, { GITHUB_TOKEN: "ghs_forge", TG_TOKEN: "tg-secret", COPY: "tg-secret" });
|
|
99
|
+
try {
|
|
100
|
+
const r = await engineRunner({ tokens: ["TG_TOKEN"] }).terragrunt(tg, ["find"], { cwd: dir, env: { CALL: "given" } });
|
|
101
|
+
expect(r.code).toBe(0);
|
|
102
|
+
expect(r.stdout).toContain("tok=none copy=none call=given");
|
|
103
|
+
} finally {
|
|
104
|
+
for (const k of ["GITHUB_TOKEN", "TG_TOKEN", "COPY"]) if (saved[k] === undefined) delete process.env[k];
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("script writes one same-named script that drops the tokens, by name and by value, and runs the binary", () => {
|
|
109
|
+
const dir = tmp();
|
|
110
|
+
const bin = script(join(dir, "real/tofu"), 'echo "tok=${GITHUB_TOKEN:-none} tg=${TG_TOKEN:-none} copy=${COPY:-none} tfvar=${TF_VAR_token:-none} keep=$KEEP args=$*"');
|
|
111
|
+
const runner = engineRunner({ tokens: ["TG_TOKEN"] });
|
|
112
|
+
const path = runner.script(join(dir, "scripts"), bin, { ...JOB });
|
|
113
|
+
expect(path.endsWith("/tofu")).toBe(true);
|
|
114
|
+
expect(runner.script(join(dir, "scripts"), bin, { ...JOB })).toBe(path);
|
|
115
|
+
const r = spawnSync(path, ["plan"], { encoding: "utf-8", env: { ...JOB } });
|
|
116
|
+
expect(r.stdout.trim()).toBe("tok=none tg=none copy=none tfvar=tg-secret keep=yes args=plan");
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("script finds a bare name on PATH, so it never runs itself", () => {
|
|
120
|
+
const dir = tmp();
|
|
121
|
+
script(join(dir, "real/tofu"), "echo real");
|
|
122
|
+
const env = { ...JOB, PATH: `${join(dir, "scripts-first")}:${join(dir, "real")}:/usr/bin:/bin` };
|
|
123
|
+
const path = engineRunner().script(join(dir, "scripts"), "tofu", env);
|
|
124
|
+
expect(readFileSync(path, "utf-8")).toContain(`'${join(dir, "real/tofu")}'`);
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe("the trace parent per command", () => {
|
|
129
|
+
test("commandTraceEnv gives TRACEPARENT and names the span, keeping the job's resource attributes and exporter", () => {
|
|
130
|
+
const trace = new OtlpTrace();
|
|
131
|
+
const span = trace.start("root roots/a");
|
|
132
|
+
const env = commandTraceEnv({ OTEL_RESOURCE_ATTRIBUTES: "team=infra", OTEL_TRACES_EXPORTER: "none" }, trace, span, { prefix: "terragucci", root: "roots/a" });
|
|
133
|
+
expect(env.TRACEPARENT).toBe(`00-${trace.traceId}-${span.spanId}-01`);
|
|
134
|
+
expect(env.OTEL_TRACES_EXPORTER).toBe("none");
|
|
135
|
+
expect(env.OTEL_RESOURCE_ATTRIBUTES).toContain("team=infra");
|
|
136
|
+
expect(env.OTEL_RESOURCE_ATTRIBUTES).toContain(`terragucci.span_id=${span.spanId}`);
|
|
137
|
+
expect(env.OTEL_RESOURCE_ATTRIBUTES).toContain("terragucci.root=roots%2Fa");
|
|
138
|
+
expect(commandTraceEnv({}, trace, span, { prefix: "p", root: "r" }).OTEL_TRACES_EXPORTER).toBe("otlp");
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test("commandTrace opens a span per command under the root's, and ends it with the exit code", async () => {
|
|
142
|
+
const trace = new OtlpTrace();
|
|
143
|
+
const root = trace.start("root roots/a");
|
|
144
|
+
const hook = commandTrace({ trace, prefix: "terragucci", parent: (c) => (c.root === "roots/a" ? root : undefined), env: {} });
|
|
145
|
+
const runner = engineRunner({ exec: async (_b, args) => ({ code: args[0] === "plan" ? 2 : args[0] === "apply" ? 1 : 0, stdout: "", out: "" }) });
|
|
146
|
+
const envs: string[] = [];
|
|
147
|
+
await withTerraformCommandHook(
|
|
148
|
+
async (c) => {
|
|
149
|
+
const r = await hook(c);
|
|
150
|
+
if (r?.env) envs.push(r.env.TRACEPARENT!);
|
|
151
|
+
return r;
|
|
152
|
+
},
|
|
153
|
+
{ root: "roots/a", method: "plan" },
|
|
154
|
+
async () => {
|
|
155
|
+
await runner.exec("tofu", ["plan"], "/w", {});
|
|
156
|
+
await runner.exec("tofu", ["apply"], "/w", {});
|
|
157
|
+
},
|
|
158
|
+
);
|
|
159
|
+
const spans = trace.spans.filter((s) => s !== root);
|
|
160
|
+
expect(spans.map((s) => [s.name, s.parentSpanId, s.kind, s.attributes["process.exit.code"], s.error])).toEqual([
|
|
161
|
+
["tofu plan", root.spanId, 3, 2, undefined],
|
|
162
|
+
["tofu apply", root.spanId, 3, 1, "exit 1"],
|
|
163
|
+
]);
|
|
164
|
+
expect(envs).toEqual(spans.map((s) => trace.traceparent(s)));
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("an upstream's reads are not traced unless asked, and a command timed apart spans its own time", async () => {
|
|
168
|
+
const trace = new OtlpTrace();
|
|
169
|
+
const hook = commandTrace({ trace, prefix: "p", env: {} });
|
|
170
|
+
const base = { root: "roots/a", method: "plan", binary: "tofu", name: "init", args: ["init"], line: "tofu init", cwd: "/w", env: {} };
|
|
171
|
+
expect(await hook({ ...base, upstream: "roots/up" })).toBeUndefined();
|
|
172
|
+
const run = await hook({ ...base, name: "plan", args: ["plan"] });
|
|
173
|
+
await run!.after!({ code: 0, seconds: 2, stdout: "", stderr: "", at: { start: 1_700_000_000_000, end: 1_700_000_002_000 } });
|
|
174
|
+
expect(trace.spans[0]!.start).toBe(1_700_000_000_000n * 1_000_000n);
|
|
175
|
+
expect(trace.spans[0]!.end).toBe(1_700_000_002_000n * 1_000_000n);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test("as engineTimings' inner hook, a command gets the trace parent and the receiver's exporter", async () => {
|
|
179
|
+
const trace = new OtlpTrace();
|
|
180
|
+
const timings = await engineTimings({ inner: commandTrace({ trace, prefix: "p", env: {} }) });
|
|
181
|
+
try {
|
|
182
|
+
const envs: NodeJS.ProcessEnv[] = [];
|
|
183
|
+
const runner = engineRunner({ exec: async (_b, _a, _d, env) => (envs.push(env), { code: 0, stdout: "", out: "" }) });
|
|
184
|
+
await withTerraformCommandHook(timings.onCommand, { root: "roots/a", method: "plan" }, () => runner.exec("tofu", ["plan"], "/w", {}));
|
|
185
|
+
expect(envs[0]!.TRACEPARENT).toBe(trace.traceparent(trace.spans[0]!));
|
|
186
|
+
if (!timings.problem) expect(envs[0]!.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT).toMatch(/^http:\/\/127\.0\.0\.1:/);
|
|
187
|
+
expect(timings.root("roots/a")?.commands.map((c) => c.command)).toEqual(["plan"]);
|
|
188
|
+
} finally {
|
|
189
|
+
await timings.close();
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
describe("a Terragrunt unit's plan", () => {
|
|
195
|
+
test("the wrapper sets a unit's variables for the plan whose -out names it, and runs the binary as it is otherwise", () => {
|
|
196
|
+
const text = terragruntUnitWrapper("/bin/tofu", ["/w/plans", "/private/w/plans"], new Map<string, Record<string, string>>([["live/a", { X: "it's" }], ["live/b", {}]]));
|
|
197
|
+
expect(text).toContain(`'/w/plans/live/a/tfplan.tfplan' | '/private/w/plans/live/a/tfplan.tfplan') export X='it'\\''s' ;;`);
|
|
198
|
+
expect(text).not.toContain("live/b");
|
|
199
|
+
expect(text.trimEnd().endsWith(`exec '/bin/tofu' "$@"`)).toBe(true);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("reaches onCommand once per unit, its variables reach that unit's plan alone, and its after has the report's time", async () => {
|
|
203
|
+
const dir = tmp();
|
|
204
|
+
const record = join(dir, "seen");
|
|
205
|
+
const bin = script(join(dir, "bin/tofu"), `echo "$UNIT_VAR" >> '${record}'`);
|
|
206
|
+
const seen: TerraformCommand[] = [];
|
|
207
|
+
const after = new Map<string, TerraformCommandResult>();
|
|
208
|
+
const calls: Array<{ args: readonly string[]; env: Record<string, string> }> = [];
|
|
209
|
+
const exec: TerragruntExec = async (_f, args, opts) => {
|
|
210
|
+
calls.push({ args, env: opts.env });
|
|
211
|
+
const at = (flag: string): string => args[args.indexOf(flag) + 1]!;
|
|
212
|
+
// Terragrunt runs the binary through TG_TF_PATH for each unit's plan, then an init with no -out.
|
|
213
|
+
for (const unit of ["live/a", "live/b"]) spawnSync(opts.env.TG_TF_PATH!, ["plan", `-out=${join(at("--out-dir"), unit, "tfplan.tfplan")}`], { encoding: "utf-8" });
|
|
214
|
+
spawnSync(opts.env.TG_TF_PATH!, ["init"], { encoding: "utf-8", env: { ...process.env, UNIT_VAR: "none" } });
|
|
215
|
+
writeFileSync(
|
|
216
|
+
at("--report-file"),
|
|
217
|
+
JSON.stringify([
|
|
218
|
+
{ Name: "live/a", Result: "succeeded", Started: "2026-11-10T10:00:00Z", Ended: "2026-11-10T10:00:04Z" },
|
|
219
|
+
{ Name: "live/b", Result: "failed", Reason: "run error", Started: "2026-11-10T10:00:00Z", Ended: "2026-11-10T10:00:01Z" },
|
|
220
|
+
]),
|
|
221
|
+
);
|
|
222
|
+
return { code: 1, stdout: "", stderr: "" };
|
|
223
|
+
};
|
|
224
|
+
await planTerragruntWave({
|
|
225
|
+
dir,
|
|
226
|
+
units: ["live/b", "live/a"],
|
|
227
|
+
workDir: "w",
|
|
228
|
+
binary: bin,
|
|
229
|
+
provisional: true,
|
|
230
|
+
exec,
|
|
231
|
+
onCommand: (c) => {
|
|
232
|
+
seen.push(c);
|
|
233
|
+
return { env: { UNIT_VAR: `for ${c.root}` }, after: (r) => void after.set(c.root, r) };
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
expect(seen.map((c) => [c.root, c.method, c.name, c.binary])).toEqual([
|
|
237
|
+
["live/a", "plan", "plan", bin],
|
|
238
|
+
["live/b", "plan", "plan", bin],
|
|
239
|
+
]);
|
|
240
|
+
expect(seen[0]!.cwd).toBe(join(dir, "live/a"));
|
|
241
|
+
expect(readFileSync(record, "utf-8").trim().split("\n")).toEqual(["for live/a", "for live/b", "none"]);
|
|
242
|
+
expect(after.get("live/a")).toMatchObject({ code: 0, seconds: 4, at: { start: Date.parse("2026-11-10T10:00:00Z"), end: Date.parse("2026-11-10T10:00:04Z") } });
|
|
243
|
+
expect(after.get("live/b")).toMatchObject({ code: 1, seconds: 1, stderr: "failed: run error" });
|
|
244
|
+
expect(calls[0]!.env.TG_TF_PATH).not.toBe(bin);
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("a unit missing from the report gets a null code, and a wave with no binary calls no hook", async () => {
|
|
248
|
+
const dir = tmp();
|
|
249
|
+
const bin = script(join(dir, "bin/tofu"), "true");
|
|
250
|
+
const after: TerraformCommandResult[] = [];
|
|
251
|
+
const exec: TerragruntExec = async (_f, args) => {
|
|
252
|
+
writeFileSync(args[args.indexOf("--report-file") + 1]!, "[]");
|
|
253
|
+
return { code: 0, stdout: "", stderr: "" };
|
|
254
|
+
};
|
|
255
|
+
await planTerragruntWave({ dir, units: ["live/a"], workDir: "w", binary: bin, provisional: true, exec, onCommand: () => ({ after: (r) => void after.push(r) }) });
|
|
256
|
+
expect(after).toMatchObject([{ code: null, seconds: 0 }]);
|
|
257
|
+
let called = false;
|
|
258
|
+
await planTerragruntWave({ dir, units: ["live/a"], workDir: "w2", provisional: true, exec, onCommand: () => void (called = true) });
|
|
259
|
+
expect(called).toBe(false);
|
|
260
|
+
});
|
|
261
|
+
});
|