Skip to content

DAG follow-up: aggregate CI output for concurrent Terraform runs - #2577

Merged
Andriy Knysh (aknysh) merged 21 commits into
mainfrom
codex/dag-github-concurrent-output
Jun 10, 2026
Merged

Andriy Knysh (aknysh) merged 21 commits into
mainfrom
codex/dag-github-concurrent-output

Conversation

@shirkevich

@shirkevich Mikhail Shirkov (shirkevich) commented Jun 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Follow-up to the graph-backed Terraform DAG execution work: concurrent multi-component Terraform plan, apply, and destroy runs now produce one deterministic aggregate CI result after the scheduler completes.
  • GitHub Actions remains the first integration surface because native --ci detection, $GITHUB_STEP_SUMMARY, $GITHUB_OUTPUT, PR comments, and commit statuses make the DAG behavior easy to verify end-to-end while hardening the shared concurrent execution path.
  • Keeps the existing public interface: no new CLI flag or atmos.yaml setting. This reuses ci.enabled, --ci, CI provider auto-detection, ci.summary, ci.output, ci.comments, ci.checks, --max-concurrency, --hide, and --log-order.
  • Single-component plan/apply/deploy behavior and non-CI multi-component behavior stay on their existing paths. Deploy remains on the existing deploy hook path.

Scope

  • Adds an aggregate Terraform CI path for graph-backed multi-component plan, apply, and destroy runs when CI mode is enabled.
  • Collects scheduler node outcomes during DAG execution and writes CI artifacts once after the scheduler finishes.
  • Serializes summary, output-variable, comment, status, and planfile side effects so worker goroutines do not write to CI files concurrently.
  • Preserves existing scheduler semantics for fail-fast, keep-going, skipped dependents, concurrency limits, workdir locking, and command ordering. destroy still runs in reverse dependency order.
  • Keeps plan-specific behavior plan-specific: aggregate planfile upload remains plan-only, and aggregate exit code 2 is used only for plan changes. Aggregate apply/destroy return 1 on failure, otherwise 0.

Anonymized Findings From DAG/CI Validation

These findings are intentionally generalized. They do not include downstream repository names, stack names, project IDs, workflow run IDs, service accounts, secrets, or environment identifiers.

  • Per-component CI hooks are not a good fit for DAG concurrency: parallel workers can race when writing $GITHUB_STEP_SUMMARY, $GITHUB_OUTPUT, comments, or statuses. The fix is to collect component results and emit one aggregate CI result after the DAG completes.
  • Graph setup can evaluate YAML store functions before Terraform workers run. Identity-aware stores need the selected/default Atmos identity during stack resolution, not just inside the later Terraform subprocess.
  • GCP Secret Manager store access should use the Atmos-selected GCP identity token when available, before falling back to file-based ADC behavior. This avoids requiring a separate GitHub Actions ADC bootstrap solely for YAML store evaluation.
  • Parallel auth pre-hooks can read credential files while another worker is writing them. GCP ADC, properties, and access-token file writes now use locking plus atomic writes to avoid partial JSON reads.
  • Shared Terraform/OpenTofu plugin caches are unsafe for concurrent init. Concurrent graph execution now disables plugin-cache env/config for worker subprocesses when effective concurrency is greater than one, favoring parallelism over shared cache reuse.
  • Aggregate details need line-aligned truncation. GitHub summaries are much easier to inspect when truncated Terraform output starts at a complete line instead of the middle of a resource block or attribute.
  • Review cleanup split aggregate rendering/provider writes into focused files, removed dynamic error construction in changed code, preserved sentinel matching for error handling, and aligned changed-code lint with repo guidelines.

Implementation Notes

  • cmd/terraform installs an aggregate result handler for graph-backed Terraform plan, apply, and destroy when CI mode is enabled.
  • pkg/scheduler/adapters captures node status, exit code, stdout/stderr, log files, timings, changed state, and skipped/failed outcomes, then finalizes a TerraformPlanCIResultSet after DAG execution.
  • pkg/ci/plugins/terraform renders one deterministic aggregate summary with component totals, resource totals, failed/changed/no-change/skipped groups, a per-component table, and details for failed/changed components.
  • Aggregate output variables are written once in stable key order: has_changes, has_errors, exit_code, resource totals, component totals, summary, command, stack, and component.
  • Optional PR comments and status contexts remain behind existing config gates and are serialized.
  • Store identity wiring applies the selected/default identity to identity-aware stores during stack/YAML function resolution.
  • GCP auth/client setup can use an identity access token directly, and credential file writes are atomic under the existing per-file locks.
  • Concurrent Terraform/OpenTofu worker subprocesses strip plugin-cache settings instead of serializing the whole run behind a cache mutex.

