Skip to content

fix: terraform plan-diff respects metadata.component and workdir - #2056

Merged
Andriy Knysh (aknysh) merged 5 commits into
mainfrom
aknysh/fix-plan-diff
Feb 6, 2026
Merged

Andriy Knysh (aknysh) merged 5 commits into
mainfrom
aknysh/fix-plan-diff

Conversation

@aknysh

@aknysh Andriy Knysh (aknysh) commented Feb 5, 2026 •

Copy link
Copy Markdown
Member

what

  • Fixed atmos terraform plan-diff to properly resolve metadata.component when looking for planfiles
  • The command now calls ProcessStacks() to resolve FinalComponent from metadata.component before constructing the component path
  • Added support for workdir and source vendoring: when workdir is enabled, plan-diff now correctly looks for planfiles in the workdir path (e.g., .workdir/terraform/<stack>-<component>/)
  • Added comprehensive test coverage for plan-diff comparison and formatting functions
  • Added test fixtures and documentation

why

  • When a component instance name differs from the actual component (e.g., foobar-atmos-pro with metadata.component: foobar), plan-diff was looking in the wrong directory
  • Expected: Look for planfile in components/terraform/foobar/
  • Actual (bug): Was looking in components/terraform/foobar-atmos-pro/ or components/terraform/
  • When source vendoring + workdir is enabled, planfiles are stored in .workdir/ path, not the base component path
  • This caused failures in CI workflows using github-action-atmos-terraform-apply when comparing planfiles for components with metadata.component set or workdir enabled

changes

File Change
internal/exec/terraform_plan_diff.go Added ProcessStacks call + workdir path support
internal/exec/terraform_plan_diff_comparison.go Use shared u.SliceContainsString utility
internal/exec/terraform_plan_diff_test.go Added workdir and source vendoring tests
docs/fixes/plan-diff-metadata-component.md Documentation of fix

references

  • Documentation: docs/fixes/plan-diff-metadata-component.md

Summary by CodeRabbit

  • Bug Fixes

    • Plan-diff now properly respects metadata.component configuration for correct component path resolution.
  • Documentation

    • Added comprehensive documentation detailing the plan-diff metadata.component fix, including root cause analysis and testing guidance.
  • Tests

    • Expanded test coverage for plan-diff scenarios, including metadata component resolution, error handling, and plan file operations.

Previously, `atmos terraform plan-diff` would look for planfiles in the wrong
directory when the component instance name differed from the actual component
(e.g., "foobar-atmos-pro" with metadata.component: "foobar").

The fix adds a ProcessStacks() call to resolve FinalComponent from
metadata.component before constructing the component path.

Changes:
- Add ProcessStacks() call in TerraformPlanDiff to resolve component metadata
- Update tests to be proper unit tests for helper functions
- Add comprehensive test coverage for comparison and formatting functions
- Add test fixtures for plan-diff metadata.component testing
- Add documentation in docs/fixes/plan-diff-metadata-component.md
- Add vendor-simple-excludes/components to .gitignore

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@aknysh
Andriy Knysh (aknysh) requested a review from a team as a code owner February 5, 2026 23:38
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Feb 5, 2026
@aknysh
Andriy Knysh (aknysh) requested a review from a team as a code owner February 5, 2026 23:38
@github-actions github-actions Bot added the size/xl Extra large size PR label Feb 5, 2026
@aknysh Andriy Knysh (aknysh) self-assigned this Feb 5, 2026
@mergify

mergify Bot commented Feb 5, 2026

Copy link
Copy Markdown
Contributor

Warning

This PR exceeds the recommended limit of 1,000 lines.

Large PRs are difficult to review and may be rejected due to their size.

Please verify that this PR does not address multiple issues.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@github-actions

github-actions Bot commented Feb 5, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@coderabbitai

