Repository navigation
fix(terraform): wire --all to ExecuteTerraformAll for dependency-ordered execution - #2486
Conversation
…red execution `atmos terraform plan --all` and `apply --all` were not running components in dependency order. The dependency-graph implementation in ExecuteTerraformAll (added in cloudposse#1516, closed cloudposse#1242) was reachable from tests but never wired into the CLI dispatcher — --all was being routed to ExecuteTerraformQuery, which iterates components via Go map iteration (randomized order, settings.depends_on ignored). This change: - Splits the dispatcher so --all routes to ExecuteTerraformAll while --components / --query / bare `-s stack` continue to route to ExecuteTerraformQuery (no change for those paths). - Ports the auth manager bootstrap into ExecuteTerraformAll so YAML functions (e.g. !terraform.state) resolve credentials correctly under --all, mirroring the cloudposse#2081 fix in ExecuteTerraformQuery. - Drops the "stack is required" validation that ExecuteTerraformAll inherited from cloudposse#1516 — the documented behavior of --all without -s is to process every stack (see terraform-apply.mdx). - Sets IncludeDependencies: false on the stack/component filter so the scope of `--all -s <stack>` matches what users see today (in-stack topological order; no cross-stack pull-in). A future opt-in flag can add cross-stack execution. - Emits the same `Would <subcmd> <component> in <stack> (dry run)` UI message for dry-run mode in both multi-component paths. - Adds an integration test asserting partial topological order for `terraform plan --all -s prod --dry-run`. Tracking: cloudposse#2485 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
Codecov Report❌ Patch coverage is
❌ Your patch check has failed because the patch coverage (78.57%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #2486 +/- ##
==========================================
+ Coverage 78.24% 78.31% +0.07%
==========================================
Files 1119 1119
Lines 106512 106525 +13
==========================================
+ Hits 83338 83424 +86
+ Misses 18520 18443 -77
- Partials 4654 4658 +4
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
… scope Address codecov patch-coverage gap on PR cloudposse#2486 (22.22% → much higher). The existing validation tests short-circuit on the first guard, leaving the auth-manager bootstrap, ExecuteDescribeStacks, dependency graph build, applyFiltersToGraph, and executeInDependencyOrder branches with no unit-test coverage. - TestExecuteTerraformAll_DryRunHappyPath: walks the full pipeline against the terraform-apply-affected fixture in dry-run mode (no terraform binary needed). Three sub-tests cover no-stack-filter, stack-scoped, and destroy (reverse-order) paths. - TestApplyFiltersToGraph_NoCrossStackPullIn: pins the new IncludeDependencies:false contract — a `--all -s prod` invocation must not pull cross-stack prerequisites from other stacks. Without this test a future flip back to true would silently broaden scope. ExecuteTerraformAll function coverage rises from validation-only to 72.7%; applyFiltersToGraph to 75%. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughCLI ChangesTerraform --all Dependency-Ordered Execution
Sequence DiagramsequenceDiagram
participant CLI as terraformRunWithOptions
participant Wire as wirePerComponentHook
participant Executor as ExecuteTerraformAll
participant Auth as createQueryAuthManager
participant Config as atmosConfig
CLI->>Wire: wire PerComponentHook for subcommand
CLI->>Executor: route when info.All set
Executor->>Auth: createQueryAuthManager()
Auth-->>Executor: authManager
Executor->>Config: SetAuthContextResolver(authManager)
Executor->>Executor: ExecuteDescribeStacks(authManager)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@cmd/terraform/utils.go`:
- Around line 506-515: The --all branch returns early and only wires
info.PerComponentHook for subCommand == "plan", so per-component CI hooks are
not executed for apply/deploy; update the info.All branch (around
ExecuteTerraformAll) to set info.PerComponentHook for all relevant subcommands
(at minimum "plan", "apply", "deploy") — e.g., add a switch or conditional that
assigns info.PerComponentHook to call runCIHooksForPlanComponent for "plan" and
the apply/deploy hook (e.g., runCIHooksForApplyComponent or the existing
apply-hook function) for "apply"/"deploy" before returning from
ExecuteTerraformAll so ExecuteTerraformAll receives the correct per-component
hook.
In `@internal/exec/terraform_all_test.go`:
- Line 4: The test uses a hardcoded fixture path with forward-slash literals
(around the fixture path used in terraform_all_test.go, e.g., the variable or
call that builds the path at Line 303), which is non-portable; replace the
string concatenation or literal like "some/dir/fixture" with filepath.Join(...)
using each path component (and add/import "path/filepath" if missing), and
update the code that references that value (e.g., the fixturePath variable or
the call inside TestTerraformAll) to use filepath.Join("some", "dir", "fixture")
so it works on Windows, macOS, and Linux.
In `@website/blog/2026-05-23-terraform-all-dependency-order-wired-up.mdx`:
- Around line 1-62: Build is failing because the Docusaurus binary isn't
installed before running "npm run build" (error: "sh: 1: docusaurus: not
found"); fix by ensuring website dependencies are installed prior to invoking
the build — update the CI/build step that calls "npm run build" to run "npm ci"
(or "npm install") in the website package first, and confirm package.json
includes the docusaurus dependency (so the "docusaurus build" script runs);
reference the npm script "build" in website/package.json and the missing command
"docusaurus build" when making the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 62ed29f6-5063-4d1a-b9a5-a607053154da
📒 Files selected for processing (8)
cmd/terraform/utils.goerrors/errors.gointernal/exec/terraform_all.gointernal/exec/terraform_all_simple_test.gointernal/exec/terraform_all_test.gointernal/exec/terraform_executor.gotests/test-cases/terraform-multi-component-flags.yamlwebsite/blog/2026-05-23-terraform-all-dependency-order-wired-up.mdx
💤 Files with no reviewable changes (1)
- errors/errors.go
CodeRabbit review on PR cloudposse#2486 surfaced two issues: 1. The --all branch in cmd/terraform/utils.go only wired info.PerComponentHook for `plan`. The parallel ExecuteTerraformQuery branch right below it wires hooks for plan/deploy/apply, so `terraform deploy --all` and `terraform apply --all` were dropping per-component CI summary entries on this path. Mirror the existing pattern. 2. The new TestExecuteTerraformAll_DryRunHappyPath used a hardcoded "../../tests/..." path with forward-slash literals, which is non-portable on Windows. Switch to filepath.Join per CLAUDE.md cross-platform rules. Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
cmd/terraform/utils.go (1)
509-523: ⚡ Quick winDeduplicate per-component hook wiring to prevent branch drift.
This same
plan/deploy/applyhook assignment now exists in both theinfo.AllandisMultiComponentExecutionpaths. Extracting it into one helper will keep future changes from diverging again.♻️ Proposed refactor
+func setPerComponentHook(info *schema.ConfigAndStacksInfo, subCommand string, actualCmd *cobra.Command) { + if subCommand == "plan" { + info.PerComponentHook = func(compInfo *schema.ConfigAndStacksInfo, output string, execErr error) { + runCIHooksForPlanComponent(actualCmd, compInfo, output, execErr) + } + } else if subCommand == "deploy" { + info.PerComponentHook = func(compInfo *schema.ConfigAndStacksInfo, output string, execErr error) { + runCIHooksForDeployComponent(actualCmd, compInfo, output, execErr) + } + } else if subCommand == "apply" { + info.PerComponentHook = func(compInfo *schema.ConfigAndStacksInfo, output string, execErr error) { + runCIHooksForApplyComponent(actualCmd, compInfo, output, execErr) + } + } +} + if info.All { wasMultiComponentExecution = true log.Debug("Routing to ExecuteTerraformAll (dependency-ordered)") - if subCommand == "plan" { - info.PerComponentHook = func(compInfo *schema.ConfigAndStacksInfo, output string, execErr error) { - runCIHooksForPlanComponent(actualCmd, compInfo, output, execErr) - } - } else if subCommand == "deploy" { - info.PerComponentHook = func(compInfo *schema.ConfigAndStacksInfo, output string, execErr error) { - runCIHooksForDeployComponent(actualCmd, compInfo, output, execErr) - } - } else if subCommand == "apply" { - info.PerComponentHook = func(compInfo *schema.ConfigAndStacksInfo, output string, execErr error) { - runCIHooksForApplyComponent(actualCmd, compInfo, output, execErr) - } - } + setPerComponentHook(&info, subCommand, actualCmd) return e.ExecuteTerraformAll(&info) } if isMultiComponentExecution(&info) { wasMultiComponentExecution = true log.Debug("Routing to ExecuteTerraformQuery (multi-component)") - // existing hook wiring... + setPerComponentHook(&info, subCommand, actualCmd) return e.ExecuteTerraformQuery(&info) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@cmd/terraform/utils.go` around lines 509 - 523, The per-component hook assignment for subCommand ("plan"/"deploy"/"apply") is duplicated in both the info.All and isMultiComponentExecution code paths; extract this logic into a single helper (e.g., setPerComponentHook or wirePerComponentHooks) that takes actualCmd, subCommand and the info pointer and assigns info.PerComponentHook appropriately using the existing runCIHooksForPlanComponent, runCIHooksForDeployComponent and runCIHooksForApplyComponent symbols; replace the duplicated blocks in both the info.All and isMultiComponentExecution branches with a single call to that helper so future changes only need one edit.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@cmd/terraform/utils.go`:
- Around line 509-523: The per-component hook assignment for subCommand
("plan"/"deploy"/"apply") is duplicated in both the info.All and
isMultiComponentExecution code paths; extract this logic into a single helper
(e.g., setPerComponentHook or wirePerComponentHooks) that takes actualCmd,
subCommand and the info pointer and assigns info.PerComponentHook appropriately
using the existing runCIHooksForPlanComponent, runCIHooksForDeployComponent and
runCIHooksForApplyComponent symbols; replace the duplicated blocks in both the
info.All and isMultiComponentExecution branches with a single call to that
helper so future changes only need one edit.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f6e86534-8140-4520-8029-53ea4b0076e9
📒 Files selected for processing (2)
cmd/terraform/utils.gointernal/exec/terraform_all_test.go
CodeRabbit nit on PR cloudposse#2486: the per-component CI hook wiring for plan/deploy/apply was duplicated between the --all and --query/--components dispatch branches (the --all branch added the duplication when this PR mirrored the existing block). Extracting wirePerComponentHook centralizes the per-subcommand mapping so adding a new subcommand requires one edit instead of two. No behavior change. Tests in cmd/terraform still pass. Co-Authored-By: Claude Opus 4.7 <[email protected]>
PR cloudposse#2486 extracted wirePerComponentHook to centralize the per-component CI hook wiring used by both ExecuteTerraformAll and ExecuteTerraformQuery dispatch paths. The helper was previously untested — codecov flagged patch coverage at 22% for cmd/terraform/utils.go. Pin its contract: - plan/deploy/apply each install a non-nil hook. - destroy/init/validate/"" leave the hook unset (no-op contract for subcommands that don't have per-component CI hooks today). - Installed hooks don't panic when invoked. - The three subcommands wire to distinct closures (catches a copy-paste regression where, e.g., apply silently invokes the plan hook — that's exactly the class of bug CodeRabbit caught earlier in this PR). wirePerComponentHook function coverage: 0% → 100%. Co-Authored-By: Claude Opus 4.7 <[email protected]>
The auth-manager-non-nil branch added in this PR (the cloudposse#2081 parity port for --all) was the last uncovered patch in terraform_all.go — codecov's stale comment still flagged it. The existing happy-path test exercises only the nil-authManager path because the terraform-apply-affected fixture has no auth config. TestExecuteTerraformAll_AuthManagerResolverWired swaps authManagerFactory for a stub returning a gomock MockAuthManager so the if-non-nil block runs end-to-end. Asserts info.AuthManager is populated as a positive signal that the branch actually executed. ExecuteTerraformAll function coverage: 72.7% → 81.8%. Lines 44-47 (resolver creation + Stores.SetAuthContextResolver) are now hit; only the error paths for InitCliConfig/createQueryAuthManager remain uncovered. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds TestExecuteTerraformAll_AuthManagerCreationError to cover the
last unhit lines that this PR added to terraform_all.go: the
`if err != nil { return err }` branch immediately after
createQueryAuthManager. A regression that silently dropped the error
and proceeded with a nil auth manager would have been invisible to
the existing suite.
Uses errors.Is(err, sentinel) against an injected factory failure so
the assertion stays robust against future re-wrapping in either
ExecuteTerraformAll or createQueryAuthManager.
ExecuteTerraformAll function coverage: 81.8% → 86.4%. The only
remaining uncovered statement in the PR's diff range is the
InitCliConfig error path (line 31-33), which requires a corrupt
fixture to trigger and isn't worth the test-infra cost.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
The terraform-apply.mdx frontmatter has `id: apply`, so the Docusaurus route is `/cli/commands/terraform/apply` rather than `terraform-apply`. The broken link failed the website-deploy-preview check.
Andriy Knysh (aknysh)
left a comment
There was a problem hiding this comment.
thanks thejrose1984
cdbff00
into
cloudposse:main
|
These changes were released in v1.220.0-rc.2. |
These nine carried `authors: [atmos]`, the generic team byline the changelog skill says to avoid. Attribution follows the pull request that implemented the feature, not the commit that added or later renamed the post file. That distinction mattered. Five of the nine appear in `git log --diff-filter=A` as added by #2753, a chronology-correction pass that renamed post files to match their publication dates. Following renames instead points at the real work: list-components-fix #1949 osterman chdir-config-isolation #1941 osterman introducing-atmos-lsp #2030 aknysh introducing-atmos-ai #2030 aknysh ci-comments-env-var #2300 osterman list-instances-matrix #2322 johncblandii terraform-all-dependency-order-wired-up #2486 thejrose1984 dotenv-include-support #1930 osterman toolchain-proxies #1687 osterman Each byline is the GitHub pull request author rather than the git commit author, because squash merges attribute the commit to whoever merged it. #2300 needed a judgment call. It was authored by `app/copilot-swe-agent`, a bot. The byline goes to osterman, who is the assignee and the human who drove the change. A bot is not a contributor byline, and the person who merged it (aknysh) did not do the work either. johncblandii and thejrose1984 were missing from `authors.yml` and are added here, which the changelog skill requires in the same change that references them. thejrose1984 publishes no display name on GitHub, so the login stands in rather than inventing one. Verified: all 263 posts now resolve to a real `authors.yml` entry, no post carries the generic byline, and the site builds with no author warnings. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
What
Routes
atmos terraform plan --allandapply --allthroughExecuteTerraformAllso components actually execute in dependency (topological) order — as originally documented in the PR #1516 changelog and the DAG concurrency PRD.Until this change, the dispatcher in
cmd/terraform/utils.gorouted all multi-component flags (--all,--components,--query) throughExecuteTerraformQuery, which walks components via Go map iteration — randomized order, withsettings.depends_onignored entirely.ExecuteTerraformAll, the function that builds the dependency graph and runsTopologicalSort, was reachable only from unit tests.Why
Fixes #2485.
Users who configured
settings.depends_onand ranatmos terraform apply --allwere relying on a feature that didn't exist at the dispatch layer. Failures looked like Terraform errors (a component applied before its prereqs), not a missing-feature bug. The DAG concurrency PRD was authored on the assumption that this path already worked.Changes
Dispatch
cmd/terraform/utils.go—info.Allnow routes toe.ExecuteTerraformAll(&info).--components/--query/ bare-s stackcontinue to route toExecuteTerraformQuery(no change).ExecuteTerraformAllparity withExecuteTerraformQueryinternal/exec/terraform_all.go— portscreateQueryAuthManagerso YAML functions (e.g.!terraform.state) resolve credentials under--all. Mirrors the #2081 fix that already exists for--query.info.Stack == ""validation. The terraform-apply docs explicitly state--allwithout-sprocesses every stack, and that's the behavior users see today viaExecuteTerraformQuery. Keeping this PR non-breaking required matching that contract.ErrStackRequiredWithAllFlagfromerrors/errors.go.Filter scope
applyFiltersToGraphpreviously setIncludeDependencies: true, which would pull cross-stack prereqs into--all -s <stack>. Switched tofalseso the scope of--all -s <stack>is identical to today's behavior — components in the requested stack only, but now in topological order. A future opt-in flag can re-enable cross-stack execution.Dry-run UX
executeNodeCommandnow emitsWould <subcmd> <component> in <stack> (dry run)viaui.Successf, matchingprocessTerraformComponent. Both multi-component paths produce the same user-facing dry-run output. (This also affects the--affectedpath, which had no integration tests asserting dry-run output — verified manually.)Tests
tests/test-cases/terraform-multi-component-flags.yamlasserts the partial topological order (vpcbeforeeks/cluster,eks/karpenterbeforeeks/karpenter-node-pool,eks/istio/basebeforeeks/istio/istiodbeforeeks/istio/test-app) using the existingterraform-apply-affectedfixture and regex with(?s). The exact total order is an implementation detail of Kahn's-algorithm tie-breaking; this test only asserts the correctness invariant.internal/exec/terraform_all_test.goandterraform_all_simple_test.go— removed the "no stack specified" cases (the validation is gone) and updatedTestApplyFiltersToGraph_*to match the new scope contract.Compatibility matrix
apply --all -s dev,depends_ondefinedapply --all -s dev, nodepends_onapply --all(no stack)apply --all -s devwith cross-stackdepends_ondestroy --all -s dev--allwith circulardepends_onapply --components vpc -s devapply --query '...' -s devapply -s dev(no component, no flag)--allwith!terraform.stateYAML function--allwith per-component CI hooksexecuteNodeCommand)Known follow-ups (not in this PR)
These are tracked in #2485 and intentionally out of scope for the dispatch fix:
DependencyParseronly reads the deprecatedsettings.depends_on. Should also readdependencies.componentslikedescribe_affected_components.goalready does.component+stackkeys are recognized.namespace/tenant/environment/stageare documented but ignored.WarninparseDependencyArray. Should be surfaced.--include-cross-stack-dependenciesflag (orsettings.terraform.dependencies.cross_stack) to re-enable the originalIncludeDependencies: truebehavior.Test plan
go build ./...go vet ./internal/exec/... ./cmd/terraform/... ./errors/...go test ./internal/exec/ ./pkg/dependency/... ./cmd/terraform/... ./errors/... ./pkg/ui/... -short— all greengo test ./tests -run 'TestCLICommands/terraform_plan_--all|TestCLICommands/terraform_plan_--query|TestCLICommands/terraform_plan_--components' -count=1— all greengo test ./tests -run 'TestCLICommands/terraform_plan_--all_executes_in_dependency_order' -count=1— green; output confirmsvpc → eks/cluster → eks/external-dns → eks/istio/base → eks/karpenter → eks/istio/istiod → eks/karpenter-node-pool → eks/istio/test-appmake lint)dependencies.components(new format) once parser is extended in a follow-upReferences
terraform plan/apply --alldoes not execute components in dependency order #2485docs/prd/dag-concurrent-execution.md🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
terraform plan --allandapply --allrun components in dependency (topological) order;destroy --allruns in reverse.--allmay be used without a stack;--all -s <stack>scopes to that stack without pulling cross‑stack prerequisites. Per‑component hooks and auth-aware YAML resolution are active during--allruns; dry‑run shows clear per‑component success messages.Tests
--allordering, scoping/filtering, auth wiring, dry‑run flows, and per‑component hook wiring.Documentation
--allbehavior, caveats, and follow-ups.