Documentation

  • Documents aggregate GitHub job summaries for graph-backed concurrent Terraform plan, apply, and destroy.
  • Documents aggregate $GITHUB_OUTPUT variables and the difference from single-component last-writer behavior.
  • Updates native CI docs to reflect destroy parser support and aggregate Terraform command results.

Validation

  • rtk env GOCACHE=/private/tmp/atmos-go-build-cache go test ./cmd/terraform ./pkg/ci/plugins/terraform ./pkg/scheduler/adapters ./pkg/hooks ./pkg/ci
  • rtk env GOCACHE=/private/tmp/atmos-go-build-cache go test -race ./pkg/ci/plugins/terraform ./pkg/scheduler/adapters
  • rtk env GOCACHE=/private/tmp/atmos-go-build-cache go test -cover ./cmd/terraform ./pkg/ci/plugins/terraform ./pkg/scheduler/adapters
  • rtk proxy env GOCACHE=/private/tmp/atmos-go-build-cache GOLANGCI_LINT_CACHE=/private/tmp/atmos-golangci-lint-cache ./custom-gcl run ./... --new-from-rev=origin/main (0 issues)
  • rtk env GOCACHE=/private/tmp/atmos-go-build-cache make build VERSION=dev-009a904f40

Summary by CodeRabbit

  • New Features

    • CI: Deterministic aggregate job summaries and outputs for multi-component Terraform plan/apply/destroy runs (per-component details, counts, aggregate exit code)
    • CLI: Improved CI-mode detection (flag, config, native envs) and GitHub Actions-friendly aggregate output emission
    • Auth: Support for Google Cloud access token authentication
    • Terraform: Added destroy-output parsing and multi-component plan aggregation
  • Documentation

    • Added/expanded docs for aggregate CI job summaries and aggregate output variables

@atmos-pro

atmos-pro Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions github-actions Bot added the size/l Large size PR label Jun 6, 2026
@github-actions

github-actions Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@shirkevich Mikhail Shirkov (shirkevich) added the no-release Do not create a new release (wait for additional code changes) label Jun 6, 2026
@codecov

codecov Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.94349% with 90 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.03%. Comparing base (3c1aba3) to head (c461f1f).

Files with missing lines Patch % Lines
pkg/ci/plugins/terraform/aggregate_render.go 86.81% 27 Missing and 2 partials ⚠️
pkg/auth/cloud/gcp/files.go 32.43% 19 Missing and 6 partials ⚠️
pkg/ci/plugins/terraform/aggregate.go 96.02% 5 Missing and 2 partials ⚠️
cmd/terraform/utils.go 86.95% 5 Missing and 1 partial ⚠️
pkg/scheduler/adapters/terraform.go 92.00% 5 Missing and 1 partial ⚠️
pkg/store/google_secret_manager_store.go 80.95% 2 Missing and 2 partials ⚠️
pkg/store/registry.go 80.00% 2 Missing and 2 partials ⚠️
pkg/ci/plugins/terraform/aggregate_provider.go 97.41% 2 Missing and 1 partial ⚠️
internal/exec/terraform_execute_helpers.go 84.61% 2 Missing ⚠️
pkg/ci/plugins/terraform/parser.go 86.66% 1 Missing and 1 partial ⚠️
... and 2 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2577      +/-   ##
==========================================
+ Coverage   78.91%   79.03%   +0.12%     
==========================================
  Files        1207     1210       +3     
  Lines      116464   117219     +755     
==========================================
+ Hits        91906    92645     +739     
- Misses      19488    19493       +5     
- Partials     5070     5081      +11     
Flag Coverage Δ
unittests 79.03% <88.94%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
internal/exec/terraform_affected.go 85.43% <100.00%> (-0.10%) ⬇️
internal/exec/terraform_all.go 77.92% <100.00%> (-0.15%) ⬇️
internal/exec/terraform_execute_helpers_exec.go 85.52% <100.00%> (+0.06%) ⬆️
internal/exec/terraform_query.go 100.00% <100.00%> (ø)
internal/exec/utils_auth.go 96.34% <100.00%> (ø)
internal/gcp/auth.go 82.75% <100.00%> (+5.48%) ⬆️
pkg/ci/executor.go 79.86% <100.00%> (+0.13%) ⬆️
pkg/ci/internal/plugin/types.go 100.00% <ø> (ø)
pkg/ci/plugins/terraform/handlers.go 61.03% <ø> (+1.03%) ⬆️
pkg/ci/plugins/terraform/plugin.go 96.19% <100.00%> (+2.50%) ⬆️
... and 18 more

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@shirkevich