coderabbitai Bot commented Feb 5, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Invoke ProcessStacks before Terraform plan-diff to resolve component metadata (metadata.component and component_folder_prefix); subsequent flag parsing, planfile path construction, preparation, and comparison use the processed info. Adds fixtures, docs, and expanded unit tests for the new flow and helpers.

Changes

Cohort / File(s) Summary
Core Plan-Diff Logic
internal/exec/terraform_plan_diff.go
Call ProcessStacks() to obtain processedInfo; parse flags from processedInfo.AdditionalArgsAndFlags; build componentPath from processedInfo.ComponentFolderPrefix + processedInfo.FinalComponent; pass processedInfo into planfile preparation and comparison; propagate errors from ProcessStacks.
Plan-Diff Comparison Helpers
internal/exec/terraform_plan_diff_comparison.go
Replace local contains usage with u.SliceContainsString; remove unused contains helper; add utils import alias u.
Unit Tests & Test Helpers
internal/exec/terraform_plan_diff_main_test.go, internal/exec/terraform_plan_diff_test.go
Remove OsExit end-to-end scaffolding; add granular tests covering ProcessStacks error paths, metadata.component resolution, planfile handling (copy/cleanup/validation), JSON extraction, diff formatting, and many helper functions; update assertions to use ErrorIs where appropriate.
Fixtures & Scenario Config
tests/fixtures/scenarios/atmos-terraform-plan-diff/...
Add new fixture atmos.yaml, Terraform base component (components/terraform/base-component/main.tf), and stack stacks/test-stack.yaml modeling base/derived components to exercise metadata.component resolution.
Docs & VCS Ignore
docs/fixes/plan-diff-metadata-component.md, .gitignore
Add documentation describing the plan-diff metadata.component fix and test scaffold; add .gitignore rule for tests/fixtures/scenarios/vendor-simple-excludes/components/**.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant TF as TerraformPlanDiff
    participant PS as ProcessStacks
    participant PlanOps as PlanOperations

    User->>TF: invoke plan-diff
    TF->>PS: ProcessStacks(stack, component args)
    PS-->>TF: processedInfo (FinalComponent, ComponentFolderPrefix, AdditionalArgsAndFlags)
    TF->>PlanOps: parse flags from processedInfo.AdditionalArgsAndFlags
    TF->>PlanOps: prepareNewPlanFile(&processedInfo)
    TF->>PlanOps: comparePlansAndGenerateDiff(&processedInfo)
    PlanOps-->>TF: diff output / errors
    TF-->>User: present diff or error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix—plan-diff now respects metadata.component and workdir—which directly aligns with the core changes in terraform_plan_diff.go and the problem being solved.
Docstring Coverage ✅ Passed Docstring coverage is 86.49% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch aknysh/fix-plan-diff

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Feb 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.81818% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.06%. Comparing base (2a065e8) to head (0093b67).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/exec/terraform_plan_diff.go 77.77% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2056      +/-   ##
==========================================
+ Coverage   76.01%   76.06%   +0.04%     
==========================================
  Files         797      797              
  Lines       74558    74558              
==========================================
+ Hits        56674    56710      +36     
+ Misses      14338    14304      -34     
+ Partials     3546     3544       -2     
Flag Coverage Δ
unittests 76.06% <81.81%> (+0.04%) ⬆️

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

Files with missing lines Coverage Δ
internal/exec/terraform_plan_diff_comparison.go 90.94% <100.00%> (+14.49%) ⬆️
internal/exec/terraform_plan_diff.go 76.62% <77.77%> (-2.58%) ⬇️

... and 6 files with indirect coverage changes

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

@coderabbitai

coderabbitai Bot commented Feb 6, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR fixes terraform plan-diff to respect metadata.component by resolving component metadata before path resolution. TerraformPlanDiff now calls ProcessStacks to obtain FinalComponent and ComponentFolderPrefix, enabling correct plan file location. Tests are refactored from integration-style to unit-focused approaches with comprehensive test fixtures added.

Changes

Cohort / File(s) Summary
Core Implementation
internal/exec/terraform_plan_diff.go
Updated to call ProcessStacks for metadata resolution before path computation; all downstream operations now use resolved FinalComponent and ComponentFolderPrefix instead of original info.
Test Refactoring
internal/exec/terraform_plan_diff_test.go, internal/exec/terraform_plan_diff_main_test.go
Refactored from integration-style tests to unit-focused tests; removed dependencies on OsExit mocking and schema types; expanded coverage for flag parsing, file validation, component resolution, and diffing logic.
Test Fixtures
tests/fixtures/scenarios/atmos-terraform-plan-diff/atmos.yaml, tests/fixtures/scenarios/atmos-terraform-plan-diff/components/terraform/base-component/main.tf, tests/fixtures/scenarios/atmos-terraform-plan-diff/stacks/test-stack.yaml
New test scenario configuration with Terraform components demonstrating metadata.component resolution across base and derived components.
Documentation
docs/fixes/plan-diff-metadata-component.md
Introduces fix documentation detailing root cause, implementation approach, and testing procedures for metadata.component resolution in plan-diff.
Config
.gitignore
Added ignore pattern for vendor-simple-excludes test fixture.

Sequence Diagram

sequenceDiagram
    participant Client as TerraformPlanDiff
    participant PS as ProcessStacks
    participant Parser as parsePlanDiffFlags
    participant FileOps as Plan File Operations
    participant Diff as comparePlansAndGenerateDiff
    
    Client->>PS: Call with original info
    PS->>PS: Resolve FinalComponent & ComponentFolderPrefix from metadata.component
    PS-->>Client: Return processedInfo
    
    Client->>Parser: Parse flags with processedInfo
    Parser-->>Client: Return parsed arguments
    
    Client->>FileOps: Prepare plan file with resolved component path
    FileOps->>FileOps: Locate/copy plan files under components/terraform/<component>/
    FileOps-->>Client: Plan files ready
    
    Client->>Diff: Compare plans with processedInfo
    Diff->>Diff: Generate resource/attribute/output diffs
    Diff-->>Client: Return diff results
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.13% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main fix: terraform plan-diff now respects metadata.component, which aligns with the core objective of the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch aknysh/fix-plan-diff

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@aknysh

Copy link
Copy Markdown
Member Author

CodeRabbit (@coderabbitai) full review please

@coderabbitai

coderabbitai Bot commented Feb 6, 2026

Copy link
Copy Markdown
Contributor

@aknysh: I'll perform a full review of all the changes in this PR.


🧠 Learnings used
Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: docs/prd/tool-dependencies-integration.md:58-64
Timestamp: 2025-12-13T06:07:37.766Z
Learning: cloudposse/atmos: For PRD docs (docs/prd/*.md), markdownlint issues like MD040/MD010/MD034 can be handled in a separate documentation cleanup commit and should not block the current PR.

Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Feb 6, 2026

Copy link
Copy Markdown
Contributor

@aknysh: I'll conduct a full review of all the changes in this PR.


🧠 Learnings used
Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: docs/prd/tool-dependencies-integration.md:58-64
Timestamp: 2025-12-13T06:07:37.766Z
Learning: cloudposse/atmos: For PRD docs (docs/prd/*.md), markdownlint issues like MD040/MD010/MD034 can be handled in a separate documentation cleanup commit and should not block the current PR.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 944
File: go.mod:206-206
Timestamp: 2025-01-17T00:18:57.769Z
Learning: For indirect dependencies with license compliance issues in the cloudposse/atmos repository, the team prefers to handle them in follow-up PRs rather than blocking the current changes, as these issues often require deeper investigation of the dependency tree.

Learnt from: Listener430
Repo: cloudposse/atmos PR: 934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 1327
File: internal/exec/describe_affected_utils_2.go:248-248
Timestamp: 2025-06-23T18:50:33.614Z
Learning: When aknysh mentions that a suggestion is not related to the current PR and needs separate tests to be reviewed in a separate PR, this indicates their preference for maintaining focused PR scope and proper test coverage for each change.

Learnt from: osterman
Repo: cloudposse/atmos PR: 808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: errors/errors.go:184-203
Timestamp: 2025-12-13T06:10:13.688Z
Learning: cloudposse/atmos: For toolchain work, duplicate/unused error sentinels in errors/errors.go should be cleaned up in a separate refactor PR and not block feature PRs; canonical toolchain sentinels live under toolchain/registry with re-exports in toolchain/errors.go.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 768
File: internal/exec/vendor_model_component.go:3-20
Timestamp: 2024-11-18T13:59:10.824Z
Learning: When replacing significant dependencies like `go-getter` that require extensive changes, prefer to address them in separate PRs.

Learnt from: samtholiya
Repo: cloudposse/atmos PR: 1466
File: toolchain/http_client_test.go:3-10
Timestamp: 2025-09-10T21:17:55.273Z
Learning: In the cloudposse/atmos repository, imports should never be changed as per samtholiya's coding guidelines.
✅ Actions performed

Full review triggered.

@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: 1

Caution

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

⚠️ Outside diff range comments (1)
internal/exec/terraform_plan_diff_main_test.go (1)

46-52: ⚠️ Potential issue | 🟡 Minor

This test documents a real flag parsing quirk.

When --orig is followed by another flag (--new=new-plan.out), the parser treats that flag string as the value for --orig. The space-separated branch in parsePlanDiffFlags (line 95-96 in terraform_plan_diff.go) doesn't check whether the next argument starts with --.

Not a blocker — the bogus path would fail at validateOriginalPlanFile. But if you ever want to tighten this up, checking for a -- prefix on the lookahead would catch the misuse earlier with a clearer error.

🤖 Fix all issues with AI agents
In `@internal/exec/terraform_plan_diff.go`:
- Around line 60-61: The comment above the componentPath construction is missing
a trailing period; update the comment that references component path and
ProcessStacks to end with a period. Locate the comment near the componentPath
variable creation (where filepath.Join is called with
atmosConfig.TerraformDirAbsolutePath, processedInfo.ComponentFolderPrefix,
processedInfo.FinalComponent) and append a period to the end of that comment so
it conforms to the godot linter rule.
🧹 Nitpick comments (3)
internal/exec/terraform_plan_diff_main_test.go (1)

228-253: Duplicate coverage with TestParsePlanDiffFlags above.

TestTerraformPlanDiff_FlagParsing (lines 228-253) tests the same scenarios already covered by the table-driven TestParsePlanDiffFlags (lines 12-87): missing orig, only orig, both with =, both with space. Consider removing this function to avoid maintaining the same assertions in two places.

internal/exec/terraform_plan_diff_test.go (2)

421-432: Use errors.Is() instead of direct equality for sentinel errors.

Lines 424 and 431 compare errors with assert.Equal. The coding guidelines require errors.Is() for error checking, which handles wrapped errors correctly.

Proposed fix
 	t.Run("empty_output_returns_ErrNoJSONOutput", func(t *testing.T) {
 		_, err := extractJSONFromOutput("")
 		assert.Error(t, err)
-		assert.Equal(t, ErrNoJSONOutput, err)
+		assert.ErrorIs(t, err, ErrNoJSONOutput)
 	})
 
 	t.Run("no_json_content_returns_ErrNoJSONOutput", func(t *testing.T) {
 		_, err := extractJSONFromOutput("some random text without json")
 		assert.Error(t, err)
-		assert.Equal(t, ErrNoJSONOutput, err)
+		assert.ErrorIs(t, err, ErrNoJSONOutput)
 	})

As per coding guidelines: "Use errors.Is() for error checking."


360-373: parsePlanDiffFlags is now tested in three places.

This function, TestPlanDiffCommandFlags, plus TestParsePlanDiffFlags and TestTerraformPlanDiff_FlagParsing in terraform_plan_diff_main_test.go all cover the same parsePlanDiffFlags logic. Consider consolidating into the table-driven test in the main test file.

Comment thread internal/exec/terraform_plan_diff.go Resolved
Andriy Knysh (aknysh) and others added 2 commits February 5, 2026 20:18
- Remove duplicate TestTerraformPlanDiff_FlagParsing function
- Remove duplicate TestPlanDiffCommandFlags function
- Use assert.ErrorIs() instead of assert.Equal() for sentinel errors

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@osterman

Copy link
Copy Markdown
Member

Does it work with source vendoring and workdir ?

@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: 1

🤖 Fix all issues with AI agents
In `@internal/exec/terraform_plan_diff.go`:
- Around line 38-45: The ProcessStacks call returns an error that is currently
returned raw; change the error handling in the processedInfo assignment so the
returned error is wrapped with contextual information (e.g., using
fmt.Errorf("process stacks for component metadata: %w", err) or your project's
error-wrap helper) to match the rest of the function's style; reference the
ProcessStacks call and variables processedInfo, atmosConfig and info when adding
the context so callers can trace which config/step failed.
🧹 Nitpick comments (2)
internal/exec/terraform_plan_diff_test.go (2)

842-854: Trim the redundant doc comment block.

The function doc says the same thing three different ways (lines 842-844, then 846-847, then 849-854). One concise paragraph is enough.

Suggested trimmed comment
-// TestTerraformPlanDiffMetadataComponentResolution tests that plan-diff respects metadata.component
-// when resolving the component path. This reproduces the bug where plan-diff looks in the wrong
-// directory when the component instance name differs from the actual component (metadata.component).
-//
-// TestTerraformPlanDiffMetadataComponentResolution tests that the component path
-// is correctly resolved when using metadata.component.
-//
-// Bug fixed: Component instance "foobar-atmos-pro" with metadata.component: "foobar"
-// Expected: Look for planfile in components/terraform/foobar/
-// Actual (bug): Was looking for planfile in components/terraform/foobar-atmos-pro/ (wrong!)
-//
-// The fix: TerraformPlanDiff now calls ProcessStacks() to resolve FinalComponent
-// from metadata.component before constructing the component path.
+// TestTerraformPlanDiffMetadataComponentResolution verifies that plan-diff uses FinalComponent
+// (resolved from metadata.component) rather than ComponentFromArg when constructing
+// the component path. This prevents searching the wrong directory (e.g.,
+// components/terraform/foobar-atmos-pro/ instead of components/terraform/foobar/).

957-967: Move the contains logic to a shared utility package to avoid duplication.

Both internal/exec/terraform_plan_diff_comparison.go:514 and cmd/cmd_utils.go:1454 implement identical slice-contains logic. Since internal/exec shouldn't depend on cmd (architectural layering), consolidate this into pkg/utils or a similar shared location and have both call it.

Comment thread internal/exec/terraform_plan_diff.go Resolved
@aknysh Andriy Knysh (aknysh) changed the title fix: terraform plan-diff now respects metadata.component fix: terraform plan-diff respects metadata.component and workdir Feb 6, 2026
- Check WorkdirPathKey in ComponentSection for workdir path resolution
- Replace local contains() with shared u.SliceContainsString utility
- Add tests for workdir and source vendoring scenarios
- Update documentation with workdir fix details
- Address code review feedback (trimmed comments, error wrapping)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@aknysh

Copy link
Copy Markdown
Member Author

Does it work with source vendoring and workdir ?

yes. Also added tests for that

@aknysh
Andriy Knysh (aknysh) merged commit 3ca5359 into main Feb 6, 2026
57 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the aknysh/fix-plan-diff branch February 6, 2026 15:07
@github-actions

github-actions Bot commented Feb 7, 2026

Copy link
Copy Markdown

These changes were released in v1.206.0-rc.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants