@intentius/chant-lexicon-terraform 0.124.77 → 0.124.79

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.
Files changed (43) hide show
  1. package/dist/change-set.d.ts +1 -0
  2. package/dist/change-set.d.ts.map +1 -1
  3. package/dist/change-set.js +19 -0
  4. package/dist/components/capability-plugin.d.ts +9 -1
  5. package/dist/components/capability-plugin.d.ts.map +1 -1
  6. package/dist/components/capability-plugin.js +44 -22
  7. package/dist/drift-record.d.ts +24 -0
  8. package/dist/drift-record.d.ts.map +1 -1
  9. package/dist/drift-record.js +52 -0
  10. package/dist/drift-rows.d.ts +49 -4
  11. package/dist/drift-rows.d.ts.map +1 -1
  12. package/dist/drift-rows.js +87 -19
  13. package/dist/integrity.json +2 -2
  14. package/dist/manifest.json +1 -1
  15. package/dist/op/activities/terraform.d.ts +11 -0
  16. package/dist/op/activities/terraform.d.ts.map +1 -1
  17. package/dist/op/activities/terraform.js +9 -1
  18. package/dist/terragrunt/capability.d.ts +129 -0
  19. package/dist/terragrunt/capability.d.ts.map +1 -0
  20. package/dist/terragrunt/capability.js +347 -0
  21. package/dist/terragrunt/index.d.ts +3 -1
  22. package/dist/terragrunt/index.d.ts.map +1 -1
  23. package/dist/terragrunt/index.js +3 -1
  24. package/dist/terragrunt/units.d.ts +9 -0
  25. package/dist/terragrunt/units.d.ts.map +1 -1
  26. package/dist/terragrunt/units.js +25 -0
  27. package/package.json +2 -2
  28. package/src/__fixtures__/drift-rows/refresh-plan-module.json +48 -0
  29. package/src/change-set.test.ts +27 -1
  30. package/src/change-set.ts +19 -0
  31. package/src/components/capability-plugin.test.ts +61 -6
  32. package/src/components/capability-plugin.ts +48 -23
  33. package/src/components/compose-op-wave.test.ts +134 -0
  34. package/src/drift-record.test.ts +62 -0
  35. package/src/drift-record.ts +58 -0
  36. package/src/drift-rows.test.ts +90 -1
  37. package/src/drift-rows.ts +89 -18
  38. package/src/op/activities/terraform.test.ts +21 -0
  39. package/src/op/activities/terraform.ts +20 -1
  40. package/src/terragrunt/capability.test.ts +327 -0
  41. package/src/terragrunt/capability.ts +431 -0
  42. package/src/terragrunt/index.ts +3 -1
  43. package/src/terragrunt/units.ts +25 -0