Copy link
Copy Markdown
Collaborator Author

CodeRabbit (@coderabbitai) review

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d1421dee-a5f1-490e-b203-f24d35924e36

📥 Commits

Reviewing files that changed from the base of the PR and between 47e2f64 and c461f1f.

📒 Files selected for processing (1)
  • cmd/terraform/utils_hooks_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/terraform/utils_hooks_test.go

📝 Walkthrough

Walkthrough

Adds CI-mode detection and a Terraform aggregate CI flow: new result contracts and events, propagate aggregate payload through hooks, capture scheduler outputs, finalize aggregate results, render/write provider artifacts (summary/outputs/planfiles/checks/comments), and supporting parser/auth/store/credential and test/docs updates.

Changes

Terraform CI aggregation and execution updates

Layer / File(s) Summary
Aggregate contracts and hook payload path
pkg/schema/schema.go, pkg/hooks/event.go, pkg/hooks/hooks.go, pkg/ci/executor.go, pkg/ci/executor_test.go, pkg/ci/internal/plugin/types.go
New TerraformPlanCIResultHandler, TerraformPlanCIResultSet/TerraformPlanCIResult, DisablePluginCache on ConfigAndStacksInfo. Aggregate payload propagates through RunCIHooksOptions, ExecuteOptions, and HookContext with tests.
CLI CI-mode detection and handler wiring
cmd/terraform/utils.go, cmd/terraform/utils_hooks_test.go
terraformCIModeEnabled() reads --ci, viper ci, then native detection; wirePerComponentHook installs TerraformPlanCIResultHandler for plan/apply/destroy when CI mode is enabled and tests validate wiring and detection sources.
Scheduler output capture and CI finalization
pkg/scheduler/adapters/terraform.go, pkg/scheduler/adapters/terraform_test.go
Capture executor combined output per node, deep-clone env sections per node, call finalizeTerraformCIResults to build TerraformPlanCIResultSet and call configured handler; adds concurrency-aware plugin-cache handling and tests for handler invocation and error guarding.
Terraform aggregate normalization and orchestration
pkg/ci/plugins/terraform/aggregate.go
onAfterTerraformAggregate normalizes payload, stably sorts components, builds per-component render models, accumulates resource/component totals, computes aggregate exit code and summary, and drives artifact writes behind gates.
Provider outputs, planfiles, checks, and comments
pkg/ci/plugins/terraform/aggregate_provider.go
Provider-backed functions write aggregate markdown, deterministic CI outputs (filtered by allowlist), upload non-skipped planfiles, update per-component check runs, and post/update aggregate PR comment markers.
Rendering, parsing, and plugin bindings
pkg/ci/plugins/terraform/aggregate_render.go, pkg/ci/plugins/terraform/handlers.go, pkg/ci/plugins/terraform/parser.go, pkg/ci/plugins/terraform/plugin.go, pkg/ci/plugins/terraform/plugin_test.go
Markdown renderer for aggregate summary with tables, resource totals, collapsible details and truncation; adds destroy output parsing; plugin registers aggregate hook bindings and measures execution time.
Aggregate behavior test matrix
pkg/ci/plugins/terraform/aggregate_test.go
Extensive tests covering rendering, outputs, exit-code rules, planfile upload, writer error handling, truncation, comment behavior, and robustness/fallbacks.
Execution-time plugin-cache controls
internal/exec/terraform.go, internal/exec/terraform_execute_helpers_exec.go, internal/exec/terraform_plugin_cache_test.go
Named plugin-cache env constants, disableTerraformPluginCacheForExecution to clear cache flags/env for a run when DisablePluginCache is set, wired into pre-exec steps, and tested for configured/unsanitized/no-op cases.
Terraform execution auth resolver refactor
internal/exec/terraform_execute_helpers.go, internal/exec/terraform_affected.go, internal/exec/terraform_all.go, internal/exec/terraform_all_test.go, internal/exec/terraform_query.go, internal/exec/terraform_shell.go, internal/exec/utils_auth.go, internal/exec/utils_auth_test.go
Introduces injectTerraformStoreAuthResolver to centralize auth resolver wiring across execution entrypoints, refines when auto-detected identity is stored, and strengthens related tests.
Store default identity and client reset behavior
pkg/store/registry.go, pkg/store/aws_ssm_param_store.go, pkg/store/azure_keyvault_store.go, pkg/store/google_secret_manager_store.go, pkg/store/identity_test.go
SetAuthContextResolverWithDefaultIdentity applies resolver with per-store default identity for empty-identity stores; identity-aware stores now clear initialized clients on identity change; GSM credential selection refactored. Tests added/updated.
GCP access-token auth plumbing
pkg/store/identity.go, internal/gcp/auth.go, internal/gcp/auth_test.go, pkg/store/authbridge/resolver.go, pkg/store/authbridge/resolver_test.go
Adds AccessToken and TokenExpiry to auth structs, GetClientOptions supports token-source auth, and resolver propagates token fields; tests validate the token path and fallbacks.
GCP credential file IO hardening
pkg/auth/cloud/gcp/files.go, pkg/auth/cloud/gcp/files_test.go
Credential file writes use atomic filesystem writes, standardized credential-file error wrapping, initial TryLock, safer lock cleanup, and concurrent-read tests to avoid partial JSON reads.
Test sandbox and YAML helpers
internal/exec/terraform_yaml_test_helpers_test.go, multiple internal tests
Adds sandbox helper and switches tests to t.Setenv and centralized sandbox setup/cleanup to improve isolation and concurrency safety.
Docs and workflow updates
website/docs/, docs/prd/
Docs and PRD updated to document aggregate multi-component plan summaries, aggregate CI outputs, and serialized GitHub job-summary behavior for plan/apply/destroy.

