Repository navigation
fix(hooks): persist interactive stack selection and auth context for PostRunE hooks - #2520
Conversation
…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]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
🚀 Go Version Change Detected This PR changes the Go version:
Tip Upgrade Checklist
This is an automated comment from the Go Version Check action. |
Dependency ReviewThe following issues were found:
License Issuesgo.mod
Scanned Files
|
|
Important Cloud Posse Engineering Team Review RequiredThis 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 |
|
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 (4)
💤 Files with no reviewable changes (1)
📝 WalkthroughWalkthroughPersists Terraform auth context and writes interactive stack selections back to the Cobra ChangesStore Hooks Auth Context and Stack Persistence
Dependency and Version Updates
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
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 docstrings
🧪 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: 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
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (12)
NOTICEcmd/terraform/utils.gocmd/terraform/utils_hooks_test.godocs/fixes/2026-05-25-store-hook-missing-backend-role-assumption.mddocs/fixes/2026-05-25-store-hooks-interactive-prompt-not-firing.mdexamples/quick-start-advanced/Dockerfilego.modinternal/exec/terraform.gointernal/exec/terraform_auth_context.gointernal/exec/terraform_auth_context_test.gopkg/ai/analyze/analyze_test.gopkg/devcontainer/lifecycle_rebuild_test.go
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ 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
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
- 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]>
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]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
These changes were released in v1.220.0-rc.4. |
what
-s).assume_role.terraform outputsubprocess has the correct credentials.why
Two bugs in the store hooks execution path caused hooks to silently fail in common scenarios:
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 componentand selects the stack from the interactive prompt, the selected stack value was stored in the localinfo.Stackbut never persisted to the Cobra flag set. PostRunE hooks re-parse args viaProcessCommandLineArgs, which reads fromcmd.Flags().GetString("stack")— still empty. The hook silently skipped because it saw no stack. Fix: after the interactive prompt fillsinfo.Stack, also set the Cobra flag viaf.Value.Set(stack)so downstream consumers can read it.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 outputsubprocess needs credentials to access the S3 state backend, which often requires a chained role assumption (e.g.,dev-role → tfstate-access-role). The mainExecuteTerraformsets up the full credential chain viasetupTerraformAuthandprepareComponentExecution, but it takesinfoby value — the populatedAuthContextandAuthManagerdon't flow back to the caller. The PostRunE hook creates a freshinfowith nil auth fields, so the output subprocess fails with "No valid credential sources found". Fix: persist the auth context viaSetLastAuthContextafterprepareComponentExecution, and inject it into the hook's freshinfoinrunHooksWithOutput.references
Summary by CodeRabbit
Bug Fixes
Chores
Tests
Documentation