@@ -91,6 +91,15 @@ export declare class TerragruntWaveError extends Error {
91
91
  * reads.
92
92
  */
93
93
  export declare function terragruntWaves(units: readonly TerragruntUnit[], options?: TerragruntWavesOptions): string[][];
94
+ /**
95
+ * The waves a pipeline lists (#4842), cut again by the graph discovery gives
96
+ * now: each listed wave split into its own dependency layers, the listed
97
+ * order kept, so canary waves listed first stay first. A pipeline written
98
+ * with the graph comes back as it is. A unit that depends on a unit of a
99
+ * later listed wave is refused, since the list is stale; units the pipeline
100
+ * does not list stay out. Empty layers are dropped.
101
+ */
102
+ export declare function terragruntListedWaves(listed: readonly (readonly string[])[], units: readonly TerragruntUnit[]): string[][];
94
103
  /**
95
104
  * Every unit that depends on one of `changed`, directly or through other
96
105
  * units, not counting `changed` itself. Sorted by path.
@@ -1 +1 @@
1
- {"version":3,"file":"units.d.ts","sourceRoot":"","sources":["../../src/terragrunt/units.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AAE7D,4GAA4G;AAC5G,eAAO,MAAM,sBAAsB,UAAU,CAAC;AAE9C;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,EAAE,SAAS,MAAM,EAA8C,CAAC;AAE1G,qFAAqF;AACrF,MAAM,WAAW,cAAc;IAC7B,mHAAmH;IACnH,IAAI,EAAE,MAAM,CAAC;IACb,qFAAqF;IACrF,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,2CAA2C;AAC3C,MAAM,WA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,CAAC,EAAE,EAAE,KAAK,EAAE,SAAS,cAAc,EAAE,GAAG,MAAM,EAAE,EAAE,CAe1H;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,SAAS,cAAc,EAAE,EAChC,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,KAAK,GAAE,CAAC,IAAI,EAAE,cAAc,KAAK,SAAS,MAAM,EAA0B,GACzE,MAAM,EAAE,CAeV"}
@@ -168,6 +168,31 @@ export function terragruntWaves(units, options = {}) {
168
168
  };
169
169
  return [...layer(nodes.filter((n) => canaries.has(n.name))), ...layer(nodes.filter((n) => !canaries.has(n.name)))];
170
170
  }
171
+ /**
172
+ * The waves a pipeline lists (#4842), cut again by the graph discovery gives
173
+ * now: each listed wave split into its own dependency layers, the listed
174
+ * order kept, so canary waves listed first stay first. A pipeline written
175
+ * with the graph comes back as it is. A unit that depends on a unit of a
176
+ * later listed wave is refused, since the list is stale; units the pipeline
177
+ * does not list stay out. Empty layers are dropped.
178
+ */
179
+ export function terragruntListedWaves(listed, units) {
180
+ const deps = new Map(units.map((u) => [u.path, u.dependencies]));
181
+ const waveOf = new Map();
182
+ listed.forEach((w, i) => w.forEach((u) => waveOf.set(u, i)));
183
+ const out = [];
184
+ listed.forEach((wave, i) => {
185
+ const members = new Set(wave);
186
+ for (const u of wave) {
187
+ const later = (deps.get(u) ?? []).filter((d) => (waveOf.get(d) ?? -1) > i);
188
+ if (later.length > 0)
189
+ throw new TerragruntWaveError(`${u} depends on ${later.join(", ")}, which the pipeline applies in a later wave; cut the waves again`);
190
+ }
191
+ const sub = wave.map((path) => ({ path, dependencies: (deps.get(path) ?? []).filter((d) => members.has(d)) }));
192
+ out.push(...terragruntWaves(sub).filter((w) => w.length > 0));
193
+ });
194
+ return out;
195
+ }
171
196
  /**
172
197
  * Every unit that depends on one of `changed`, directly or through other
173
198
  * units, not counting `changed` itself. Sorted by path.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-terraform",
3
- "version": "0.124.77",
3
+ "version": "0.124.79",
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.77",
96
+ "@intentius/chant": "^0.124.79",
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,48 @@
1
+ {
2
+ "format_version": "1.2",
3
+ "terraform_version": "1.9.8",
4
+ "resource_drift": [
5
+ {
6
+ "address": "module.service.aws_sqs_queue.jobs[\"orders\"]",
7
+ "module_address": "module.service",
8
+ "mode": "managed",
9
+ "type": "aws_sqs_queue",
10
+ "name": "jobs",
11
+ "index": "orders",
12
+ "provider_name": "registry.terraform.io/hashicorp/aws",
13
+ "change": {
14
+ "actions": ["update"],
15
+ "before": { "name": "shop-orders-jobs", "visibility_timeout_seconds": 30, "tags": { "team": "a" }, "kms_data_key": "hunter2" },
16
+ "after": { "name": "shop-orders-jobs", "visibility_timeout_seconds": 45, "tags": { "team": "b" }, "kms_data_key": "hunter2" },
17
+ "after_unknown": {},
18
+ "before_sensitive": { "kms_data_key": true, "tags": {} },
19
+ "after_sensitive": { "kms_data_key": true, "tags": {} }
20
+ }
21
+ },
22
+ {
23
+ "address": "aws_instance.web",
24
+ "mode": "managed",
25
+ "type": "aws_instance",
26
+ "name": "web",
27
+ "deposed": "00000001",
28
+ "provider_name": "registry.terraform.io/hashicorp/aws",
29
+ "change": {
30
+ "actions": ["delete"],
31
+ "before": { "id": "i-0001", "instance_type": "t3.micro" },
32
+ "after": null,
33
+ "after_unknown": {},
34
+ "before_sensitive": {},
35
+ "after_sensitive": false
36
+ }
37
+ }
38
+ ],
39
+ "resource_changes": [
40
+ {
41
+ "address": "aws_s3_bucket.code_only",
42
+ "mode": "managed",
43
+ "type": "aws_s3_bucket",
44
+ "name": "code_only",
45
+ "change": { "actions": ["create"], "before": null, "after": { "bucket": "waiting-on-main" } }
46
+ }
47
+ ]
48
+ }
@@ -19,7 +19,7 @@
19
19
  import { readFileSync, writeFileSync } from "node:fs";
20
20
  import { join } from "node:path";
21
21
  import { describe, expect, test } from "vitest";
22
- import { composeChangeSet, type ChangeSetPart } from "@intentius/chant/change-set";
22
+ import { composeChangeSet, isEmptyChangeSet, type ChangeSetPart } from "@intentius/chant/change-set";
23
23
  import { actionFor, choudoufuSetPlanParts, parseTerraformAddress, plannerForBinary, terraformChangeSetPart } from "./change-set";
24
24
  import { terraformPlanDigest } from "./plan-digest";
25
25
 
@@ -149,3 +149,29 @@ describe("address and action parsing", () => {
149
149
  expect(plannerForBinary(undefined)).toBe("terraform");
150
150
  });
151
151
  });
152
+
153
+ describe("a plan that changes only outputs (#4849)", () => {
154
+ // The recorded tofu plan's no-op resource, with output_changes as show -json gives them.
155
+ const keep = (read("tofu.plan.json") as { resource_changes: { address: string }[] }).resource_changes.find((r) => r.address === "terraform_data.keep")!;
156
+ const withOutputs = (outputs: Record<string, string[]>) => ({
157
+ format_version: "1.2",
158
+ resource_changes: [keep],
159
+ output_changes: Object.fromEntries(Object.entries(outputs).map(([name, actions]) => [name, { actions, before: "a", after: actions.includes("no-op") ? "a" : "b", after_unknown: false, before_sensitive: false, after_sensitive: false }])),
160
+ });
161
+
162
+ test("the member names each output the plan changes, sorted, and the change set is not empty", () => {
163
+ const part = terraformChangeSetPart({ member: "root", plan: withOutputs({ url: ["update"], name: ["create"], kept: ["no-op"] }), planner: "tofu" });
164
+ expect(part.entries.map((e) => e.action)).toEqual(["no-op"]);
165
+ expect(part.member.outputs).toEqual(["name", "url"]);
166
+ expect(isEmptyChangeSet(composeChangeSet([part]))).toBe(false);
167
+ });
168
+
169
+ test("a plan whose outputs are all no-op, or that has none, names none, and hashes as before", () => {
170
+ const plain = withOutputs({ kept: ["no-op"] });
171
+ const part = terraformChangeSetPart({ member: "root", plan: plain, planner: "tofu" });
172
+ expect(part.member).not.toHaveProperty("outputs");
173
+ expect(isEmptyChangeSet(composeChangeSet([part]))).toBe(true);
174
+ expect(part.member.planDigest).toBe(terraformPlanDigest(plain));
175
+ expect(terraformChangeSetPart({ member: "estate", plan: read("tofu.plan.json"), planner: "tofu" }).member).not.toHaveProperty("outputs");
176
+ });
177
+ });
package/src/change-set.ts CHANGED
@@ -152,6 +152,7 @@ export interface TerraformChangeSetPartInput {
152
152
  * One terraform-family root's part, from its `show -json` plan.
153
153
  *
154
154
  * Every `resource_changes` entry becomes an entry, no-op and read included.
155
+ * The outputs `output_changes` changes are the member's `outputs`.
155
156
  * A plan stock marked `errored` is a failed member: its entries are kept,
156
157
  * but nothing should apply it.
157
158
  */
@@ -189,6 +190,7 @@ export function terraformChangeSetPart(input: TerraformChangeSetPartInput): Chan
189
190
  });