Sequence Diagram (aggregate CI flow)

sequenceDiagram
  participant Scheduler as Scheduler
  participant Dispatcher as TerraformDispatcher
  participant Finalize as finalizeTerraformCIResults
  participant Handler as TerraformPlanCIResultHandler
  participant RunHooks as RunCIHooks
  participant Provider as CIProvider

  Scheduler->>Dispatcher: dispatch graph nodes
  Dispatcher->>Dispatcher: capture executor CombinedOutput per node
  Dispatcher->>Finalize: return node outcomes + timings
  Finalize->>Handler: HandleTerraformPlanCIResults(resultSet)
  Handler->>RunHooks: RunCIHooks(event=after.terraform.*.aggregate, Aggregate=resultSet)
  RunHooks->>Provider: writeAggregateSummary / writeAggregateOutputs / postAggregateComment
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • cloudposse/atmos#2486: Overlaps with per-component hook wiring changes in cmd/terraform/utils.go.
  • cloudposse/atmos#2430: Related multi-component CI plan wiring and aggregate handling for plan/apply/destroy.
  • cloudposse/atmos#2382: Related CI hook context/ExecuteOptions changes affecting aggregate payload propagation.

Suggested reviewers

  • aknysh
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/dag-github-concurrent-output

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cmd/terraform/utils_hooks_test.go (1)

36-41: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Extend the compile-time schema sentinel for the new field.

The test now relies on ConfigAndStacksInfo.TerraformPlanCIResultHandler, but the sentinel block doesn’t include it yet.

Suggested fix
 var _ = schema.ConfigAndStacksInfo{
 	Stack:            "",
 	Component:        "",
 	ComponentFromArg: "",
 	ComponentType:    "",
+	TerraformPlanCIResultHandler: nil,
 }

As per coding guidelines, “Add compile-time sentinels for schema field references in tests.”

Also applies to: 499-501, 509-510

