@intentius/chant-lexicon-terraform 0.124.78 → 0.124.80

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 (45) 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 +75 -2
  5. package/dist/components/capability-plugin.d.ts.map +1 -1
  6. package/dist/components/capability-plugin.js +250 -142
  7. package/dist/components/compose-group.d.ts +2 -1
  8. package/dist/components/compose-group.d.ts.map +1 -1
  9. package/dist/components/compose-group.js +6 -6
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -1
  13. package/dist/integrity.json +2 -2
  14. package/dist/manifest.json +1 -1
  15. package/dist/op/activities/terraform.d.ts +33 -0
  16. package/dist/op/activities/terraform.d.ts.map +1 -1
  17. package/dist/op/activities/terraform.js +37 -5
  18. package/dist/state-reads.d.ts +20 -3
  19. package/dist/state-reads.d.ts.map +1 -1
  20. package/dist/state-reads.js +20 -4
  21. package/dist/terragrunt/capability.d.ts +129 -0
  22. package/dist/terragrunt/capability.d.ts.map +1 -0
  23. package/dist/terragrunt/capability.js +352 -0
  24. package/dist/terragrunt/index.d.ts +3 -1
  25. package/dist/terragrunt/index.d.ts.map +1 -1
  26. package/dist/terragrunt/index.js +3 -1
  27. package/dist/terragrunt/units.d.ts +9 -0
  28. package/dist/terragrunt/units.d.ts.map +1 -1
  29. package/dist/terragrunt/units.js +25 -0
  30. package/package.json +2 -2
  31. package/src/change-set.test.ts +27 -1
  32. package/src/change-set.ts +19 -0
  33. package/src/components/capability-plugin.test.ts +61 -6
  34. package/src/components/capability-plugin.ts +290 -139
  35. package/src/components/compose-group.ts +8 -7
  36. package/src/components/compose-op-wave.test.ts +134 -0
  37. package/src/components/terraform-apply-op-wave.test.ts +295 -0
  38. package/src/index.ts +5 -0
  39. package/src/op/activities/terraform.test.ts +21 -0
  40. package/src/op/activities/terraform.ts +64 -4
  41. package/src/state-reads.ts +23 -5
  42. package/src/terragrunt/capability.test.ts +348 -0
  43. package/src/terragrunt/capability.ts +437 -0
  44. package/src/terragrunt/index.ts +3 -1
  45. package/src/terragrunt/units.ts +25 -0