190
191
  const sideEffects = (Array.isArray(plan.action_invocations) ? plan.action_invocations : []).map(sideEffectFor);
191
192
  const errored = plan.errored === true;
193
+ const outputs = changedOutputs(plan.output_changes);
192
194
  return {
193
195
  member: {
194
196
  member: input.member,
@@ -199,6 +201,7 @@ export function terraformChangeSetPart(input: TerraformChangeSetPartInput): Chan
199
201
  ...(errored ? { error: `${planner} marked the plan errored` } : {}),
200
202
  planDigest: terraformPlanDigest(plan),
201
203
  ...(input.nativeDigest ? { nativeDigest: input.nativeDigest } : {}),
204
+ ...(outputs.length > 0 ? { outputs } : {}),
202
205
  holes: [],
203
206
  },
204
207
  entries,
@@ -206,6 +209,22 @@ export function terraformChangeSetPart(input: TerraformChangeSetPartInput): Chan
206
209
  };
207
210
  }
208
211
 
212
+ /**
213
+ * The outputs a plan's `output_changes` changes, sorted (#4849): each whose
214
+ * actions are anything but `no-op`. A plan that changes only outputs is a
215
+ * change, as terragucci counts it.
216
+ */
217
+ function changedOutputs(raw: unknown): string[] {
218
+ if (!isObject(raw)) return [];
219
+ return Object.entries(raw)
220
+ .filter(([, change]) => {
221
+ const actions = isObject(change) && Array.isArray(change.actions) ? change.actions : [];
222
+ return actions.some((a) => a !== "no-op");
223
+ })
224
+ .map(([name]) => name)
225
+ .sort();
226
+ }
227
+
209
228
  /**
210
229
  * One `action_invocations` entry of a plan (Terraform 1.14): the action's
211
230
  * address and type, and, for a lifecycle trigger, the resource and event.
@@ -22,14 +22,17 @@ const planTargets: Array<string[] | undefined> = [];
22
22
  const planTexts: Array<boolean | undefined> = [];
23
23
  // #4463: a plan that fails, as one with a stand-in a validation block rejects does.
24
24
  let planError: Error | undefined;
25
+ // #4842: the env each activity was handed.
26
+ const envs: Array<[string, unknown]> = [];
25
27
 
26
28
  vi.mock("../op/activities/terraform", () => ({
27
29
  // The exit constants exit-codes.ts maps choudoufu's statuses with (#4553), as the module has them.
28
30
  CHOUDOUFU_APPROVAL_EXIT_CODE: 3,
29
31
  CHOUDOUFU_WAVE_EXIT: { landed: 0, error: 1, setMoved: 3, rootFailed: 4 },
30
32
  choudoufuWaveRoot: vi.fn(async () => waveRoot),
31
- choudoufuPlanSet: vi.fn(async (args: { root: string }) => {
33
+ choudoufuPlanSet: vi.fn(async (args: { root: string; env?: unknown }) => {
32
34
  calls.push(`plan-set ${args.root}`);
35
+ envs.push(["plan-set", args.env]);
33
36
  return {
34
37
  setDigest: `sha256:set-${args.root}`,
35
38
  rootDigest: `sha256:root-${args.root}`,
@@ -46,24 +49,28 @@ vi.mock("../op/activities/terraform", () => ({
46
49
  waveApplyArgs.push(args);
47
50
  return waveApply;
48
51
  }),
49
- terraformInit: vi.fn(async (args: { root: string }) => {
52
+ terraformInit: vi.fn(async (args: { root: string; env?: unknown }) => {
50
53
  calls.push(`init ${args.root}`);
54
+ envs.push(["init", args.env]);
51
55
  return { dir: `/x/${args.root}` };
52
56
  }),
53
- terraformPlan: vi.fn(async (args: { root: string; vars?: Record<string, unknown>; targets?: string[]; text?: boolean }) => {
57
+ terraformPlan: vi.fn(async (args: { root: string; vars?: Record<string, unknown>; targets?: string[]; text?: boolean; env?: unknown }) => {
54
58
  calls.push(`plan ${args.root} ${JSON.stringify(args.vars ?? {})}`);
59
+ envs.push(["plan", args.env]);
55
60
  planTargets.push(args.targets);
56
61
  planTexts.push(args.text);
57
62
  if (planError) throw planError;
58
63
  // `dir` as the real result has it (#4545 writes the plan document beside the plan file there).
59
64
  return { planFile: "chant.tfplan", dir: `/x/${args.root}`, planDigest: `jcs1-sha256:${args.root}`, json: planJson, ...(changeSet ? { changeSet } : {}) };
60
65
  }),
61
- terraformApply: vi.fn(async (args: { root: string; planFile: string }) => {
66
+ terraformApply: vi.fn(async (args: { root: string; planFile: string; env?: unknown }) => {
62
67
  calls.push(`apply ${args.root} ${args.planFile}`);
68
+ envs.push(["apply", args.env]);
63
69
  return { planFile: args.planFile, dir: `/x/${args.root}`, ...applyResult };
64
70
  }),
65
- terraformOutputs: vi.fn(async (args: { root: string }) => {
71
+ terraformOutputs: vi.fn(async (args: { root: string; env?: unknown }) => {
66
72
  calls.push(`output ${args.root}`);
73
+ envs.push(["output", args.env]);
67
74
  return { id: `${args.root}-id` };
68
75
  }),
69
76
  }));
@@ -82,6 +89,38 @@ beforeEach(() => {
82
89
  planTargets.length = 0;
83
90
  planTexts.length = 0;
84
91
  planError = undefined;
92
+ envs.length = 0;
93
+ });
94
+
95
+ describe("terraform-apply with a run hook's env and check after init (#4842)", () => {
96
+ const env = { AWS_ROLE_ARN: "arn:aws:iam::1:role/e01" };
97
+
98
+ test("plan and run hand processEnv to init, plan, apply and output, and call afterInit between init and plan", async () => {
99
+ const order: string[] = [];
100
+ const planned = await terraformApplyCapability.plan!({ env: "test", component: "e01", processEnv: env, afterInit: async () => void order.push(`check after ${calls.length} calls`) }, { root: "e01" });
101
+ expect(calls).toEqual(["init e01", "plan e01 {}"]);
102
+ expect(order).toEqual(["check after 1 calls"]);
103
+ await terraformApplyCapability.run({ env: "test", component: "e01", processEnv: env, plans: { e01: planned.artifact } }, { root: "e01" });
104
+ expect(envs).toEqual([["init", env], ["plan", env], ["apply", env], ["output", env]]);
105
+ });
106
+
107
+ test("a check after init that throws stops the plan", async () => {
108
+ await expect(terraformApplyCapability.plan!({ env: "test", component: "e01", afterInit: async () => { throw new Error("a module outside the list"); } }, { root: "e01" })).rejects.toThrow("a module outside the list");
109
+ expect(calls).toEqual(["init e01"]);
110
+ });
111
+
112
+ test("a choudoufu root planned as a one-root set gets the env, and the check before its plan", async () => {
113
+ waveRoot = { wave: true, root: "estates/e01" };
114
+ const order: string[] = [];
115
+ await terraformApplyCapability.plan!({ env: "test", component: "e01", processEnv: env, afterInit: async () => void order.push(`check after ${calls.length} calls`) }, { root: "e01" });
116
+ expect(order).toEqual(["check after 0 calls"]);
117
+ expect(envs).toEqual([["plan-set", env]]);
118
+ });
119
+
120
+ test("without them nothing changes", async () => {
121
+ await terraformApplyCapability.plan!({ env: "test", component: "e01" }, { root: "e01" });
122
+ expect(envs).toEqual([["init", undefined], ["plan", undefined]]);
123
+ });
85
124
  });
86
125
 
87
126
  describe("terraform-apply plans with one show -json (#4479)", () => {
@@ -208,7 +247,7 @@ describe("terraform-apply on a choudoufu root in a gated wave (#3459)", () => {
208
247
 
209
248
  describe("terraform-apply", () => {
210
249
  test("the plugin contributes it", () => {
211
- expect(terraformCapabilityPlugin.capabilities().map((c) => c.kind)).toEqual(["terraform-apply", "terraform-state-unlock", "terraform-state-push", "terraform-copy", "terraform-action"]);
250
+ expect(terraformCapabilityPlugin.capabilities().map((c) => c.kind)).toEqual(["terraform-apply", "terraform-state-unlock", "terraform-state-push", "terraform-copy", "terraform-action", "terragrunt-apply"]);
212
251
  });
213
252
 
214
253
  test("plan inits and plans the root, with its vars, and names the root as the member", async () => {
@@ -486,3 +525,19 @@ describe("terraform-apply previews a root outside a group with placeholders (#44
486
525
  expect(calls.some((c) => c.startsWith("apply"))).toBe(false);
487
526
  });
488
527
  });
528
+
529
+ describe("terraform-apply on a root whose plan changes only outputs (#4849)", () => {
530
+ test("its part names the outputs, so its change set is not empty", async () => {
531
+ const { terraformChangeSetPart } = await import("../change-set");
532
+ const { composeChangeSet, isEmptyChangeSet } = await import("@intentius/chant/change-set");
533
+ const plan = {
534
+ resource_changes: [{ address: "terraform_data.keep", mode: "managed", type: "terraform_data", name: "keep", change: { actions: ["no-op"], before: { input: "a" }, after: { input: "a" }, after_unknown: {} } }],
535
+ output_changes: { url: { actions: ["update"], before: "a", after: "b", after_unknown: false } },
536
+ };
537
+ planJson = plan;
538
+ changeSet = terraformChangeSetPart({ member: "e01", plan }) as unknown as Record<string, unknown>;
539
+ const planned = await terraformApplyCapability.plan!({ env: "test", component: "e01" }, { root: "e01" });
540
+ expect(planned.changeSet?.member.outputs).toEqual(["url"]);
541
+ expect(isEmptyChangeSet(composeChangeSet([planned.changeSet!]))).toBe(false);
542
+ });
543
+ });
@@ -119,6 +119,14 @@
119
119
  * yet makes the member a hole naming it, so the root is never planned on a
120
120
  * stand-in.
121
121
  *
122
+ * A wave's run hooks in the product's process (chant#4842) reach the step
123
+ * through its context. `processEnv` goes to every command for the root (a
124
+ * role's credentials, values from a secret store), and `afterInit` is
125
+ * called after `init` and before `plan`, or before `live-plan-set`, which
126
+ * inits and plans in one command. A `root` with no `terraform.roots` entry
127
+ * plans the step's `dir` as its directory, so a product can name each root
128
+ * by its path without writing an entry for it.
129
+ *
122
130
  * Every plan also writes its `show -json` beside the plan file and names it
123
131
  * as `artifact.planJson`, the document a wave's cost hold prices
124
132
  * (`../cost-hold.ts`).
@@ -167,10 +175,11 @@ import { conePlanDigest, type PlanCone } from "../cone";
167
175
  import { fillStateReads, stateReadsProblems, waitingReadsReason, type TerraformStateRead } from "../state-reads";
168
176
  import { terraformStateOpCapabilities } from "../state-ops";
169
177
  import { terraformActionCapability } from "../action-ops";
178
+ import { terragruntApply } from "../terragrunt/capability";
170
179
 
171
180
  /** The `terraform-apply` step's input. */
172
181
  export interface TerraformApplyStepInput {
173
- /** Key into `terraform.roots`. Also the member's name in a wave's set digest. */
182
+ /** Key into `terraform.roots`. Also the member's name in a wave's set digest. With no such entry, `dir` is the root's directory (chant#4842). */
174
183
  root: string;
175
184
  /** Input variables, after the root's var files. See `TerraformPlanArgs.vars`. */
176
185
  vars?: Record<string, unknown>;
@@ -246,7 +255,10 @@ function waitingOnReads(ctx: DeployContext, input: TerraformApplyStepInput, wait
246
255
  return { member: input.root, planDigest, changeSet };
247
256
  }
248
257
 
249
- const rootArgs = (input: TerraformApplyStepInput) => ({ root: input.root, ...(input.cwd ? { cwd: input.cwd } : {}), ...(input.dir ? { dir: input.dir } : {}) });
258
+ /** A run hook's environment (chant#4842, `DeployContext.processEnv`), which every command for the root runs with. */
259
+ type RunEnv = Record<string, string> | undefined;
260
+
261
+ const rootArgs = (input: TerraformApplyStepInput, env?: RunEnv) => ({ root: input.root, ...(input.cwd ? { cwd: input.cwd } : {}), ...(input.dir ? { dir: input.dir } : {}), ...(env ? { env } : {}) });
250
262
 
251
263
  function requireRoot(input: TerraformApplyStepInput): void {
252
264
  if (typeof input.root !== "string" || input.root === "") {
@@ -254,14 +266,16 @@ function requireRoot(input: TerraformApplyStepInput): void {
254
266
  }
255
267
  }
256
268
 
257
- async function planRoot(input: TerraformApplyStepInput, targets?: string[]): Promise<PlannedRoot & { changeSet?: ChangeSetPart; json?: unknown }> {
269
+ async function planRoot(input: TerraformApplyStepInput, targets?: string[], at: { env?: RunEnv; afterInit?: () => Promise<void> } = {}): Promise<PlannedRoot & { changeSet?: ChangeSetPart; json?: unknown }> {
258
270
  requireRoot(input);
259
- await terraformInit(rootArgs(input));
271
+ await terraformInit(rootArgs(input, at.env));
272
+ // chant#4842: the run hook's check, once init fetched the modules and providers and before the plan runs their code.
273
+ await at.afterInit?.();
260
274
  // One `show -json` per plan (#4479): its document is the digest, the change
261
275
  // set, the planned outputs and the shape. Nothing here reads the
262
276
  // `-no-color` render, so the plan skips it.
263
277
  const planned = await terraformPlan({
264
- ...rootArgs(input),
278
+ ...rootArgs(input, at.env),
265
279
  ...(input.vars ? { vars: input.vars } : {}),
266
280
  ...(targets && targets.length > 0 ? { targets } : {}),
267
281
  ...lockTimeoutOf(input),
@@ -390,7 +404,8 @@ async function rootDir(input: TerraformApplyStepInput): Promise<{ dir: string; b
390
404
  const start = resolve(input.cwd ?? process.cwd());
391
405
  const { config, configPath } = await loadChantConfigUpward(start);
392
406
  const terraform = (config as { terraform?: TerraformConfig }).terraform;
393
- const declared = terraform?.roots?.[input.root]?.dir;
407
+ // chant#4842: a root with no entry and a dir of its own is that directory.
408
+ const declared = terraform?.roots?.[input.root]?.dir ?? input.dir;
394
409
  if (declared === undefined) return undefined;
395
410
  const dir = input.dir ?? declared;
396
411
  return { dir: resolve(configPath ? dirname(configPath) : start, dir), ...(terraform?.binary ? { binary: terraform.binary } : {}) };
@@ -418,9 +433,10 @@ async function previewRoot(ctx: DeployContext, input: TerraformApplyStepInput, u
418
433
  if (typeof stand === "string") return waitingRoot(ctx, input, unresolved, stand);
419
434
  let planned: Awaited<ReturnType<typeof terraformPlan>>;
420
435
  try {
421
- await terraformInit(rootArgs(input));
436
+ await terraformInit(rootArgs(input, ctx.processEnv));
437
+ await ctx.afterInit?.();
422
438
  planned = await terraformPlan({
423
- ...rootArgs(input),
439
+ ...rootArgs(input, ctx.processEnv),
424
440
  vars: stand.vars,
425
441
  planFile: PREVIEW_PLAN_FILE,
426
442
  ...(targets ? { targets } : {}),
@@ -509,7 +525,7 @@ async function runChoudoufuWave(
509
525
  planned: ChoudoufuWavePlannedRoot,
510
526
  ): Promise<TerraformApplyStepOutput> {
511
527
  const applied = await choudoufuWaveApply({
512
- ...rootArgs(input),
528
+ ...rootArgs(input, ctx.processEnv),
513
529
  planSetFile: planned.choudoufu.planSetFile,
514
530
  setDigest: planned.choudoufu.setDigest,
515
531
  ...(ctx.carried?.[input.root] !== undefined ? { carried: ctx.carried[input.root] } : {}),
@@ -520,7 +536,7 @@ async function runChoudoufuWave(
520
536
  if (terraformPlanMoved({ command: "live-wave-apply", code: applied.exitCode })) throw new TerraformPlanMovedError(input.root, message);
521
537
  throw new Error(message);
522
538
  }
523
- const outputs = await terraformOutputs(rootArgs(input));
539
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
524
540
  return { root: input.root, planDigest: planned.planDigest, fromWavePlan: true, outputs };
525
541
  }
526
542
 
@@ -563,9 +579,12 @@ export const terraformApplyCapability: Capability<TerraformApplyStepInput, Terra
563
579
  const targets = ctx.targets && ctx.targets.length > 0 ? ctx.targets : undefined;
564
580
  if (unresolved.length > 0) return previewRoot(ctx, input, unresolved, targets);
565
581
  // A targeted root plans with `plan -target`, and a cone plan with `plan -cone` (#4545), never as a choudoufu one-root set.
566
- const wave = targets || input.cone ? { wave: false } : await choudoufuWaveRoot({ ...rootArgs(input), ...(input.vars ? { vars: input.vars } : {}) });
582
+ const env = ctx.processEnv;
583
+ const wave = targets || input.cone ? { wave: false } : await choudoufuWaveRoot({ ...rootArgs(input, env), ...(input.vars ? { vars: input.vars } : {}) });
567
584
  if (wave.wave) {
568
- const set = await choudoufuPlanSet(rootArgs(input));
585
+ // chant#4842: live-plan-set inits and plans in one command, so the run hook's check comes before it.
586
+ await ctx.afterInit?.();
587
+ const set = await choudoufuPlanSet(rootArgs(input, env));
569
588
  const artifact: ChoudoufuWavePlannedRoot = {
570
589
  planDigest: set.planDigest,
571
590
  choudoufu: { planSetFile: set.planSetFile, setDigest: set.setDigest },
@@ -573,7 +592,7 @@ export const terraformApplyCapability: Capability<TerraformApplyStepInput, Terra
573
592
  };
574
593
  return { member: input.root, planDigest: set.planDigest, artifact, changeSet: set.changeSet, outputs: terraformPlannedOutputs(set.json), shape: terraformPlanShape(set.json, input.root) };
575
594
  }
576
- const { changeSet, json, ...planned } = await planRoot(input, targets);
595
+ const { changeSet, json, ...planned } = await planRoot(input, targets, { env, ...(ctx.afterInit ? { afterInit: ctx.afterInit } : {}) });
577
596
  // #4552: a choudoufu root's rows, keyed from the plan document while it is at hand.
578
597
  const lockRows = changeSet?.member.planner === "choudoufu" ? terraformLockRows(input.root, changeSet.member.scope, json) : undefined;
579
598
  return {
@@ -590,10 +609,10 @@ export const terraformApplyCapability: Capability<TerraformApplyStepInput, Terra
590
609
  },
591
610
  // The root's outputs as its state holds them now (#3183): what a dependent
592
611
  // planned before this root applies reads through `stackOutput()`.
593
- async outputs(_ctx: DeployContext, input: TerraformApplyStepInput): Promise<Record<string, unknown>> {
612
+ async outputs(ctx: DeployContext, input: TerraformApplyStepInput): Promise<Record<string, unknown>> {
594
613
  requireRoot(input);
595
- await terraformInit(rootArgs(input));
596
- return terraformOutputs(rootArgs(input));
614
+ await terraformInit(rootArgs(input, ctx.processEnv));
615
+ return terraformOutputs(rootArgs(input, ctx.processEnv));
597
616
  },
598
617
  // #4447 (ws-107): a group core forms of components that read each other plans and applies as one composed run
599
618
  // when `terraform.compose.enabled` is set (./compose-group.ts). Delegates, so the methods are read when called.
@@ -634,20 +653,20 @@ export const terraformApplyCapability: Capability<TerraformApplyStepInput, Terra
634
653
  if (isShapeArtifact(fromWave)) {
635
654
  // A root previewed with stand-ins (#4463): plan it now with the real
636
655
  // values, and apply that plan only when it is within the preview's shape.
637
- const fresh = await planRoot(await readsForRun(input), ctx.targets);
656
+ const fresh = await planRoot(await readsForRun(input), ctx.targets, { env: ctx.processEnv });
638
657
  const differences = planShapeDifferences(fromWave.shape, terraformPlanShape(fresh.json, input.root));
639
658
  if (differences.length > 0) throw new PlanShapeMovedError(input.root, differences);
640
- const applied = await terraformApply({ ...rootArgs(input), planFile: fresh.planFile, ...lockTimeoutOf(input) });
659
+ const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: fresh.planFile, ...lockTimeoutOf(input) });
641
660
  if (!applied.applied) {
642
661
  throw new Error(`terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ${applied.refusal ?? ""}`);
643
662
  }
644
- const outputs = await terraformOutputs(rootArgs(input));
663
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
645
664
  return { root: input.root, planDigest: fresh.planDigest, fromWavePlan: false, outputs };
646
665
  }
647
666
  const planned: PlannedRoot = isPlannedRoot(fromWave)
648
667
  ? fromWave
649
- : await planRoot(await readsForRun(input), ctx.targets).then(({ planFile, planDigest }) => ({ planFile, planDigest }));
650
- const applied = await terraformApply({ ...rootArgs(input), planFile: planned.planFile, ...lockTimeoutOf(input) });
668
+ : await planRoot(await readsForRun(input), ctx.targets, { env: ctx.processEnv }).then(({ planFile, planDigest }) => ({ planFile, planDigest }));
669
+ const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: planned.planFile, ...lockTimeoutOf(input) });
651
670
  if (!applied.applied) {
652
671
  const message =
653
672
  `terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ` +
@@ -658,7 +677,7 @@ export const terraformApplyCapability: Capability<TerraformApplyStepInput, Terra
658
677
  if (applied.refused === "approval-mismatch" && isPlannedRoot(fromWave)) throw new TerraformPlanMovedError(input.root, message);
659
678
  throw new Error(message);
660
679
  }
661
- const outputs = await terraformOutputs(rootArgs(input));
680
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
662
681
  return { root: input.root, planDigest: planned.planDigest, fromWavePlan: isPlannedRoot(fromWave), outputs };
663
682
  },
664
683
  };
@@ -678,7 +697,13 @@ export const terraformCapabilityPlugin: CapabilityPlugin = {
678
697
  return ownPackageVersion(import.meta.url);
679
698
  },
680
699
  capabilities(): Array<Capability<never, unknown>> {
681
- return [terraformApplyCapability as Capability<never, unknown>, ...terraformStateOpCapabilities.map((c) => c as unknown as Capability<never, unknown>), terraformActionCapability as unknown as Capability<never, unknown>];
700
+ return [
701
+ terraformApplyCapability as Capability<never, unknown>,
702
+ ...terraformStateOpCapabilities.map((c) => c as unknown as Capability<never, unknown>),
703
+ terraformActionCapability as unknown as Capability<never, unknown>,
704
+ // #4842: Terragrunt units as an op wave's step, found at plan time and run with one run --all.
705
+ terragruntApply as unknown as Capability<never, unknown>,
706
+ ];
682
707
  },
683
708
  families(): Record<string, readonly string[]> {
684
709
  return TERRAFORM_VERB_FAMILIES;