🤖 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_hooks_test.go` around lines 36 - 41, The compile-time
sentinel block for schema.ConfigAndStacksInfo in the test is missing the
TerraformPlanCIResultHandler field that is now being referenced in the test. Add
the TerraformPlanCIResultHandler field to the sentinel block (the var _ =
schema.ConfigAndStacksInfo{...} declaration around lines 36-41) with an
appropriate zero value. Also apply the same field addition to the other sentinel
blocks mentioned at lines 499-501 and 509-510 to ensure all references to this
schema field are covered by compile-time sentinels as per the coding guidelines.

Source: Coding guidelines

🧹 Nitpick comments (2)
pkg/ci/plugins/terraform/aggregate_test.go (2)

161-237: ⚡ Quick win

Add compile-time sentinels for schema field references used by this fixture.

This helper hardcodes many schema.TerraformPlanCIResult fields; a small compile-guard will fail fast on schema field renames instead of silently drifting test fixtures.

Suggested guard block
+var _ = schema.TerraformPlanCIResult{
+	NodeID:     "",
+	Stack:      "",
+	Component:  "",
+	Status:     "",
+	Processed:  false,
+	Changed:    false,
+	ExitCode:   0,
+	Output:     "",
+	LogFiles:   nil,
+	StartedAt:  time.Time{},
+	FinishedAt: time.Time{},
+	DurationMS: 0,
+	Error:      "",
+}
+
 func newAggregateHookContext() *plugin.HookContext {

As per coding guidelines, **/*_test.go: “Add compile-time sentinels for schema field references in tests… so field rename immediately fails the build”.

🤖 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 `@pkg/ci/plugins/terraform/aggregate_test.go` around lines 161 - 237, The test
fixture newAggregateHookContext() hardcodes many schema.TerraformPlanCIResult
fields; add a small compile-time sentinel near that helper (e.g., a var _ =
[]schema.TerraformPlanCIResult{{NodeID: "", Stack: "", Component: "", Status:
"", Processed: false, Changed: false, ExitCode: 0, Output: "", Error: "",
StartedAt: time.Time{}, FinishedAt: time.Time{}, DurationMS: 0}}) that
references every schema field used in the fixture so any schema field rename
triggers a compile error; place the sentinel in the same test file adjacent to
newAggregateHookContext() and import time if needed.

Source: Coding guidelines


74-126: ⚡ Quick win

Use a table-driven test for the exit-code rule matrix.

This block covers three independent scenarios in one linear body; converting to table-driven keeps expansion safer and aligns with repository test conventions.

Refactor sketch
 func TestBuildPlanAggregateExitCodeRules(t *testing.T) {
 	p := &Plugin{}
-
-	noChanges := p.buildPlanAggregate(schema.TerraformPlanCIResultSet{Results: []schema.TerraformPlanCIResult{
-		{
-			NodeID:    "vpc-dev",
-			Stack:     "dev",
-			Component: "vpc",
-			Status:    "succeeded",
-			Processed: true,
-			Output:    "No changes. Your infrastructure matches the configuration.",
-		},
-	}})
-	assert.Equal(t, 0, noChanges.ExitCode)
-
-	changes := p.buildPlanAggregate(schema.TerraformPlanCIResultSet{Results: []schema.TerraformPlanCIResult{
-		{
-			NodeID:    "vpc-dev",
-			Stack:     "dev",
-			Component: "vpc",
-			Status:    "succeeded",
-			Processed: true,
-			Changed:   true,
-			ExitCode:  2,
-			Output:    "Plan: 1 to add, 0 to change, 0 to destroy.",
-		},
-	}})
-	assert.Equal(t, 2, changes.ExitCode)
-
-	failed := p.buildPlanAggregate(schema.TerraformPlanCIResultSet{Results: []schema.TerraformPlanCIResult{
-		{
-			NodeID:    "vpc-dev",
-			Stack:     "dev",
-			Component: "vpc",
-			Status:    "failed",
-			Processed: true,
-			ExitCode:  1,
-			Output:    "Error: invalid value",
-			Error:     "terraform failed",
-		},
-		{
-			NodeID:    "database-dev",
-			Stack:     "dev",
-			Component: "database",
-			Status:    "succeeded",
-			Processed: true,
-			Changed:   true,
-			ExitCode:  2,
-			Output:    "Plan: 1 to add, 0 to change, 0 to destroy.",
-		},
-	}})
-	assert.Equal(t, 1, failed.ExitCode)
+	cases := []struct {
+		name    string
+		set     schema.TerraformPlanCIResultSet
+		wantCode int
+	}{
+		{
+			name: "no changes",
+			set: schema.TerraformPlanCIResultSet{Results: []schema.TerraformPlanCIResult{
+				{NodeID: "vpc-dev", Stack: "dev", Component: "vpc", Status: "succeeded", Processed: true, Output: "No changes. Your infrastructure matches the configuration."},
+			}},
+			wantCode: 0,
+		},
+		{
+			name: "changes",
+			set: schema.TerraformPlanCIResultSet{Results: []schema.TerraformPlanCIResult{
+				{NodeID: "vpc-dev", Stack: "dev", Component: "vpc", Status: "succeeded", Processed: true, Changed: true, ExitCode: 2, Output: "Plan: 1 to add, 0 to change, 0 to destroy."},
+			}},
+			wantCode: 2,
+		},
+		{
+			name: "failed dominates changes",
+			set: schema.TerraformPlanCIResultSet{Results: []schema.TerraformPlanCIResult{
+				{NodeID: "vpc-dev", Stack: "dev", Component: "vpc", Status: "failed", Processed: true, ExitCode: 1, Output: "Error: invalid value", Error: "terraform failed"},
+				{NodeID: "database-dev", Stack: "dev", Component: "database", Status: "succeeded", Processed: true, Changed: true, ExitCode: 2, Output: "Plan: 1 to add, 0 to change, 0 to destroy."},
+			}},
+			wantCode: 1,
+		},
+	}
+
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			got := p.buildPlanAggregate(tc.set)
+			assert.Equal(t, tc.wantCode, got.ExitCode)
+		})
+	}
 }

As per coding guidelines, **/*_test.go: “Use table-driven tests for testing multiple scenarios in Go”.

🤖 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 `@pkg/ci/plugins/terraform/aggregate_test.go` around lines 74 - 126, Split the
linear TestBuildPlanAggregateExitCodeRules into a table-driven test: create a
slice of test cases each with a name, input TerraformPlanCIResultSet and
expected ExitCode, then range over them and call t.Run(tc.name, func(t
*testing.T) { got := (&Plugin{}).buildPlanAggregate(tc.input); assert.Equal(t,
tc.want, got.ExitCode) }). Keep the same example result objects (used currently
inline) as case inputs for the "no changes", "changes", and "failed" scenarios
and reuse the Plugin.buildPlanAggregate symbol and
TestBuildPlanAggregateExitCodeRules name when replacing the body. Ensure each
case is independent and includes a descriptive name for clarity.

Source: Coding guidelines

🤖 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 284-287: Replace the free-form fmt.Errorf wrapper around
cfg.InitCliConfig with a static sentinel error from the repository errors
package: import the project errors package and change the return to wrap the
call error with the static error (e.g. return fmt.Errorf("%w: %v",
errors.ErrCIHookConfigInit, err)) so the code uses the repository's predefined
error value; update the import list if needed and reference cfg.InitCliConfig
and handler.info when making the change.

In `@pkg/ci/plugins/terraform/aggregate_test.go`:
- Around line 166-167: The fixture sets HookContext.EventPrefix to "terraform"
which violates the hook context contract (must be "before" or "after"); update
the test fixture created by newAggregateTestConfig (or where
HookContext.EventPrefix is assigned) to use a valid value such as "before" (or
"after" if the test intends to simulate post-hook behavior) so the EventPrefix
field in the HookContext fixture matches the contract and restores correct
event-routing test semantics.

In `@pkg/ci/plugins/terraform/aggregate.go`:
- Around line 498-503: The loop that calls writer.WriteOutput over keys
currently only logs failures (log.Warn in aggregate.go) and returns nil, which
swallows errors; change it to collect each non-nil error from
writer.WriteOutput(key, vars[key]) (referencing writer.WriteOutput and the
keys/vars loop), accumulate them using errors.Join (wrap individual errors with
context if helpful), and after the loop return the joined error (or nil if no
errors) instead of always returning nil so upstream can fail deterministically
on write failures.

In `@pkg/scheduler/adapters/terraform_test.go`:
- Around line 1444-1458: The test is appending to the shared slice captureFlags
from the concurrent Executor callback (used via ExecuteTerraform with
MaxConcurrency: 2), which can race; protect access by synchronizing appends:
introduce a mutex (or a channel/atomic-safe structure) and use it inside the
Executor closure when modifying captureFlags, e.g., lock before append and
unlock after, or send values to a single goroutine that collects them; update
references to captureFlags and the Executor function accordingly (symbols:
captureFlags, ExecuteTerraform, TerraformOptions.Executor, TerraformExecution)
to ensure thread-safe collection.

---

Outside diff comments:
In `@cmd/terraform/utils_hooks_test.go`:
- Around line 36-41: The compile-time sentinel block for
schema.ConfigAndStacksInfo in the test is missing the
TerraformPlanCIResultHandler field that is now being referenced in the test. Add
the TerraformPlanCIResultHandler field to the sentinel block (the var _ =
schema.ConfigAndStacksInfo{...} declaration around lines 36-41) with an
appropriate zero value. Also apply the same field addition to the other sentinel
blocks mentioned at lines 499-501 and 509-510 to ensure all references to this
schema field are covered by compile-time sentinels as per the coding guidelines.

---

Nitpick comments:
In `@pkg/ci/plugins/terraform/aggregate_test.go`:
- Around line 161-237: The test fixture newAggregateHookContext() hardcodes many
schema.TerraformPlanCIResult fields; add a small compile-time sentinel near that
helper (e.g., a var _ = []schema.TerraformPlanCIResult{{NodeID: "", Stack: "",
Component: "", Status: "", Processed: false, Changed: false, ExitCode: 0,
Output: "", Error: "", StartedAt: time.Time{}, FinishedAt: time.Time{},
DurationMS: 0}}) that references every schema field used in the fixture so any
schema field rename triggers a compile error; place the sentinel in the same
test file adjacent to newAggregateHookContext() and import time if needed.
- Around line 74-126: Split the linear TestBuildPlanAggregateExitCodeRules into
a table-driven test: create a slice of test cases each with a name, input
TerraformPlanCIResultSet and expected ExitCode, then range over them and call
t.Run(tc.name, func(t *testing.T) { got :=
(&Plugin{}).buildPlanAggregate(tc.input); assert.Equal(t, tc.want, got.ExitCode)
}). Keep the same example result objects (used currently inline) as case inputs
for the "no changes", "changes", and "failed" scenarios and reuse the
Plugin.buildPlanAggregate symbol and TestBuildPlanAggregateExitCodeRules name
when replacing the body. Ensure each case is independent and includes a
descriptive name for clarity.
🪄 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: b364c43f-7f21-4499-8254-58c44c6fadec

📥 Commits

Reviewing files that changed from the base of the PR and between 01b3c60 and 16a3316.

📒 Files selected for processing (14)
  • cmd/terraform/utils.go
  • cmd/terraform/utils_hooks_test.go
  • pkg/ci/executor.go
  • pkg/ci/executor_test.go
  • pkg/ci/internal/plugin/types.go
  • pkg/ci/plugins/terraform/aggregate.go
  • pkg/ci/plugins/terraform/aggregate_test.go
  • pkg/ci/plugins/terraform/plugin.go
  • pkg/ci/plugins/terraform/plugin_test.go
  • pkg/hooks/event.go
  • pkg/hooks/hooks.go
  • pkg/scheduler/adapters/terraform.go
  • pkg/scheduler/adapters/terraform_test.go
  • pkg/schema/schema.go

Comment thread cmd/terraform/utils.go Resolved
Comment thread pkg/ci/plugins/terraform/aggregate.go Resolved
@shirkevich

Copy link
Copy Markdown
Collaborator Author

CodeRabbit (@coderabbitai) review

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@shirkevich

Copy link
Copy Markdown
Collaborator Author

CodeRabbit (@coderabbitai) review

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
cmd/terraform/utils_hooks_test.go (1)

38-44: ⚡ Quick win

Consider including PerComponentHook in the sentinel.

The sentinel correctly guards TerraformPlanCIResultHandler, but PerComponentHook is also heavily referenced in this test file (lines 505, 520, 532, 545, etc.). Adding it would ensure upstream renames immediately fail the build.

🛡️ Strengthen the sentinel
 var _ = schema.ConfigAndStacksInfo{
 	Stack:                        "",
 	Component:                    "",
 	ComponentFromArg:             "",
 	ComponentType:                "",
 	TerraformPlanCIResultHandler: nil,
+	PerComponentHook:             nil,
 }
🤖 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_hooks_test.go` around lines 38 - 44, The current sentinel
value for schema.ConfigAndStacksInfo guards TerraformPlanCIResultHandler but
omits the PerComponentHook field; update the sentinel (the var _ =
schema.ConfigAndStacksInfo{ ... }) to include PerComponentHook: nil so any
upstream rename of PerComponentHook will break the build immediately—keep
TerraformPlanCIResultHandler as-is and add the PerComponentHook entry to the
struct literal.

