Skip to content

fix(hooks): persist interactive stack selection and auth context for PostRunE hooks - #2520

Merged
Andriy Knysh (aknysh) merged 7 commits into
mainfrom
aknysh/auth-fixes-7
May 26, 2026
Merged

Andriy Knysh (aknysh) merged 7 commits into
mainfrom
aknysh/auth-fixes-7

Conversation

@aknysh

@aknysh Andriy Knysh (aknysh) commented May 25, 2026 •

Copy link
Copy Markdown
Member

what

  • Store hooks now fire when the stack is selected via the interactive prompt (not just when passed with -s).
  • Store hooks can now read terraform outputs from S3 backends that require role assumption via assume_role.
  • Auth context and auth manager from the main terraform execution are persisted and injected into PostRunE hook info so the hook's terraform output subprocess has the correct credentials.

why

Two bugs in the store hooks execution path caused hooks to silently fail in common scenarios:

  1. Interactive stack selection lost for hooks (Store hooks don't fire when stack is selected via interactive prompt #2432): When a user runs atmos terraform apply component and selects the stack from the interactive prompt, the selected stack value was stored in the local info.Stack but never persisted to the Cobra flag set. PostRunE hooks re-parse args via ProcessCommandLineArgs, which reads from cmd.Flags().GetString("stack") — still empty. The hook silently skipped because it saw no stack. Fix: after the interactive prompt fills info.Stack, also set the Cobra flag via f.Value.Set(stack) so downstream consumers can read it.

  2. Missing backend credentials for hook's terraform output (Store hook doesn't assume backend role when reading terraform outputs #2433): The store hook's terraform output subprocess needs credentials to access the S3 state backend, which often requires a chained role assumption (e.g., dev-role → tfstate-access-role). The main ExecuteTerraform sets up the full credential chain via setupTerraformAuth and prepareComponentExecution, but it takes info by value — the populated AuthContext and AuthManager don't flow back to the caller. The PostRunE hook creates a fresh info with nil auth fields, so the output subprocess fails with "No valid credential sources found". Fix: persist the auth context via SetLastAuthContext after prepareComponentExecution, and inject it into the hook's fresh info in runHooksWithOutput.

references

Summary by CodeRabbit

  • Bug Fixes

    • Post-run hooks now preserve Terraform auth so store hooks and hooks triggered after interactive stack selection work when role-assumption is required.
  • Chores

    • Bumped Go to 1.26.3, upgraded many dependencies, updated NOTICE license listings, and advanced app version to 1.220.0.
  • Tests

    • Added tests for interactive component/stack prompts and auth-context persistence.
  • Documentation

    • Added two docs describing the store-hook role-assumption issue and interactive-prompt hook behavior.

Review Change Stack

Andriy Knysh (aknysh) and others added 3 commits May 25, 2026 12:04
…PostRunE hooks

Two fixes for store hooks:

1. Store hooks don't fire when stack is selected via interactive prompt
   (fixes #2432): the interactively-selected stack was stored in the
   local info struct but never persisted to the Cobra flag set. PostRunE
   hooks re-parse args via ProcessCommandLineArgs which reads from
   cmd.Flags().GetString("stack") — empty. Fix: set the Cobra flag
   after the prompt fills info.Stack.

2. Store hook can't read terraform outputs from backends requiring role
   assumption (fixes #2433): the hook creates a fresh info with nil
   AuthContext and AuthManager. The main ExecuteTerraform sets these up
   but passes info by value, so they don't flow back. Fix: persist the
   auth context via SetLastAuthContext after prepareComponentExecution,
   and inject it into the hook's fresh info in runHooksWithOutput.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@aknysh
Andriy Knysh (aknysh) requested a review from a team as a code owner May 25, 2026 17:01
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label May 25, 2026
@atmos-pro

atmos-pro Bot commented May 25, 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/m Medium size PR label May 25, 2026
@aknysh Andriy Knysh (aknysh) self-assigned this May 25, 2026
@github-actions

github-actions Bot commented May 25, 2026 •

Copy link
Copy Markdown

🚀 Go Version Change Detected

This PR changes the Go version:

  • Base branch (main): 1.26.2
  • This PR: 1.26.3
  • Change: ⬆️ Upgrade

Tip

Upgrade Checklist


This is an automated comment from the Go Version Check action.

@github-actions

github-actions Bot commented May 25, 2026 •

Copy link
Copy Markdown

Dependency Review

The following issues were found:
  • ✅ 0 vulnerable package(s)
  • ✅ 0 package(s) with incompatible licenses
  • ✅ 0 package(s) with invalid SPDX license definitions
  • ⚠️ 16 package(s) with unknown licenses.
See the Details below.

License Issues

go.mod

PackageVersionLicenseIssue Type
github.com/aws/aws-sdk-go-v2/config1.32.18NullUnknown License
github.com/aws/aws-sdk-go-v2/credentials1.19.17NullUnknown License
github.com/aws/aws-sdk-go-v2/service/bedrockruntime1.52.0NullUnknown License
github.com/aws/aws-sdk-go-v2/service/eks1.84.0NullUnknown License
github.com/aws/aws-sdk-go-v2/service/ssooidc1.36.0NullUnknown License
github.com/docker/cli29.5.2+incompatibleNullUnknown License
github.com/go-git/go-git/v55.19.1NullUnknown License
github.com/google/go-containerregistry0.21.6NullUnknown License
github.com/googleapis/enterprise-certificate-proxy0.3.16NullUnknown License
github.com/hashicorp/consul/api1.34.3NullUnknown License
github.com/modelcontextprotocol/go-sdk1.6.1NullUnknown License
github.com/posthog/posthog-go1.12.6NullUnknown License
golang.org/x/crypto0.52.0NullUnknown License
golang.org/x/net0.55.0NullUnknown License
golang.org/x/sys0.45.0NullUnknown License
k8s.io/kube-openapi0.0.0-20260520065146-aa012df4f4afNullUnknown License
Allowed Licenses: MIT, MIT-0, Apache-2.0, BSD-2-Clause, BSD-2-Clause-Views, BSD-3-Clause, ISC, MPL-2.0, 0BSD, Unlicense, CC0-1.0, CC-BY-3.0, CC-BY-4.0, CC-BY-SA-3.0, Python-2.0, OFL-1.1, LicenseRef-scancode-generic-cla, LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-unicode, LicenseRef-scancode-google-patent-license-golang
Excluded from license check: pkg:golang/modernc.org/libc

Scanned Files

  • go.mod

@mergify

mergify Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@mergify mergify Bot added the needs-cloudposse Needs Cloud Posse assistance label May 25, 2026
@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

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: d94f458a-f37d-42fa-aee5-9dc242423f1d

📥 Commits

Reviewing files that changed from the base of the PR and between 1b6bfe5 and 1b9f3bd.

📒 Files selected for processing (4)
  • cmd/terraform/shared/prompt.go
  • cmd/terraform/shared/prompt_test.go
  • cmd/terraform/utils.go
  • cmd/terraform/utils_hooks_test.go
💤 Files with no reviewable changes (1)
  • cmd/terraform/utils.go

📝 Walkthrough

Walkthrough

Persists Terraform auth context and writes interactive stack selections back to the Cobra --stack flag so post-run hooks run with the same credentials and stack context; adds tests and docs; performs dependency, go.mod, and NOTICE/license updates plus minor version bumps in examples/tests.

Changes

Store Hooks Auth Context and Stack Persistence

Layer / File(s) Summary
Auth context persistence storage module
internal/exec/terraform_auth_context.go, internal/exec/terraform_auth_context_test.go
New package-level mutex-protected storage caches Terraform auth context and manager across calls. Exported SetLastAuthContext, GetLastAuthContext, and ClearLastAuthContext functions added; tests cover round-trip, nil, clear, and overwrite behavior.
Auth context capture and injection
internal/exec/terraform.go, cmd/terraform/utils.go
ExecuteTerraform calls SetLastAuthContext(...) after preparing execution; runHooksWithOutput copies the cached auth context/manager into the parsed hook info before validation/initialization so hooks can assume backend roles.
Stack persistence through interactive selection
cmd/terraform/shared/prompt.go, cmd/terraform/utils.go, cmd/terraform/shared/prompt_test.go, cmd/terraform/utils_hooks_test.go
PromptForStack now uses an injected prompt helper and persists non-empty selections into the Cobra --stack flag; interactive prompt helpers are exposed as package-level variables for testability. Tests added/updated to assert flag persistence and interactive prompting behavior.
Test coverage for auth context and stack selection
cmd/terraform/utils_hooks_test.go
New tests verify persisting selected stack to the Cobra flag, injecting preserved auth context into hook execution, prompt error propagation, component+stack prompt persistence, and no-op behavior when inputs already provided or multi-component mode enabled.
Documentation of auth context and stack propagation issues
docs/fixes/2026-05-25-store-hook-missing-backend-role-assumption.md, docs/fixes/2026-05-25-store-hooks-interactive-prompt-not-firing.md
Adds two fix docs describing reproducers, root causes, workarounds, and planned tests/fixes for the store-hook backend role-assumption and interactive-prompt failures.

Dependency and Version Updates

Layer / File(s) Summary
Dependency license notice updates
NOTICE
Updated license URLs/references for many dependencies and removed bundled entries github.com/containerd/stargz-snapshotter/estargz and github.com/vbatts/tar-split.
Go module and dependency upgrades
go.mod
Bumped go directive to 1.26.3; updated direct and indirect module versions (AWS SDK v2 modules, cloud.google.com, googleapis/genAI/genproto, containerd/docker/go-git/k8s golang.org/x/*, modernc.org/libc, etc.); removed github.com/vbatts/tar-split.
Atmos version reference updates in examples and tests
examples/quick-start-advanced/Dockerfile, pkg/ai/analyze/analyze_test.go, pkg/devcontainer/lifecycle_rebuild_test.go
Bumped Atmos version references from 1.219.0 to 1.220.0 in example Dockerfile and test expectations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • cloudposse/atmos#2382: Touches Terraform hook wrapper path (runHooksWithOutput) and related hook execution plumbing.

Suggested reviewers

  • osterman
  • goruha
  • milldr
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 65.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 changes: persisting interactive stack selection and auth context for PostRunE hooks, which directly addresses the PR's core fixes.
Linked Issues check ✅ Passed The PR directly addresses both linked issues: #2432 (interactive stack selection persisted to Cobra flag so hooks fire) and #2433 (auth context propagated to hook subprocess for backend assume_role support).
Out of Scope Changes check ✅ Passed All changes are in scope. Version bumps (Dockerfile, go.mod, test versions) and documentation posts are supportive changes; no unrelated refactoring or feature creep detected.

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

✨ 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 aknysh/auth-fixes-7

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.

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

🤖 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_hooks_test.go`:
- Around line 556-577: The test currently only exercises
SetLastAuthContext/GetLastAuthContext helpers but never calls
runHooksWithOutput; update TestRunHooksWithOutput_InjectsLastAuthContext to
register a simple mock hook (or use an existing hook runner) that reads the auth
context, call runHooksWithOutput (ensuring any required inputs like outputs or
hook config are provided), and assert the hook observed the injected auth
context (compare AWS.Profile or other fields) and that runHooksWithOutput
returns/propagates expected results; keep the existing
SetLastAuthContext/GetLastAuthContext usage to seed the context and use the same
identifying symbols (TestRunHooksWithOutput_InjectsLastAuthContext,
runHooksWithOutput, SetLastAuthContext, GetLastAuthContext) to locate and modify
the test.
- Around line 529-554: The test currently bypasses
handleInteractiveComponentStackSelection by directly setting info.Stack and the
Cobra flag; instead, invoke handleInteractiveComponentStackSelection from
TestInteractiveStackSelection_PersistsToCobraFlag using newHookTestCmd() and a
prompt stub that simulates the interactive selection (returning
"tenant1-ue1-dev") so the real persistence path runs; remove the manual
f.Value.Set(...) call and assert afterwards via cmd.Flags().GetString("stack")
that the flag was mutated as a side effect; reference the
schema.ConfigAndStacksInfo instance and ensure the stubbed prompt integrates
with whatever prompt/reader dependency handleInteractiveComponentStackSelection
uses (replace or inject the prompt function/reader used by that function).

In `@cmd/terraform/utils.go`:
- Around line 703-705: Check the result of f.Value.Set(stack) instead of
ignoring it: after obtaining f via cmd.Flag("stack") and calling
f.Value.Set(stack), if it returns an error return a wrapped static error (from
errors/errors.go) that includes the original cause (using the project's
error-wrapping helper) so PostRunE re-parse won't proceed with an empty stack;
ensure you reference cmd.Flag("stack"), f.Value.Set(stack) and return the
wrapped static error rather than discarding the error.

In `@docs/fixes/2026-05-25-store-hook-missing-backend-role-assumption.md`:
- Around line 53-56: Add the missing language tag to the fenced code block
containing the Terraform error output by changing the triple-backtick fence that
wraps the two lines starting with "✗ Fetching my_output output from my-component
in my-stack" and "Error: failed to retrieve terraform outputs: No valid
credential sources found" to include "text" (i.e., ```text) so the block becomes
fenced as a text code block and satisfies markdownlint MD040.
- Around line 109-121: Replace the "TBD" with a concrete resolution: document
that the hook now inherits the parent `terraform apply` environment (so the
parent process must pass its full environment into the hook subprocess) and that
the hook invokes `terraform output` with SkipInit=true to avoid re-initializing
the backend; describe how to thread credentials by either passing the resolved
env vars into the subprocess or calling the auth manager to resolve and inject
the same credential envs (e.g., AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
AWS_SESSION_TOKEN or role-assumed creds) before running `terraform output`, and
include a short verification step to check the backend role
assumption/credentials are present when the hook runs.

In `@docs/fixes/2026-05-25-store-hooks-interactive-prompt-not-firing.md`:
- Around line 74-82: Replace the "TBD" in the Fix section with a concise summary
of the actual shipped fix: explain that the interactive stack selection is now
persisted (stack persistence for interactive selection) and that hook execution
now reads the stack from the resolved execution context used by the CLI rather
than the original CLI args, plus note the CI-hooks gating change if applicable
(CI hooks check no longer blocks non-CI hook events or was adjusted to respect
the resolved context). Mention any key components touched (the interactive stack
persistence logic, the hook runner, and the execution context resolution) so
readers can locate the change.

In `@NOTICE`:
- Line 54: The NOTICE file has been manually edited and diverges from the
generator output; revert those manual dependency URL/version edits by running
the generator and committing its output: execute ./scripts/generate-notice.sh to
regenerate NOTICE, review the generated changes (reverting any hand-edits in
NOTICE), and commit the regenerated NOTICE so CI and license review reflect the
canonical generator output.
🪄 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: a6dd4122-39a1-42f3-84d4-f105794c25e5

📥 Commits

Reviewing files that changed from the base of the PR and between 3ae76cd and 586a3e3.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (12)
  • NOTICE
  • cmd/terraform/utils.go
  • cmd/terraform/utils_hooks_test.go
  • docs/fixes/2026-05-25-store-hook-missing-backend-role-assumption.md
  • docs/fixes/2026-05-25-store-hooks-interactive-prompt-not-firing.md
  • examples/quick-start-advanced/Dockerfile
  • go.mod
  • internal/exec/terraform.go
  • internal/exec/terraform_auth_context.go
  • internal/exec/terraform_auth_context_test.go
  • pkg/ai/analyze/analyze_test.go
  • pkg/devcontainer/lifecycle_rebuild_test.go

Comment thread cmd/terraform/utils_hooks_test.go Resolved
Comment thread cmd/terraform/utils_hooks_test.go Resolved
Comment thread cmd/terraform/utils.go Resolved
Comment thread NOTICE Resolved
@codecov

codecov Bot commented May 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.10345% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.57%. Comparing base (733edd0) to head (1b9f3bd).

Files with missing lines Patch % Lines
cmd/terraform/shared/prompt.go 75.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2520      +/-   ##
==========================================
+ Coverage   78.53%   78.57%   +0.03%     
==========================================
  Files        1143     1144       +1     
  Lines      109855   109879      +24     
==========================================
+ Hits        86275    86335      +60     
+ Misses      18791    18756      -35     
+ Partials     4789     4788       -1     
Flag Coverage Δ
unittests 78.57% <93.10%> (+0.03%) ⬆️

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

Files with missing lines Coverage Δ
cmd/terraform/utils.go 58.77% <100.00%> (+1.21%) ⬆️
internal/exec/terraform.go 80.00% <100.00%> (+0.25%) ⬆️
internal/exec/terraform_auth_context.go 100.00% <100.00%> (ø)
cmd/terraform/shared/prompt.go 96.92% <75.00%> (-0.95%) ⬇️

... 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.

- Handle f.Value.Set error instead of dropping it (wraps with ErrSetFlag).
- Replace manual test with real handleInteractiveComponentStackSelection
  call using stubbed prompts (promptForStack/promptForComponent are now
  package-level vars for test injection).
- Call real runHooksWithOutput from demo-stacks fixture to exercise the
  auth context injection path end-to-end.
- Add prompt error propagation test and both-prompts test covering the
  component+stack interactive selection path.
- Clean up fix docs: replace TBD sections with actual implementation
  details, add PR references, add language tags to fenced blocks.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes May 25, 2026
Move the Cobra flag persistence from handleInteractiveComponentStackSelection
into shared.PromptForStack so any caller of the prompt gets the flag
write-back for free. This addresses the review feedback that the persistence
should live in the shared interactive handler, not at each call site.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit 3bc31f2 into main May 26, 2026
60 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the aknysh/auth-fixes-7 branch May 26, 2026 21:25
@atmos-pro

atmos-pro Bot commented May 26, 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 May 26, 2026
@github-actions

Copy link
Copy Markdown

These changes were released in v1.220.0-rc.4.

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/m Medium size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Store hook doesn't assume backend role when reading terraform outputs Store hooks don't fire when stack is selected via interactive prompt

2 participants