@@ -119,6 +119,19 @@
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
+ * - `workspace`: the workspace the root runs in (chant#4854). `init` runs in
123
+ * `default`, then `workspace select -or-create=true` selects it, creating
124
+ * it when the backend does not list it yet, and the plan, apply and
125
+ * output run in it. Such a root plans with `plan`, never as a one-root set.
126
+ *
127
+ * A wave's run hooks in the product's process (chant#4842) reach the step
128
+ * through its context. `processEnv` goes to every command for the root (a
129
+ * role's credentials, values from a secret store), and `afterInit` is
130
+ * called after `init` and before `plan`, or before `live-plan-set`, which
131
+ * inits and plans in one command. A `root` with no `terraform.roots` entry
132
+ * plans the step's `dir` as its directory, so a product can name each root
133
+ * by its path without writing an entry for it.
134
+ *
122
135
  * Every plan also writes its `show -json` beside the plan file and names it
123
136
  * as `artifact.planJson`, the document a wave's cost hold prices
124
137
  * (`../cost-hold.ts`).
@@ -167,14 +180,15 @@ import { conePlanDigest, type PlanCone } from "../cone";
167
180
  import { fillStateReads, stateReadsProblems, waitingReadsReason, type TerraformStateRead } from "../state-reads";
168
181
  import { terraformStateOpCapabilities } from "../state-ops";
169
182
  import { terraformActionCapability } from "../action-ops";
183
+ import { terragruntApply } from "../terragrunt/capability";
170
184
 
171
185
  /** The `terraform-apply` step's input. */
172
186
  export interface TerraformApplyStepInput {
173
- /** Key into `terraform.roots`. Also the member's name in a wave's set digest. */
187
+ /** 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
188
  root: string;
175
189
  /** Input variables, after the root's var files. See `TerraformPlanArgs.vars`. */
176
190
  vars?: Record<string, unknown>;
177
- /** Where the `chant.config.*` search starts. Default: the current directory. */
191
+ /** Where the `chant.config.*` search starts. Default: the directory the caller runs the step in (`DeployContext.cwd`, an op wave's `cwd`, chant#4854), else the current directory. */
178
192
  cwd?: string;
179
193
  /** The root's files from here instead of its entry's `dir` (#4542): a promote under a release sets it to the recorded copy. */
180
194
  dir?: string;
@@ -184,6 +198,49 @@ export interface TerraformApplyStepInput {
184
198
  cone?: string;
185
199
  /** Vars read from other roots' outputs (#4545), Atmos's `!terraform.state`. The step's `vars` win over them. */
186
200
  reads?: TerraformStateRead[];
201
+ /**
202
+ * The workspace the root plans and applies in (chant#4854), such as an
203
+ * Atmos instance's. `init` runs in `default`, then `workspace select
204
+ * -or-create=true` selects it, creating it when the backend does not list
205
+ * it yet, and plan, apply and output run with `TF_WORKSPACE` set to it.
206
+ * Absent: the entry's `workspace`, or the run's environment, as before.
207
+ */
208
+ workspace?: string;
209
+ /**
210
+ * The binary the root runs, a name on `PATH` or a path, in place of
211
+ * `terraform.binary` (terragucci issue 1303): a root that pins its own
212
+ * terraform or tofu release. A product's {@link TerraformRootResolver}
213
+ * sets it per root. Absent: `terraform.binary`, as before.
214
+ */
215
+ binary?: string;
216
+ }
217
+
218
+ /** What a root runs in place of the step's (terragucci issue 1303). An unset field runs the step's. */
219
+ export interface TerraformRootTools {
220
+ /** The binary, a name on `PATH` or a path. See {@link TerraformApplyStepInput.binary}. */
221
+ binary?: string;
222
+ /**
223
+ * The environment a read of this root's state runs with over the job's,
224
+ * when another root's `reads` name it as their upstream (terragucci issue
225
+ * 1303): its role's credentials, never the reader's. The root's own plan
226
+ * and apply take theirs from the run hooks (`DeployContext.processEnv`).
227
+ */
228
+ readEnv?: Record<string, string>;
229
+ }
230
+
231
+ /**
232
+ * What a root runs (terragucci issue 1303), asked once per plan and per
233
+ * apply with the root and the step's input, as `terragrunt-apply`'s
234
+ * `resolveUnit` is asked per unit. A product passes its own, which installs
235
+ * a pinned release and checks its version, so a root runs what it plans
236
+ * with whatever `chant.config.ts` names.
237
+ */
238
+ export type TerraformRootResolver = (root: string, input: TerraformApplyStepInput) => TerraformRootTools | Promise<TerraformRootTools>;
239
+
240
+ /** What {@link terraformApplyCapabilityWith} takes. */
241
+ export interface TerraformApplyDeps {
242
+ /** What each root runs. Default: the step's `binary`, else `terraform.binary`. */
243
+ resolveRoot?: TerraformRootResolver;
187
244
  }
188
245
 
189
246
  /** What `terraform-apply` returns. `outputs` is what a dependent's `stackOutput()` reads. */
@@ -221,13 +278,22 @@ function lockTimeoutOf(input: TerraformApplyStepInput): { lockTimeout?: string }
221
278
  * read once, the values under the step's own `vars`. `waiting` when an
222
279
  * upstream has no such output yet. Throws when a state cannot be read.
223
280
  */
224
- async function withReads(input: TerraformApplyStepInput): Promise<{ input: TerraformApplyStepInput } | { waiting: string; upstreams: string[] }> {
281
+ async function withReads(input: TerraformApplyStepInput, resolveRoot?: TerraformRootResolver): Promise<{ input: TerraformApplyStepInput } | { waiting: string; upstreams: string[] }> {
225
282
  const reads = input.reads ?? [];
226
283
  if (reads.length === 0) return { input };
227
284
  const problems = stateReadsProblems(reads);
228
285
  if (problems.length > 0) throw new Error(`terraform-apply: root "${input.root}": ${problems.join("; ")}`);
229
- const filled = await fillStateReads(reads, async (root) => {
230
- const at = { root, ...(input.cwd ? { cwd: input.cwd } : {}) };
286
+ const filled = await fillStateReads(reads, async (root, read) => {
287
+ // terragucci issue 1303: the upstream's own directory, workspace, binary and environment, as terragucci's upstreamOutputs reads it.
288
+ const tools = resolveRoot ? await resolveRoot(root, { root, ...(input.cwd ? { cwd: input.cwd } : {}), ...(read.dir ? { dir: read.dir } : {}), ...(read.workspace ? { workspace: read.workspace } : {}) }) : undefined;
289
+ const at = {
290
+ root,
291
+ ...(input.cwd ? { cwd: input.cwd } : {}),
292
+ ...(read.dir ? { dir: read.dir } : {}),
293
+ ...(read.workspace ? { workspace: read.workspace } : {}),
294
+ ...(tools?.binary ? { binary: tools.binary } : {}),
295
+ ...(tools?.readEnv ? { env: tools.readEnv } : {}),
296
+ };
231
297
  await terraformInit(at);
232
298
  return terraformOutputs(at);
233
299
  });
@@ -246,22 +312,40 @@ function waitingOnReads(ctx: DeployContext, input: TerraformApplyStepInput, wait
246
312
  return { member: input.root, planDigest, changeSet };
247
313
  }
248
314
 
249
- const rootArgs = (input: TerraformApplyStepInput) => ({ root: input.root, ...(input.cwd ? { cwd: input.cwd } : {}), ...(input.dir ? { dir: input.dir } : {}) });
315
+ /** A run hook's environment (chant#4842, `DeployContext.processEnv`), which every command for the root runs with. */
316
+ type RunEnv = Record<string, string> | undefined;
317
+
318
+ const rootArgs = (input: TerraformApplyStepInput, env?: RunEnv) => ({
319
+ root: input.root,
320
+ ...(input.cwd ? { cwd: input.cwd } : {}),
321
+ ...(input.dir ? { dir: input.dir } : {}),
322
+ ...(env ? { env } : {}),
323
+ ...(input.workspace ? { workspace: input.workspace } : {}),
324
+ ...(input.binary ? { binary: input.binary } : {}),
325
+ });
250
326
 
251
327
  function requireRoot(input: TerraformApplyStepInput): void {
252
328
  if (typeof input.root !== "string" || input.root === "") {
253
329
  throw new Error('terraform-apply: "root" is required and names an entry in terraform.roots');
254
330
  }
331
+ if (input.workspace !== undefined && (typeof input.workspace !== "string" || input.workspace.trim() === "")) {
332
+ throw new Error(`terraform-apply: root "${input.root}": workspace must name a workspace`);
333
+ }
334
+ if (input.binary !== undefined && (typeof input.binary !== "string" || input.binary.trim() === "")) {
335
+ throw new Error(`terraform-apply: root "${input.root}": binary must name a binary or its path`);
336
+ }
255
337
  }
256
338
 
257
- async function planRoot(input: TerraformApplyStepInput, targets?: string[]): Promise<PlannedRoot & { changeSet?: ChangeSetPart; json?: unknown }> {
339
+ async function planRoot(input: TerraformApplyStepInput, targets?: string[], at: { env?: RunEnv; afterInit?: () => Promise<void> } = {}): Promise<PlannedRoot & { changeSet?: ChangeSetPart; json?: unknown }> {
258
340
  requireRoot(input);
259
- await terraformInit(rootArgs(input));
341
+ await terraformInit(rootArgs(input, at.env));
342
+ // chant#4842: the run hook's check, once init fetched the modules and providers and before the plan runs their code.
343
+ await at.afterInit?.();
260
344
  // One `show -json` per plan (#4479): its document is the digest, the change
261
345
  // set, the planned outputs and the shape. Nothing here reads the
262
346
  // `-no-color` render, so the plan skips it.
263
347
  const planned = await terraformPlan({
264
- ...rootArgs(input),
348
+ ...rootArgs(input, at.env),
265
349
  ...(input.vars ? { vars: input.vars } : {}),
266
350
  ...(targets && targets.length > 0 ? { targets } : {}),
267
351
  ...lockTimeoutOf(input),
@@ -385,15 +469,50 @@ function isShapeArtifact(value: unknown): value is TerraformShapeArtifact {
385
469
  return v?.kind === "terraform-apply-shape" && typeof v.digest === "string" && typeof v.shape === "object" && v.shape !== null;
386
470
  }
387
471
 
472
+ /** Each step input core passed, as it was filled (chant#4854, terragucci issue 1303), for the methods core calls with the input alone. */
473
+ const filledInputs = new WeakMap<object, TerraformApplyStepInput>();
474
+
475
+ /**
476
+ * The step's input with `cwd` set to the caller's directory when it names
477
+ * none (chant#4854, `DeployContext.cwd`): an op wave run in process for
478
+ * another directory finds that directory's `chant.config.*`, not the
479
+ * process's. The input core passed is remembered, so `defaultLockGrain`,
480
+ * `lockGrainRefusal` and `traceFacts`, which get the input alone, read the
481
+ * same config.
482
+ */
483
+ export function withContextCwd(ctx: { cwd?: string } | undefined, input: TerraformApplyStepInput): TerraformApplyStepInput {
484
+ if (!input || typeof input !== "object" || input.cwd !== undefined || ctx?.cwd === undefined) return input;
485
+ const filled = { ...input, cwd: ctx.cwd };
486
+ filledInputs.set(input, { ...filledInputs.get(input), ...filled });
487
+ return filled;
488
+ }
489
+
490
+ /** The step's input with `cwd` from the context and what `resolveRoot` answers for the root (terragucci issue 1303), remembered for the input core passed. */
491
+ async function filledInput(resolveRoot: TerraformRootResolver | undefined, ctx: { cwd?: string } | undefined, input: TerraformApplyStepInput): Promise<TerraformApplyStepInput> {
492
+ const at = withContextCwd(ctx, input);
493
+ if (!resolveRoot || !at || typeof at !== "object" || typeof at.root !== "string" || at.root === "") return at;
494
+ const tools = await resolveRoot(at.root, at);
495
+ if (tools?.binary !== undefined && (typeof tools.binary !== "string" || tools.binary.trim() === "")) {
496
+ throw new Error(`terraform-apply: root "${at.root}": the product's resolveRoot answered a binary that names nothing`);
497
+ }
498
+ if (!tools?.binary) return at;
499
+ const filled = { ...at, binary: tools.binary };
500
+ filledInputs.set(input, filled);
501
+ return filled;
502
+ }
503
+
388
504
  /** The root's directory, as `terraform.roots` names it from the nearest `chant.config.*`, and the configured binary. */
389
- async function rootDir(input: TerraformApplyStepInput): Promise<{ dir: string; binary?: string } | undefined> {
505
+ async function rootDir(given: TerraformApplyStepInput): Promise<{ dir: string; binary?: string } | undefined> {
506
+ const input = filledInputs.get(given) ?? given;
390
507
  const start = resolve(input.cwd ?? process.cwd());
391
508
  const { config, configPath } = await loadChantConfigUpward(start);
392
509
  const terraform = (config as { terraform?: TerraformConfig }).terraform;
393
- const declared = terraform?.roots?.[input.root]?.dir;
510
+ // chant#4842: a root with no entry and a dir of its own is that directory.
511
+ const declared = terraform?.roots?.[input.root]?.dir ?? input.dir;
394
512
  if (declared === undefined) return undefined;
395
513
  const dir = input.dir ?? declared;
396
- return { dir: resolve(configPath ? dirname(configPath) : start, dir), ...(terraform?.binary ? { binary: terraform.binary } : {}) };
514
+ const binary = input.binary ?? terraform?.binary;
515
+ return { dir: resolve(configPath ? dirname(configPath) : start, dir), ...(binary ? { binary } : {}) };
397
516
  }
398
517
 
399
518
  const firstLines = (err: unknown): string => {
@@ -418,9 +537,10 @@ async function previewRoot(ctx: DeployContext, input: TerraformApplyStepInput, u
418
537
  if (typeof stand === "string") return waitingRoot(ctx, input, unresolved, stand);
419
538
  let planned: Awaited<ReturnType<typeof terraformPlan>>;
420
539
  try {
421
- await terraformInit(rootArgs(input));
540
+ await terraformInit(rootArgs(input, ctx.processEnv));
541
+ await ctx.afterInit?.();
422
542
  planned = await terraformPlan({
423
- ...rootArgs(input),
543
+ ...rootArgs(input, ctx.processEnv),
424
544
  vars: stand.vars,
425
545
  planFile: PREVIEW_PLAN_FILE,
426
546
  ...(targets ? { targets } : {}),
@@ -509,7 +629,7 @@ async function runChoudoufuWave(
509
629
  planned: ChoudoufuWavePlannedRoot,
510
630
  ): Promise<TerraformApplyStepOutput> {
511
631
  const applied = await choudoufuWaveApply({
512
- ...rootArgs(input),
632
+ ...rootArgs(input, ctx.processEnv),
513
633
  planSetFile: planned.choudoufu.planSetFile,
514
634
  setDigest: planned.choudoufu.setDigest,
515
635
  ...(ctx.carried?.[input.root] !== undefined ? { carried: ctx.carried[input.root] } : {}),
@@ -520,13 +640,13 @@ async function runChoudoufuWave(
520
640
  if (terraformPlanMoved({ command: "live-wave-apply", code: applied.exitCode })) throw new TerraformPlanMovedError(input.root, message);
521
641
  throw new Error(message);
522
642
  }
523
- const outputs = await terraformOutputs(rootArgs(input));
643
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
524
644
  return { root: input.root, planDigest: planned.planDigest, fromWavePlan: true, outputs };
525
645
  }
526
646
 
527
647
  /** The input a `run` that plans for itself plans with (#4545): its reads filled, or an error naming the upstream to apply first. */
528
- async function readsForRun(input: TerraformApplyStepInput): Promise<TerraformApplyStepInput> {
529
- const read = await withReads(input);
648
+ async function readsForRun(input: TerraformApplyStepInput, resolveRoot?: TerraformRootResolver): Promise<TerraformApplyStepInput> {
649
+ const read = await withReads(input, resolveRoot);
530
650
  if ("waiting" in read) throw new Error(`terraform-apply: root "${input.root}": ${read.waiting}`);
531
651
  return read.input;
532
652
  }
@@ -539,129 +659,154 @@ async function plannerOf(input: TerraformApplyStepInput, plan?: CapabilityPlan):
539
659
  return planner === "terraform" || planner === "tofu" || planner === "choudoufu" ? planner : "terraform";
540
660
  }
541
661
 
542
- export const terraformApplyCapability: Capability<TerraformApplyStepInput, TerraformApplyStepOutput> = {
543
- kind: "terraform-apply",
544
- // A root's apply has no undo short of applying the previous configuration,
545
- // which is a change of its own. COMP003 asks the component to say so.
546
- rollbackPolicy: "needs-opt-out",
547
- // #4300: `--target` passes through as `-target`, and the saved plan holds those addresses alone.
548
- targets: "accept",
549
- // #4627: `plan` refreshes the root's state before it plans unless told `-refresh=false`, which chant never passes,
550
- // so `--refresh` asks for what every plan does and the digest still binds it. `-target` plans a resource with what it
551
- // depends on and never what depends on it, so `--target-dependents` has nothing to map onto.
552
- planFlags: {
553
- refresh: "accept",
554
- targetDependents: { refuse: "terraform and tofu plan a -target with what it depends on, never what depends on it, so there is no flag to widen it to its dependents; name each dependent with --target" },
555
- },
556
- async plan(ctx: DeployContext, given: TerraformApplyStepInput): Promise<CapabilityPlan> {
557
- requireRoot(given);
558
- // #4545: a root reading an upstream's output that is not there yet is a hole naming the upstream.
559
- const read = await withReads(given);
560
- if ("waiting" in read) return waitingOnReads(ctx, given, read);
561
- const { input } = read;
562
- const unresolved = [...(ctx.unresolvedInputs ?? [])].sort();
563
- const targets = ctx.targets && ctx.targets.length > 0 ? ctx.targets : undefined;
564
- if (unresolved.length > 0) return previewRoot(ctx, input, unresolved, targets);
565
- // 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 } : {}) });
567
- if (wave.wave) {
568
- const set = await choudoufuPlanSet(rootArgs(input));
569
- const artifact: ChoudoufuWavePlannedRoot = {
570
- planDigest: set.planDigest,
571
- choudoufu: { planSetFile: set.planSetFile, setDigest: set.setDigest },
572
- lockRows: terraformLockRows(input.root, set.changeSet.member.scope, set.json),
662
+ /**
663
+ * `terraform-apply` with `deps` in place of the defaults (terragucci issue
664
+ * 1303). `resolveRoot` answers what each root runs, so a product whose roots
665
+ * pin their own releases passes its resolver, as it passes `resolveUnit` to
666
+ * `terragruntApplyCapability`. A composed group (`together`) runs the
667
+ * project's binary, as before.
668
+ */
669
+ export function terraformApplyCapabilityWith(deps: TerraformApplyDeps = {}): Capability<TerraformApplyStepInput, TerraformApplyStepOutput> {
670
+ return {
671
+ kind: "terraform-apply",
672
+ // A root's apply has no undo short of applying the previous configuration,
673
+ // which is a change of its own. COMP003 asks the component to say so.
674
+ rollbackPolicy: "needs-opt-out",
675
+ // #4300: `--target` passes through as `-target`, and the saved plan holds those addresses alone.
676
+ targets: "accept",
677
+ // #4627: `plan` refreshes the root's state before it plans unless told `-refresh=false`, which chant never passes,
678
+ // so `--refresh` asks for what every plan does and the digest still binds it. `-target` plans a resource with what it
679
+ // depends on and never what depends on it, so `--target-dependents` has nothing to map onto.
680
+ planFlags: {
681
+ refresh: "accept",
682
+ targetDependents: { refuse: "terraform and tofu plan a -target with what it depends on, never what depends on it, so there is no flag to widen it to its dependents; name each dependent with --target" },
683
+ },
684
+ async plan(ctx: DeployContext, step: TerraformApplyStepInput): Promise<CapabilityPlan> {
685
+ const given = await filledInput(deps.resolveRoot, ctx, step);
686
+ requireRoot(given);
687
+ // #4545: a root reading an upstream's output that is not there yet is a hole naming the upstream.
688
+ const read = await withReads(given, deps.resolveRoot);
689
+ if ("waiting" in read) return waitingOnReads(ctx, given, read);
690
+ const { input } = read;
691
+ const unresolved = [...(ctx.unresolvedInputs ?? [])].sort();
692
+ const targets = ctx.targets && ctx.targets.length > 0 ? ctx.targets : undefined;
693
+ if (unresolved.length > 0) return previewRoot(ctx, input, unresolved, targets);
694
+ // A targeted root plans with `plan -target`, and a cone plan with `plan -cone` (#4545), never as a choudoufu one-root set.
695
+ const env = ctx.processEnv;
696
+ const wave = targets || input.cone ? { wave: false } : await choudoufuWaveRoot({ ...rootArgs(input, env), ...(input.vars ? { vars: input.vars } : {}) });
697
+ if (wave.wave) {
698
+ // chant#4842: live-plan-set inits and plans in one command, so the run hook's check comes before it.
699
+ await ctx.afterInit?.();
700
+ const set = await choudoufuPlanSet(rootArgs(input, env));
701
+ const artifact: ChoudoufuWavePlannedRoot = {
702
+ planDigest: set.planDigest,
703
+ choudoufu: { planSetFile: set.planSetFile, setDigest: set.setDigest },
704
+ lockRows: terraformLockRows(input.root, set.changeSet.member.scope, set.json),
705
+ };
706
+ return { member: input.root, planDigest: set.planDigest, artifact, changeSet: set.changeSet, outputs: terraformPlannedOutputs(set.json), shape: terraformPlanShape(set.json, input.root) };
707
+ }
708
+ const { changeSet, json, ...planned } = await planRoot(input, targets, { env, ...(ctx.afterInit ? { afterInit: ctx.afterInit } : {}) });
709
+ // #4552: a choudoufu root's rows, keyed from the plan document while it is at hand.
710
+ const lockRows = changeSet?.member.planner === "choudoufu" ? terraformLockRows(input.root, changeSet.member.scope, json) : undefined;
711
+ return {
712
+ member: input.root,
713
+ planDigest: planned.planDigest,
714
+ artifact: { ...planned, ...(lockRows ? { lockRows } : {}) },
715
+ ...(changeSet ? { changeSet } : {}),
716
+ // plywood#55: each changed resource's own digest, which a merged wave compares with the pull request's per resource.
717
+ resourceDigests: terraformResourceDigests(json),
718
+ outputs: terraformPlannedOutputs(json),
719
+ shape: terraformPlanShape(json, input.root),
720
+ ...(targets ? { targets } : {}),
573
721
  };
574
- return { member: input.root, planDigest: set.planDigest, artifact, changeSet: set.changeSet, outputs: terraformPlannedOutputs(set.json), shape: terraformPlanShape(set.json, input.root) };
575
- }
576
- const { changeSet, json, ...planned } = await planRoot(input, targets);
577
- // #4552: a choudoufu root's rows, keyed from the plan document while it is at hand.
578
- const lockRows = changeSet?.member.planner === "choudoufu" ? terraformLockRows(input.root, changeSet.member.scope, json) : undefined;
579
- return {
580
- member: input.root,
581
- planDigest: planned.planDigest,
582
- artifact: { ...planned, ...(lockRows ? { lockRows } : {}) },
583
- ...(changeSet ? { changeSet } : {}),
584
- // plywood#55: each changed resource's own digest, which a merged wave compares with the pull request's per resource.
585
- resourceDigests: terraformResourceDigests(json),
586
- outputs: terraformPlannedOutputs(json),
587
- shape: terraformPlanShape(json, input.root),
588
- ...(targets ? { targets } : {}),
589
- };
590
- },
591
- // The root's outputs as its state holds them now (#3183): what a dependent
592
- // planned before this root applies reads through `stackOutput()`.
593
- async outputs(_ctx: DeployContext, input: TerraformApplyStepInput): Promise<Record<string, unknown>> {
594
- requireRoot(input);
595
- await terraformInit(rootArgs(input));
596
- return terraformOutputs(rootArgs(input));
597
- },
598
- // #4447 (ws-107): a group core forms of components that read each other plans and applies as one composed run
599
- // when `terraform.compose.enabled` is set (./compose-group.ts). Delegates, so the methods are read when called.
600
- groupReads: (ctx, members) => terraformComposeGroup.groupReads(ctx, members),
601
- // #4542: a member pointed at a release's recorded copy plans alone, since a composition reads the declared roots.
602
- groupFallback: async (ctx, members) =>
603
- members.some((m) => typeof m.step.dir === "string")
604
- ? { kind: "release-copy", reason: "a member deploys a release's recorded copy of its root, which a composition does not read" }
605
- : terraformComposeGroup.groupFallback(ctx, members),
606
- // #4542: the root's files, which a release cut records and a promote under it plans.
607
- releaseInputs: (input, ctx) => terraformReleaseInputs(input, ctx),
608
- // #4552: resource under choudoufu, the root under Terraform, tofu and Terragrunt, which refuse resource by name.
609
- async defaultLockGrain(input, plan) {
610
- return terraformDefaultLockGrain(await plannerOf(input, plan));
611
- },
612
- async lockGrainRefusal(input, grain, plan) {
613
- if (grain !== "resource") return undefined;
614
- const binary = (await rootDir(input).catch(() => undefined))?.binary;
615
- return terraformLockGrainRefusal(grain, await plannerOf(input, plan), binary);
616
- },
617
- // The ruling for ci-products (2026-10-28): a Terraform, tofu or Terragrunt root waits for its root row on the ledger in place of
618
- // the backend's lock. A choudoufu root stays on the resource grain and never asks for this row.
619
- targetLockRow(input) {
620
- return typeof input?.root === "string" && input.root !== "" ? { key: rootRowKey(input.root), target: input.root, address: input.root } : undefined;
621
- },
622
- lockRows(input, plan) {
623
- const kept = (plan.artifact as { lockRows?: LockRow[] } | undefined)?.lockRows;
624
- if (Array.isArray(kept)) return kept;
625
- return plan.changeSet ? terraformLockRowsFromPart(input.root, plan.changeSet) : [];
626
- },
627
- // #4555: the root and the binary, for the step's span and run record.
628
- traceFacts: async (input, outcome) => terraformTraceFacts(input, outcome, (await rootDir(input).catch(() => undefined))?.binary),
629
- planGroup: (ctx, members) => terraformComposeGroup.planGroup(ctx, members),
630
- runGroup: (ctx, run, members) => terraformComposeGroup.runGroup(ctx, run, members),
631
- async run(ctx: DeployContext, input: TerraformApplyStepInput): Promise<TerraformApplyStepOutput> {
632
- const fromWave = ctx.plans?.[input.root];
633
- if (isChoudoufuWavePlan(fromWave)) return runChoudoufuWave(ctx, input, fromWave);
634
- if (isShapeArtifact(fromWave)) {
635
- // A root previewed with stand-ins (#4463): plan it now with the real
636
- // values, and apply that plan only when it is within the preview's shape.
637
- const fresh = await planRoot(await readsForRun(input), ctx.targets);
638
- const differences = planShapeDifferences(fromWave.shape, terraformPlanShape(fresh.json, input.root));
639
- if (differences.length > 0) throw new PlanShapeMovedError(input.root, differences);
640
- const applied = await terraformApply({ ...rootArgs(input), planFile: fresh.planFile, ...lockTimeoutOf(input) });
722
+ },
723
+ // The root's outputs as its state holds them now (#3183): what a dependent
724
+ // planned before this root applies reads through `stackOutput()`.
725
+ async outputs(ctx: DeployContext, step: TerraformApplyStepInput): Promise<Record<string, unknown>> {
726
+ const input = await filledInput(deps.resolveRoot, ctx, step);
727
+ requireRoot(input);
728
+ await terraformInit(rootArgs(input, ctx.processEnv));
729
+ return terraformOutputs(rootArgs(input, ctx.processEnv));
730
+ },
731
+ // #4447 (ws-107): a group core forms of components that read each other plans and applies as one composed run
732
+ // when `terraform.compose.enabled` is set (./compose-group.ts). Delegates, so the methods are read when called.
733
+ groupReads: (ctx, members) => terraformComposeGroup.groupReads(ctx, members),
734
+ // #4542: a member pointed at a release's recorded copy plans alone, since a composition reads the declared roots.
735
+ groupFallback: async (ctx, members) =>
736
+ members.some((m) => typeof m.step.dir === "string")
737
+ ? { kind: "release-copy", reason: "a member deploys a release's recorded copy of its root, which a composition does not read" }
738
+ : terraformComposeGroup.groupFallback(ctx, members),
739
+ // #4542: the root's files, which a release cut records and a promote under it plans.
740
+ releaseInputs: (input, ctx) => terraformReleaseInputs(input, ctx),
741
+ // #4552: resource under choudoufu, the root under Terraform, tofu and Terragrunt, which refuse resource by name.
742
+ async defaultLockGrain(input, plan) {
743
+ return terraformDefaultLockGrain(await plannerOf(input, plan));
744
+ },
745
+ async lockGrainRefusal(input, grain, plan) {
746
+ if (grain !== "resource") return undefined;
747
+ const binary = (await rootDir(input).catch(() => undefined))?.binary;
748
+ return terraformLockGrainRefusal(grain, await plannerOf(input, plan), binary);
749
+ },
750
+ // The ruling for ci-products (2026-10-28): a Terraform, tofu or Terragrunt root waits for its root row on the ledger in place of
751
+ // the backend's lock. A choudoufu root stays on the resource grain and never asks for this row.
752
+ targetLockRow(input) {
753
+ return typeof input?.root === "string" && input.root !== "" ? { key: rootRowKey(input.root), target: input.root, address: input.root } : undefined;
754
+ },
755
+ lockRows(input, plan) {
756
+ const kept = (plan.artifact as { lockRows?: LockRow[] } | undefined)?.lockRows;
757
+ if (Array.isArray(kept)) return kept;
758
+ return plan.changeSet ? terraformLockRowsFromPart(input.root, plan.changeSet) : [];
759
+ },
760
+ // #4555: the root and the binary, for the step's span and run record.
761
+ traceFacts: async (input, outcome) => terraformTraceFacts(input, outcome, (await rootDir(input).catch(() => undefined))?.binary),
762
+ planGroup: (ctx, members) => {
763
+ // chant#4854: each member's lock grain reads the config at the wave's directory too.
764
+ for (const m of members) if (m.input) withContextCwd(m.ctx ?? ctx, m.input);
765
+ return terraformComposeGroup.planGroup(ctx, members);
766
+ },
767
+ runGroup: (ctx, run, members) => {
768
+ for (const m of members) if (m.input) withContextCwd(m.ctx ?? ctx, m.input);
769
+ return terraformComposeGroup.runGroup(ctx, run, members);
770
+ },
771
+ async run(ctx: DeployContext, step: TerraformApplyStepInput): Promise<TerraformApplyStepOutput> {
772
+ const input = await filledInput(deps.resolveRoot, ctx, step);
773
+ const fromWave = ctx.plans?.[input.root];
774
+ if (isChoudoufuWavePlan(fromWave)) return runChoudoufuWave(ctx, input, fromWave);
775
+ if (isShapeArtifact(fromWave)) {
776
+ // A root previewed with stand-ins (#4463): plan it now with the real
777
+ // values, and apply that plan only when it is within the preview's shape.
778
+ const fresh = await planRoot(await readsForRun(input, deps.resolveRoot), ctx.targets, { env: ctx.processEnv });
779
+ const differences = planShapeDifferences(fromWave.shape, terraformPlanShape(fresh.json, input.root));
780
+ if (differences.length > 0) throw new PlanShapeMovedError(input.root, differences);
781
+ const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: fresh.planFile, ...lockTimeoutOf(input) });
782
+ if (!applied.applied) {
783
+ throw new Error(`terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ${applied.refusal ?? ""}`);
784
+ }
785
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
786
+ return { root: input.root, planDigest: fresh.planDigest, fromWavePlan: false, outputs };
787
+ }
788
+ const planned: PlannedRoot = isPlannedRoot(fromWave)
789
+ ? fromWave
790
+ : await planRoot(await readsForRun(input, deps.resolveRoot), ctx.targets, { env: ctx.processEnv }).then(({ planFile, planDigest }) => ({ planFile, planDigest }));
791
+ const applied = await terraformApply({ ...rootArgs(input, ctx.processEnv), planFile: planned.planFile, ...lockTimeoutOf(input) });
641
792
  if (!applied.applied) {
642
- throw new Error(`terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ${applied.refusal ?? ""}`);
793
+ const message =
794
+ `terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ` +
795
+ (applied.refusal ?? "");
796
+ // A plan the wave approved that choudoufu refuses as no longer matching
797
+ // moved since the approval (#4553: one made against another estate is a
798
+ // failure). One this run made itself is planned afresh by the next run.
799
+ if (applied.refused === "approval-mismatch" && isPlannedRoot(fromWave)) throw new TerraformPlanMovedError(input.root, message);
800
+ throw new Error(message);
643
801
  }
644
- const outputs = await terraformOutputs(rootArgs(input));
645
- return { root: input.root, planDigest: fresh.planDigest, fromWavePlan: false, outputs };
646
- }
647
- const planned: PlannedRoot = isPlannedRoot(fromWave)
648
- ? 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) });
651
- if (!applied.applied) {
652
- const message =
653
- `terraform-apply: root "${input.root}" refused the plan it was given (${applied.refused ?? "refused"}). ` +
654
- (applied.refusal ?? "");
655
- // A plan the wave approved that choudoufu refuses as no longer matching
656
- // moved since the approval (#4553: one made against another estate is a
657
- // failure). One this run made itself is planned afresh by the next run.
658
- if (applied.refused === "approval-mismatch" && isPlannedRoot(fromWave)) throw new TerraformPlanMovedError(input.root, message);
659
- throw new Error(message);
660
- }
661
- const outputs = await terraformOutputs(rootArgs(input));
662
- return { root: input.root, planDigest: planned.planDigest, fromWavePlan: isPlannedRoot(fromWave), outputs };
663
- },
664
- };
802
+ const outputs = await terraformOutputs(rootArgs(input, ctx.processEnv));
803
+ return { root: input.root, planDigest: planned.planDigest, fromWavePlan: isPlannedRoot(fromWave), outputs };
804
+ },
805
+ };
806
+ }
807
+
808
+ /** `terraform-apply` with each root on the step's `binary`, else `terraform.binary`. */
809
+ export const terraformApplyCapability: Capability<TerraformApplyStepInput, TerraformApplyStepOutput> = terraformApplyCapabilityWith();
665
810
 
666
811
  export const TERRAFORM_VERB_FAMILIES = {
667
812
  apply: ["terraform-apply"],
@@ -678,7 +823,13 @@ export const terraformCapabilityPlugin: CapabilityPlugin = {
678
823
  return ownPackageVersion(import.meta.url);
679
824
  },
680
825
  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>];
826
+ return [
827
+ terraformApplyCapability as Capability<never, unknown>,
828
+ ...terraformStateOpCapabilities.map((c) => c as unknown as Capability<never, unknown>),
829
+ terraformActionCapability as unknown as Capability<never, unknown>,
830
+ // #4842: Terragrunt units as an op wave's step, found at plan time and run with one run --all.
831
+ terragruntApply as unknown as Capability<never, unknown>,
832
+ ];
682
833
  },
683
834
  families(): Record<string, readonly string[]> {
684
835
  return TERRAFORM_VERB_FAMILIES;
@@ -103,7 +103,8 @@ interface ComposedArtifact {
103
103
  /** What the group methods use, each replaceable in a test. */
104
104
  export interface ComposeGroupDeps {
105
105
  /** The project's config. Default: `loadChantConfigUpward` from the current directory. */
106
- project?: () => Promise<ComposeProject>;
106
+ /** The project at the group's directory (`GroupContext.cwd`, chant#4854), else at `process.cwd()`. */
107
+ project?: (cwd?: string) => Promise<ComposeProject>;
107
108
  /** The run for a composition. Default: `EstateRun` when `estate` is set, else `ComposedRun`. */
108
109
  runner?: (o: GroupRunnerOptions) => ComposedRunner;
109
110
  /**
@@ -128,8 +129,8 @@ export interface ComposeGroupMethods {
128
129
  runGroup(ctx: GroupContext, run: GroupRun, members: readonly GroupMember<StepInput>[]): Promise<CapabilityGroupOutcome>;
129
130
  }
130
131
 
131
- async function loadProject(): Promise<ComposeProject> {
132
- const start = resolve(process.cwd());
132
+ async function loadProject(cwd?: string): Promise<ComposeProject> {
133
+ const start = resolve(cwd ?? process.cwd());
133
134
  const { config, configPath } = await loadChantConfigUpward(start);
134
135
  const projectRoot = configPath ? dirname(configPath) : start;
135
136
  const terraform = (config as { terraform?: TerraformConfig }).terraform;
@@ -369,7 +370,7 @@ export function composeGroup(deps: ComposeGroupDeps = {}): ComposeGroupMethods {
369
370
 
370
371
  /** The composition the group plans as, or throws when it does not compose. */
371
372
  async function composed(ctx: GroupContext, members: readonly GroupMember<StepInput>[]): Promise<{ p: ComposeProject; c: Composition }> {
372
- const p = await project();
373
+ const p = await project(ctx.cwd);
373
374
  const off = composeOff(p.terraform);
374
375
  if (off) throw new Error(off.reason);
375
376
  const c = await compositionOf(ctx, p, members);
@@ -403,14 +404,14 @@ export function composeGroup(deps: ComposeGroupDeps = {}): ComposeGroupMethods {
403
404
  }
404
405
 
405
406
  return {
406
- async groupReads(_ctx, members) {
407
- const p = await project();
407
+ async groupReads(ctx, members) {
408
+ const p = await project(ctx.cwd);
408
409
  if (composeOff(p.terraform)) return [];
409
410
  return hclGroupReads(p, members);
410
411
  },
411
412
 
412
413
  async groupFallback(ctx, members) {
413
- const p = await project();
414
+ const p = await project(ctx.cwd);
414
415
  const off = composeOff(p.terraform);
415
416
  if (off) return { kind: off.kind, reason: off.reason };
416
417
  const c = await compositionOf(ctx, p, members);