Source: Coding guidelines

🤖 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_hooks_test.go`:
- Around line 38-44: The current sentinel value for schema.ConfigAndStacksInfo
guards TerraformPlanCIResultHandler but omits the PerComponentHook field; update
the sentinel (the var _ = schema.ConfigAndStacksInfo{ ... }) to include
PerComponentHook: nil so any upstream rename of PerComponentHook will break the
build immediately—keep TerraformPlanCIResultHandler as-is and add the
PerComponentHook entry to the struct literal.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b74c63c0-6c44-4f7e-a8ac-53f16323a362

📥 Commits

Reviewing files that changed from the base of the PR and between 16a3316 and 628b149.

📒 Files selected for processing (8)
  • cmd/terraform/utils.go
  • cmd/terraform/utils_hooks_test.go
  • pkg/ci/plugins/terraform/aggregate.go
  • pkg/ci/plugins/terraform/aggregate_test.go
  • pkg/scheduler/adapters/terraform_test.go
  • website/docs/ci/job-summaries.mdx
  • website/docs/cli/commands/terraform/terraform-plan.mdx
  • website/docs/cli/configuration/ci/output.mdx
✅ Files skipped from review due to trivial changes (1)
  • website/docs/cli/commands/terraform/terraform-plan.mdx
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/scheduler/adapters/terraform_test.go
  • cmd/terraform/utils.go
  • pkg/ci/plugins/terraform/aggregate.go

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 6, 2026
@shirkevich

Copy link
Copy Markdown
Collaborator Author

CodeRabbit (@coderabbitai) review

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@aknysh

Copy link
Copy Markdown
Member

Mikhail Shirkov (@shirkevich) please resolve the conflicts and ping me for review. Also, address the comments

@mergify

mergify Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it Mikhail Shirkov (@shirkevich)? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Jun 9, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but please remove the changes for codecov action, and instead bump to v7.

codecov/codecov-action#1956

…urrent-output

# Conflicts:
#	pkg/hooks/event.go
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/exec/yaml_func_terraform_output_test.go (1)

27-37: ⚡ Quick win

Redundant environment variable initialization before sandbox setup helpers.

All six test sites manually set ATMOS_CLI_CONFIG_PATH and ATMOS_BASE_PATH via t.Setenv, then immediately call a sandbox helper that sets environment variables internally. The sandbox helpers (setupTerraformYamlFunctionSandbox in internal/exec tests and setupDoubleHyphenSandbox in CLI tests) already handle environment configuration, making the manual t.Setenv calls redundant. Remove the manual environment setup before each helper invocation.

🤖 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 `@internal/exec/yaml_func_terraform_output_test.go` around lines 27 - 37,
Remove the redundant manual environment setup calls to
t.Setenv("ATMOS_CLI_CONFIG_PATH", "") and t.Setenv("ATMOS_BASE_PATH", "") before
invoking the sandbox helpers; the helper function
setupTerraformYamlFunctionSandbox (and similar setupDoubleHyphenSandbox used
elsewhere) already configures those env vars internally, so delete the explicit
t.Setenv lines and keep only the working directory setup and the call to
setupTerraformYamlFunctionSandbox in the test.
🤖 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 `@internal/exec/yaml_func_terraform_output_test.go`:
- Around line 27-37: Remove the redundant manual environment setup calls to
t.Setenv("ATMOS_CLI_CONFIG_PATH", "") and t.Setenv("ATMOS_BASE_PATH", "") before
invoking the sandbox helpers; the helper function
setupTerraformYamlFunctionSandbox (and similar setupDoubleHyphenSandbox used
elsewhere) already configures those env vars internally, so delete the explicit
t.Setenv lines and keep only the working directory setup and the call to
setupTerraformYamlFunctionSandbox in the test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8bf1ff9a-f87e-4b29-8048-9eed11261fa0

📥 Commits

Reviewing files that changed from the base of the PR and between d775e5a and 47e2f64.

📒 Files selected for processing (5)
  • internal/exec/terraform_yaml_test_helpers_test.go
  • internal/exec/yaml_func_terraform_output_test.go
  • internal/exec/yaml_func_terraform_state_test.go
  • internal/exec/yaml_func_utils_test.go
  • tests/cli_double_hyphen_test.go
✅ Files skipped from review due to trivial changes (1)
  • internal/exec/terraform_yaml_test_helpers_test.go

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 10, 2026
@shirkevich

Copy link
Copy Markdown
Collaborator Author

Erik Osterman (Cloud Posse) (@osterman) Andriy Knysh (@aknysh) fixed nitpicks and codecov

@aknysh Andriy Knysh (aknysh) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aknysh
Andriy Knysh (aknysh) merged commit aa223e0 into main Jun 10, 2026
59 of 60 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the codex/dag-github-concurrent-output branch June 10, 2026 14:33
@atmos-pro

atmos-pro Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label Jun 10, 2026
@github-actions

Copy link
Copy Markdown

These changes were released in v1.221.0.

Igor Rodionov (goruha) added a commit that referenced this pull request Jun 11, 2026
…atmos into 1198-pact-consumer-contracts

* '1198-pact-consumer-contracts' of github.com:cloudposse/atmos:
  fix(ansible): forward `-- <args>` passthrough to ansible-playbook (#2594)
  fix(ci): use localhost endpoints in LocalStack demo to avoid DNS hangs (#2598)
  DAG follow-up: aggregate CI output for concurrent Terraform runs (#2577)
  fix(list): prevent nil pointer panic when spinner exits early (#2591)
  feat: describe affected evaluates all provisioned component sections (#2573)

This branch was successfully deployed

1 active deployment
preview — c461f1f4 Deployed Jun 10, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

no-release Do not create a new release (wait for additional code changes) size/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants