Repository navigation
fix(terraform): preserve explicit identity and auth context for local runs - #2348
Conversation
…ight noise Prevent terraform execution from falling back to default CI identity when users pass --identity/-i, skip CI hook setup on non-CI local runs unless forced, and propagate AuthManager through component processing so nested terraform state/output resolution reuses the authenticated identity. Made-with: Cursor
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
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 (2)
📝 WalkthroughWalkthroughAdds ChangesIdentity shorthand and authentication pipeline
Hook template processing and CI provider improvements
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/exec/cli_utils.go`:
- Around line 509-510: The stripping logic currently marks "-i" in the set map
as a value-taking flag (set["-i"] = true), which causes the stripper to always
consume the next token and drop native flags like "-i -lock=false"; instead,
change the behavior to treat "-i" as an optional-value flag: update the stripper
so that when encountering "-i" it only consumes the following token if that
token exists and does NOT start with '-' (i.e. a real identity value), otherwise
it leaves the next token intact. Apply this same fix where "-i" is registered in
the set map (the earlier set["-i"] assignment) and in the other similar block
around the 691-697 area, and ensure this matches parseIdentityFlag's behavior.
- Around line 239-244: The identity flag handler currently returns an empty
string when the user passed --identity= (Cobra marks the flag changed with an
empty value), which lets env var ATMOS_IDENTITY override an explicit request for
interactive selection; change the logic in the flag-read sites (the block using
cmd.Flags().GetString("identity") and the other similar blocks at the indicated
locations) to detect when cmd.Flags().Changed("identity") is true and value ==
"" and, in that case, return cfg.IdentityFlagSelectValue (with true) instead of
"" so an explicit empty flag maps to the interactive-selection sentinel;
otherwise keep the existing NormalizeIdentityValue(value) behavior and return
true.
In `@pkg/hooks/hooks_test.go`:
- Around line 520-528: The test is flaky when running under a CI environment
because ci.IsCI() can be true; to isolate it, at the start of this test function
(before the two t.Run calls) call backup := testSaveAndClearRegistry() and defer
testRestoreRegistry(backup) so all CI providers are temporarily disabled; this
ensures the first subtest calling RunCIHooks("before.terraform.plan", config,
info, "", false, nil) sees ci.IsCI() == false and skips hooks while the second
subtest still exercises the experimental gate.
🪄 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: 417ea92e-3c00-40ec-9201-95364cd15491
📒 Files selected for processing (9)
internal/exec/cli_utils.gointernal/exec/cli_utils_identity_test.gointernal/exec/cli_utils_test.gointernal/exec/utils.gointernal/exec/utils_authmanager_propagation_test.gopkg/hooks/hooks.gopkg/hooks/hooks_test.gotests/fixtures/scenarios/native-ci/github-output.txttests/fixtures/scenarios/native-ci/github-step-summary.txt
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
internal/exec/terraform_execute_helpers.go (1)
132-135: Add perf tracking to the exported helper.
SetupTerraformAuthForCLIis a new public entry point and delegates to untracked auth setup work, so addperf.Trackhere.♻️ Proposed fix
import ( "context" "errors" "fmt" @@ cfg "github.com/cloudposse/atmos/pkg/config" "github.com/cloudposse/atmos/pkg/dependencies" log "github.com/cloudposse/atmos/pkg/logger" + "github.com/cloudposse/atmos/pkg/perf" "github.com/cloudposse/atmos/pkg/provisioner" _ "github.com/cloudposse/atmos/pkg/provisioner/source" // register source provisioner @@ func SetupTerraformAuthForCLI(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (any, error) { + defer perf.Track(atmosConfig, "exec.SetupTerraformAuthForCLI")() + return setupTerraformAuth(atmosConfig, info) }As per coding guidelines, “Add
defer perf.Track(atmosConfig, "pkg.FuncName")()plus blank line to all public functions.”🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/terraform_execute_helpers.go` around lines 132 - 135, The exported function SetupTerraformAuthForCLI currently delegates to setupTerraformAuth without performance tracking; add a perf.Track invocation at the top of SetupTerraformAuthForCLI by inserting a defer perf.Track(atmosConfig, "internal/exec.SetupTerraformAuthForCLI")() immediately after the function starts, followed by a blank line, so the public entrypoint is tracked while still delegating to setupTerraformAuth.cmd/terraform/output.go (1)
112-126: Make the auth propagation explicit.Line 126 depends on
info.AuthManagerbeing populated by side effect. Capture the returned manager too, so the handoff is clear and test stubs cannot accidentally drop it.♻️ Proposed cleanup
- if _, err := outputSetupTerraformAuth(&atmosConfig, &info); err != nil { + authManager, err := outputSetupTerraformAuth(&atmosConfig, &info) + if err != nil { return nil, nil, err } + info.AuthManager = authManager return &info, &atmosConfig, nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/terraform/output.go` around lines 112 - 126, The code relies on info.AuthManager being set as a side-effect of outputSetupTerraformAuth; instead capture and use the returned auth manager explicitly. Change the call that currently ignores outputSetupTerraformAuth's return to assign its returned manager (e.g., authManager, atmosConfig, info := outputSetupTerraformAuth(...)) and then pass that authManager into outputGetComponentOutputs (instead of info.AuthManager) inside executeOutputWithFormat; update any variable names accordingly so the handoff between outputSetupTerraformAuth, executeOutputWithFormat, and outputGetComponentOutputs is explicit and testable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cmd/terraform/output_test.go`:
- Around line 331-374: The test only restores the Viper key "output-file" but
executeOutputWithFormat also reads "skip-init", "uppercase", and "flatten", so
capture the original values for those keys from viper.GetViper(), set any
desired test values (or leave false/zero) before calling
executeOutputWithFormat, and register a t.Cleanup that restores each original
value; update TestExecuteOutputWithFormat_PassesAuthManager to save and restore
v.Get("skip-init"), v.Get("uppercase"), and v.Get("flatten") (similar to how
origOutputFile is handled) so shared Viper state cannot cause order-dependent
failures.
---
Nitpick comments:
In `@cmd/terraform/output.go`:
- Around line 112-126: The code relies on info.AuthManager being set as a
side-effect of outputSetupTerraformAuth; instead capture and use the returned
auth manager explicitly. Change the call that currently ignores
outputSetupTerraformAuth's return to assign its returned manager (e.g.,
authManager, atmosConfig, info := outputSetupTerraformAuth(...)) and then pass
that authManager into outputGetComponentOutputs (instead of info.AuthManager)
inside executeOutputWithFormat; update any variable names accordingly so the
handoff between outputSetupTerraformAuth, executeOutputWithFormat, and
outputGetComponentOutputs is explicit and testable.
In `@internal/exec/terraform_execute_helpers.go`:
- Around line 132-135: The exported function SetupTerraformAuthForCLI currently
delegates to setupTerraformAuth without performance tracking; add a perf.Track
invocation at the top of SetupTerraformAuthForCLI by inserting a defer
perf.Track(atmosConfig, "internal/exec.SetupTerraformAuthForCLI")() immediately
after the function starts, followed by a blank line, so the public entrypoint is
tracked while still delegating to setupTerraformAuth.
🪄 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: ca7b2a97-a454-4259-b066-6bdc7c3c7610
📒 Files selected for processing (3)
cmd/terraform/output.gocmd/terraform/output_test.gointernal/exec/terraform_execute_helpers.go
- Added tests to verify the behavior of the `-i` flag as an optional-value flag, ensuring that trailing native flags are preserved during pass-through stripping. - Implemented a test to confirm that explicitly passing an empty identity flag (`--identity=`) is treated as an interactive-selection sentinel, preventing it from being overridden by environment variables. - Updated the `TestProcessComponentConfig_PropagatesAuthManager` to ensure the correct propagation of the AuthContext with AWS credentials. These changes improve the robustness of identity handling in the Atmos CLI and ensure accurate propagation of authentication contexts.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (7)
cmd/terraform/output_test.go (1)
20-27: Helper looks solid.
initOutputTestIOcleanly bootstraps the IO/UI singletons and registersdata.Resetviat.Cleanup. One small thought: ifuiexposes a reset, you may want to register it here too so formatter state from this test doesn't leak into siblings — otherwise this is fine as-is.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/terraform/output_test.go` around lines 20 - 27, The test helper initOutputTestIO currently calls ui.InitFormatter and registers data.Reset in t.Cleanup; to avoid formatter state leaking into sibling tests, also register the UI reset function in the cleanup (e.g., add ui.Reset or ui.ResetFormatter to the t.Cleanup calls alongside data.Reset); if the ui package does not yet expose a reset function, add a public reset (e.g., ui.ResetFormatter) and call it from the test helper after ui.InitFormatter.internal/exec/utils_authmanager_propagation_test.go (2)
14-57: Add a negative-path companion test for the nil/empty branches.The current test only covers the happy path where
authManager != nilandGetStackInfo()returns a non-nilAuthContext. The guarded branches ininternal/exec/utils.go(lines 195-201) —authManager == nil,GetStackInfo() == nil, andmanagerStackInfo.AuthContext == nil— are untested, so a future refactor could regress them silently.As per coding guidelines: "Include negative-path tests for recovery logic: whenever a test verifies that a recovery/fallback triggers under condition X, add a corresponding test that verifies the recovery does NOT trigger when condition X is absent."
🧪 Suggested companion subtests (illustrative)
func TestProcessComponentConfig_AuthManagerNil(t *testing.T) { stacksMap := map[string]any{ /* same fixture */ } info := &schema.ConfigAndStacksInfo{} err := ProcessComponentConfig(&schema.AtmosConfiguration{}, info, "tenant-dev-test", stacksMap, "terraform", "vpc", nil) require.NoError(t, err) assert.Nil(t, info.AuthManager) assert.Nil(t, info.AuthContext) } func TestProcessComponentConfig_AuthManagerNilStackInfo(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mock := types.NewMockAuthManager(ctrl) mock.EXPECT().GetStackInfo().Return(nil).Times(1) // ... assert info.AuthManager == mock but info.AuthContext == nil. }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/utils_authmanager_propagation_test.go` around lines 14 - 57, Add negative-path tests for ProcessComponentConfig to cover the guarded branches where authManager == nil, GetStackInfo() == nil, and managerStackInfo.AuthContext == nil: create subtests in internal/exec/utils_authmanager_propagation_test.go that reuse the stacksMap fixture and call ProcessComponentConfig with (a) nil authManager and assert info.AuthManager==nil and info.AuthContext==nil, (b) a gomock mock AuthManager whose GetStackInfo() returns nil and assert info.AuthManager==mock and info.AuthContext==nil, and (c) a mock whose GetStackInfo() returns a ConfigAndStacksInfo with nil AuthContext and assert info.AuthManager==mock and info.AuthContext==nil; use gomock.Controller and require.NoError/assert.Equal as in the existing TestProcessComponentConfig_PropagatesAuthManager.
15-16: Drop the redundantdefer ctrl.Finish().Your project uses go.uber.org/mock v0.6.0 with Go 1.26, both of which support automatic cleanup registration in
NewController(t). The defer statement is harmless but adds unnecessary noise.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/utils_authmanager_propagation_test.go` around lines 15 - 16, Remove the redundant cleanup call by deleting the explicit "defer ctrl.Finish()" after creating the gomock controller; keep the controller creation line "ctrl := gomock.NewController(t)" in the test so that automatic cleanup provided by NewController(t) is used instead of calling ctrl.Finish() manually.internal/exec/cli_utils.go (2)
280-287: Add a doc comment forpreferArgsIdentityOverSelectValue.The helper is non-trivial (it encodes the "Cobra reports SelectValue but raw args have a real identity" rule that the prior PRs needed to fix). A short doc comment would make the precedence rule self-documenting alongside
resolveIdentityValue.📝 Proposed doc
+// preferArgsIdentityOverSelectValue returns argsIdentity (normalized) when Cobra reports the +// interactive-selection sentinel but the legacy raw-args parser captured a real identity value. +// This recovers the explicit value for space-separated forms like `--identity value` / `-i value` +// where Cobra may surface NoOptDefVal-style sentinels. Otherwise the Cobra-parsed value wins. func preferArgsIdentityOverSelectValue(flagValue string, argsIdentity string) string {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/cli_utils.go` around lines 280 - 287, Add a short doc comment above the function preferArgsIdentityOverSelectValue that explains the precedence rule it implements: when Cobra reports the sentinel cfg.IdentityFlagSelectValue for a flag but raw CLI args contain a non-empty, non-sentinel identity, the function returns the normalized args identity (via cfg.NormalizeIdentityValue) instead of the flagValue; otherwise it returns flagValue. Mention the relation to resolveIdentityValue and the sentinel cfg.IdentityFlagSelectValue so future readers understand why this helper exists.
80-81: Consider extracting-ishorthand to acfgconstant.
cfg.IdentityFlagis used everywhere else for the long form, but-iis hardcoded as a raw string here, and again at lines 569, 580, and 706. A smallcfg.IdentityFlagShort = "-i"would keep the shorthand discoverable and prevent drift if the shorthand ever changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/cli_utils.go` around lines 80 - 81, The hardcoded shorthand "-i" is repeated and should be added to the cfg struct as a named constant to avoid drift; add a new cfg.IdentityFlagShort = "-i" and replace all occurrences of the raw "-i" (e.g., in the CLI flag setup where cfg.IdentityFlag is used) with cfg.IdentityFlagShort so both the long and short forms are discoverable and maintained in one place.pkg/ci/registry_provider.go (1)
94-113: Clean addition; consider unifying with the in-package test helpers.The cross-package isolation utility looks solid — lock scoping is correct, the restore closure is symmetric, and the doc comment explains the intent well.
One small nit:
pkg/ci/registry_provider_test.goalready hastestSaveAndClearRegistry/testRestoreRegistrydoing essentially the same thing with a different shape (returning the map vs. a restore closure). Now thatSwapRegistryForTestexists, those in-package helpers could delegate to it so there's one canonical pattern across the codebase.♻️ Suggested follow-up in
pkg/ci/registry_provider_test.go// testSaveAndClearRegistry delegates to the exported helper so the same // swap-and-restore semantics are used everywhere. func testSaveAndClearRegistry() func() { return SwapRegistryForTest() } func testRestoreRegistry(restore func()) { restore() }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/ci/registry_provider.go` around lines 94 - 113, The in-package test helpers duplicate the swap-and-restore logic now provided by SwapRegistryForTest; update pkg/ci/registry_provider_test.go so testSaveAndClearRegistry delegates to the exported SwapRegistryForTest (i.e., return SwapRegistryForTest()) and make testRestoreRegistry simply invoke the passed restore function; this unifies behavior under the single canonical helper (referencing SwapRegistryForTest, testSaveAndClearRegistry, and testRestoreRegistry).pkg/hooks/hooks_test.go (1)
234-240: Strengthen the assertion to actually prove templates weren't processed.The test name says "DoesNotProcessTemplates" and the fixture relies on the malformed
"{{"payload, but the assertions only verify the hook loaded with the right command — same checks would pass even if templates were processed (assuming processing somehow succeeded or silently dropped the value). Add an assertion that the raw{{literal survives intact in the hook outputs to make the test meaningful and regression-proof.♻️ Proposed assertion tightening
assert.Contains(t, hooks.items, "static-hook") assert.Equal(t, "store", hooks.items["static-hook"].Command) + // Confirm the malformed template payload was preserved verbatim, proving + // ProcessTemplates=false took the GetHooks path instead of the renderer. + assert.Equal(t, "{{", hooks.items["static-hook"].Outputs["broken"], + "raw template payload must survive unprocessed")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/hooks/hooks_test.go` around lines 234 - 240, The test currently only checks the hook exists and its Command, but to prove templates weren't processed you must assert the raw malformed template literal survives; update the test after calling GetHooks to also check the hook's payload field (e.g. hooks.items["static-hook"].Outputs or whichever field holds the hook output/template) contains the literal "{{" (or the exact malformed string used in the fixture) so the test fails if template processing altered or removed the raw text.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/hooks/hooks_test.go`:
- Around line 174-232: The test TestGetHooks_DoesNotProcessTemplates fails
because the provided Stack "acme-dev-test" does not exist in the generated
stacksMap (lookup happens in ProcessComponentConfig in utils.go), so update the
fixture to make the stack key resolvable: either set info.Stack to the
manifest-derived key (e.g., "orgs/acme/_defaults") or add a manifest that
produces the "acme-dev-test" key (for example create
stacks/orgs/acme/acme-dev-test.yaml or add an explicit name: acme-dev-test in
the acme manifest) so ProcessComponentConfig can find the stack and the test
reaches hook discovery.
---
Nitpick comments:
In `@cmd/terraform/output_test.go`:
- Around line 20-27: The test helper initOutputTestIO currently calls
ui.InitFormatter and registers data.Reset in t.Cleanup; to avoid formatter state
leaking into sibling tests, also register the UI reset function in the cleanup
(e.g., add ui.Reset or ui.ResetFormatter to the t.Cleanup calls alongside
data.Reset); if the ui package does not yet expose a reset function, add a
public reset (e.g., ui.ResetFormatter) and call it from the test helper after
ui.InitFormatter.
In `@internal/exec/cli_utils.go`:
- Around line 280-287: Add a short doc comment above the function
preferArgsIdentityOverSelectValue that explains the precedence rule it
implements: when Cobra reports the sentinel cfg.IdentityFlagSelectValue for a
flag but raw CLI args contain a non-empty, non-sentinel identity, the function
returns the normalized args identity (via cfg.NormalizeIdentityValue) instead of
the flagValue; otherwise it returns flagValue. Mention the relation to
resolveIdentityValue and the sentinel cfg.IdentityFlagSelectValue so future
readers understand why this helper exists.
- Around line 80-81: The hardcoded shorthand "-i" is repeated and should be
added to the cfg struct as a named constant to avoid drift; add a new
cfg.IdentityFlagShort = "-i" and replace all occurrences of the raw "-i" (e.g.,
in the CLI flag setup where cfg.IdentityFlag is used) with cfg.IdentityFlagShort
so both the long and short forms are discoverable and maintained in one place.
In `@internal/exec/utils_authmanager_propagation_test.go`:
- Around line 14-57: Add negative-path tests for ProcessComponentConfig to cover
the guarded branches where authManager == nil, GetStackInfo() == nil, and
managerStackInfo.AuthContext == nil: create subtests in
internal/exec/utils_authmanager_propagation_test.go that reuse the stacksMap
fixture and call ProcessComponentConfig with (a) nil authManager and assert
info.AuthManager==nil and info.AuthContext==nil, (b) a gomock mock AuthManager
whose GetStackInfo() returns nil and assert info.AuthManager==mock and
info.AuthContext==nil, and (c) a mock whose GetStackInfo() returns a
ConfigAndStacksInfo with nil AuthContext and assert info.AuthManager==mock and
info.AuthContext==nil; use gomock.Controller and require.NoError/assert.Equal as
in the existing TestProcessComponentConfig_PropagatesAuthManager.
- Around line 15-16: Remove the redundant cleanup call by deleting the explicit
"defer ctrl.Finish()" after creating the gomock controller; keep the controller
creation line "ctrl := gomock.NewController(t)" in the test so that automatic
cleanup provided by NewController(t) is used instead of calling ctrl.Finish()
manually.
In `@pkg/ci/registry_provider.go`:
- Around line 94-113: The in-package test helpers duplicate the swap-and-restore
logic now provided by SwapRegistryForTest; update
pkg/ci/registry_provider_test.go so testSaveAndClearRegistry delegates to the
exported SwapRegistryForTest (i.e., return SwapRegistryForTest()) and make
testRestoreRegistry simply invoke the passed restore function; this unifies
behavior under the single canonical helper (referencing SwapRegistryForTest,
testSaveAndClearRegistry, and testRestoreRegistry).
In `@pkg/hooks/hooks_test.go`:
- Around line 234-240: The test currently only checks the hook exists and its
Command, but to prove templates weren't processed you must assert the raw
malformed template literal survives; update the test after calling GetHooks to
also check the hook's payload field (e.g. hooks.items["static-hook"].Outputs or
whichever field holds the hook output/template) contains the literal "{{" (or
the exact malformed string used in the fixture) so the test fails if template
processing altered or removed the raw text.
🪄 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: 79df99f8-e84d-4dc7-ad69-3015c50aab73
📒 Files selected for processing (9)
cmd/terraform/output.gocmd/terraform/output_test.gointernal/exec/cli_utils.gointernal/exec/cli_utils_identity_test.gointernal/exec/cli_utils_test.gointernal/exec/terraform_execute_helpers.gointernal/exec/utils_authmanager_propagation_test.gopkg/ci/registry_provider.gopkg/hooks/hooks_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- cmd/terraform/output.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
pkg/ci/registry_provider_test.go (1)
142-150: Consider inlining these thin wrappers.Both helpers now do nothing beyond forwarding to
SwapRegistryForTest()and invoking the returned closure. Call sites could read more naturally asdefer SwapRegistryForTest()()(orrestore := SwapRegistryForTest(); defer restore()), removing the indirection. Happy to leave them if you prefer keeping the local test-API stable.♻️ Optional inline refactor at call sites
- backup := testSaveAndClearRegistry() - defer testRestoreRegistry(backup) + defer SwapRegistryForTest()()And drop
testSaveAndClearRegistry/testRestoreRegistry.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@pkg/ci/registry_provider_test.go` around lines 142 - 150, The two thin wrappers testSaveAndClearRegistry and testRestoreRegistry simply forward to SwapRegistryForTest and its returned closure; remove these wrappers and update call sites to inline the behavior by calling defer SwapRegistryForTest()() (or using restore := SwapRegistryForTest(); defer restore()), replacing references to testSaveAndClearRegistry/testRestoreRegistry with direct use of SwapRegistryForTest and its returned restore function.cmd/identity_flag.go (1)
70-116: Tiny godoc nit: mention the-ishorthand.The logic now handles
-i,-i=value, and-i valuesymmetrically with--identity, but the function comment at lines 70-79 still only enumerates the long-form cases. A quick line for the shorthand would keep the docs honest with the implementation.📝 Suggested doc tweak
// extractIdentityFromArgs manually parses os.Args to find --identity flag and its value. // This is necessary because Cobra's NoOptDefVal behavior causes it to misinterpret // "--identity value" as "--identity" (without value) when positional args are present. // -// Handles three cases: -// - --identity value (space-separated) -> returns "value" -// - --identity=value (equals sign) -> returns "value" -// - --identity (no value) -> returns cfg.IdentityFlagSelectValue +// Handles the long and short forms symmetrically: +// - --identity value | -i value (space-separated) -> returns "value" +// - --identity=value | -i=value (equals sign) -> returns "value" +// - --identity | -i (no value) -> returns cfg.IdentityFlagSelectValue // -// Returns empty string if --identity flag is not present in args. +// Returns empty string if neither --identity nor -i is present in args.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/identity_flag.go` around lines 70 - 116, Update the comment for extractIdentityFromArgs to mention the short flag shorthand handled (cfg.IdentityFlagShort, e.g., -i) so the doc lists both long and short forms; explicitly state that the function handles --identity value, --identity=value, --identity (no value), and the equivalent -i value, -i=value, and -i (no value) cases, keeping the rest of the comment intact.cmd/terraform/output_test.go (1)
20-28: Optional: guard against concurrent IO/UI re-init.
initOutputTestIOmutates process-global IO and UI singletons viadata.InitWriter/ui.InitFormatterand resets them on cleanup. If a future test in this package ever callst.Parallel()(or another helper initializes these singletons concurrently), theResetcleanups can race with another in-flight test. Worth a brief comment here noting "do not callt.Parallel()in tests using this helper" so the constraint is explicit for the next contributor.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/terraform/output_test.go` around lines 20 - 28, initOutputTestIO mutates package-global IO/UI singletons via data.InitWriter and ui.InitFormatter and registers data.Reset and ui.Reset for cleanup; update the helper to document the concurrency constraint (e.g., add a short comment above initOutputTestIO) stating that tests using initOutputTestIO must not call t.Parallel() or reinitialize these singletons concurrently to avoid races between Reset cleanups, and reference the involved symbols (initOutputTestIO, data.InitWriter, ui.InitFormatter, data.Reset, ui.Reset) so future contributors see the limitation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@pkg/ci/registry_provider_test.go`:
- Around line 147-150: Update the doc comment so its leading identifier matches
the actual function name: change the comment that starts "TestRestoreRegistry
restores the provider registry..." to begin with "testRestoreRegistry restores
the provider registry..." (or alternatively export the function by renaming it
to TestRestoreRegistry and update usages/tests accordingly); ensure the comment
prefix exactly matches the function name `testRestoreRegistry` (or
`TestRestoreRegistry` if you choose to export) to satisfy Godoc conventions.
---
Nitpick comments:
In `@cmd/identity_flag.go`:
- Around line 70-116: Update the comment for extractIdentityFromArgs to mention
the short flag shorthand handled (cfg.IdentityFlagShort, e.g., -i) so the doc
lists both long and short forms; explicitly state that the function handles
--identity value, --identity=value, --identity (no value), and the equivalent -i
value, -i=value, and -i (no value) cases, keeping the rest of the comment
intact.
In `@cmd/terraform/output_test.go`:
- Around line 20-28: initOutputTestIO mutates package-global IO/UI singletons
via data.InitWriter and ui.InitFormatter and registers data.Reset and ui.Reset
for cleanup; update the helper to document the concurrency constraint (e.g., add
a short comment above initOutputTestIO) stating that tests using
initOutputTestIO must not call t.Parallel() or reinitialize these singletons
concurrently to avoid races between Reset cleanups, and reference the involved
symbols (initOutputTestIO, data.InitWriter, ui.InitFormatter, data.Reset,
ui.Reset) so future contributors see the limitation.
In `@pkg/ci/registry_provider_test.go`:
- Around line 142-150: The two thin wrappers testSaveAndClearRegistry and
testRestoreRegistry simply forward to SwapRegistryForTest and its returned
closure; remove these wrappers and update call sites to inline the behavior by
calling defer SwapRegistryForTest()() (or using restore :=
SwapRegistryForTest(); defer restore()), replacing references to
testSaveAndClearRegistry/testRestoreRegistry with direct use of
SwapRegistryForTest and its returned restore function.
🪄 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: 3841febd-d715-4241-bd5e-401f8fab8040
📒 Files selected for processing (11)
cmd/auth.gocmd/auth_exec.gocmd/auth_shell.gocmd/identity_flag.gocmd/terraform/flags.gocmd/terraform/output_test.gointernal/exec/cli_utils.gointernal/exec/utils_authmanager_propagation_test.gopkg/ci/registry_provider_test.gopkg/config/const.gopkg/hooks/hooks_test.go
✅ Files skipped from review due to trivial changes (4)
- cmd/auth_shell.go
- cmd/auth.go
- cmd/terraform/flags.go
- cmd/auth_exec.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/exec/utils_authmanager_propagation_test.go
- pkg/hooks/hooks_test.go
- internal/exec/cli_utils.go
|
Mikhail Shirkov (@shirkevich) thanks for the PR, please resolve the conflicts and ping me for re-review |
…ity-ci-preflight-noise # Conflicts: # cmd/auth.go # cmd/auth_exec.go # cmd/auth_shell.go # cmd/terraform/flags.go # internal/exec/cli_utils_identity_test.go # internal/exec/cli_utils_test.go # pkg/component/ansible/executor.go # pkg/flags/global_registry.go # pkg/hooks/hooks_test.go
|
CodeRabbit (@coderabbitai) review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/ansible/ansible_test.go`:
- Around line 82-103: The test
TestAnsibleIdentityRegistryNormalizesLongIdentityOnly does not initialize the
cmd test kit, so add a call to cmd.NewTestKit(t) at the start of this test to
ensure RootCmd state (flags/args) is reset before using
internal.GetCommandFlagRegistry and preprocess.NewNoOptDefValPreprocessor;
similarly, add cmd.NewTestKit(t) to the other new command tests in this file
(the other tests added in the same diff) to avoid cross-test coupling.
In `@cmd/ansible/ansible.go`:
- Around line 126-133: resolveAnsibleIdentity currently returns parsedIdentity
raw while other branches call cfg.NormalizeIdentityValue; change the early
return to normalize parsedIdentity via cfg.NormalizeIdentityValue before
returning so behavior is consistent; update the return for the parsedIdentity
branch in resolveAnsibleIdentity to call
cfg.NormalizeIdentityValue(parsedIdentity) and keep the existing
getChangedIdentityFlagValue branch unchanged.
🪄 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: 74b94c05-906b-4e55-a952-2a838190d9ab
📒 Files selected for processing (21)
cmd/ansible/ansible.gocmd/ansible/ansible_test.gocmd/identity_helpers.gocmd/terraform/flags.gocmd/terraform/output.gocmd/terraform/output_test.gointernal/exec/cli_utils.gointernal/exec/cli_utils_identity_test.gointernal/exec/cli_utils_test.gointernal/exec/terraform_execute_helpers.gointernal/exec/terraform_output_getter.gointernal/exec/terraform_output_getter_test.gointernal/exec/utils.gopkg/ci/registry_provider_test.gopkg/component/ansible/executor.gopkg/component/ansible/executor_test.gopkg/config/const.gopkg/flags/global_registry.gopkg/flags/global_registry_test.gopkg/hooks/hooks.gopkg/hooks/hooks_test.go
💤 Files with no reviewable changes (18)
- internal/exec/terraform_output_getter_test.go
- pkg/flags/global_registry_test.go
- pkg/config/const.go
- pkg/component/ansible/executor.go
- internal/exec/utils.go
- internal/exec/terraform_execute_helpers.go
- internal/exec/terraform_output_getter.go
- pkg/component/ansible/executor_test.go
- internal/exec/cli_utils_test.go
- cmd/terraform/flags.go
- cmd/terraform/output.go
- cmd/terraform/output_test.go
- pkg/ci/registry_provider_test.go
- pkg/flags/global_registry.go
- internal/exec/cli_utils_identity_test.go
- pkg/hooks/hooks.go
- pkg/hooks/hooks_test.go
- internal/exec/cli_utils.go
|
Andriy Knysh (@aknysh) ready for review |
Codecov Report❌ Patch coverage is ❌ Your patch check has failed because the patch coverage (72.41%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #2348 +/- ##
==========================================
+ Coverage 78.21% 78.24% +0.03%
==========================================
Files 1119 1119
Lines 106335 106484 +149
==========================================
+ Hits 83171 83323 +152
+ Misses 18522 18506 -16
- Partials 4642 4655 +13
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
cee5479
into
cloudposse:main
Pre-commit was failing on the merge ref for PR #2482 because three commits recently merged to main (#2348, #2478, #2481) contain files that were not gofumpt-formatted and a couple of native-ci test fixtures with trailing whitespace from captured terraform output. These files are not touched by this PR, but they appear in the PR's GitHub-generated merge ref diff and so pre-commit checks them. Apply the auto-fixes that pre-commit produces: - cmd/terraform/output.go: group two consecutive var decls. - internal/exec/terraform_output_getter_test.go: line-break in assert.PanicsWithValue calls (2x). - pkg/terraform/output/executor_test.go: line-break in NewExecutor call. - pkg/terraform/output/get_test.go: line-break in assert.PanicsWithValue calls (3x). - tests/fixtures/scenarios/native-ci/github-output.txt: trim trailing whitespace. - tests/fixtures/scenarios/native-ci/github-step-summary.txt: trim trailing whitespace. The fixture files are runtime outputs set via GITHUB_OUTPUT and GITHUB_STEP_SUMMARY env vars during the native-ci test scenarios and are only checked via file_contains substring assertions, so trimming trailing whitespace is safe. Co-Authored-By: Claude Opus 4.7 <[email protected]>
…nd skip controls (#2482) * feat(hooks): kind system + scanner kinds + auto-install + --skip-hooks Co-Authored-By: Claude Opus 4.7 <[email protected]> * chore(hooks): test coverage + error-builder polish + helper extraction Co-Authored-By: Claude Opus 4.7 <[email protected]> * chore: apply gofumpt and trim trailing whitespace after main merge Pre-commit was failing on the merge ref for PR #2482 because three commits recently merged to main (#2348, #2478, #2481) contain files that were not gofumpt-formatted and a couple of native-ci test fixtures with trailing whitespace from captured terraform output. These files are not touched by this PR, but they appear in the PR's GitHub-generated merge ref diff and so pre-commit checks them. Apply the auto-fixes that pre-commit produces: - cmd/terraform/output.go: group two consecutive var decls. - internal/exec/terraform_output_getter_test.go: line-break in assert.PanicsWithValue calls (2x). - pkg/terraform/output/executor_test.go: line-break in NewExecutor call. - pkg/terraform/output/get_test.go: line-break in assert.PanicsWithValue calls (3x). - tests/fixtures/scenarios/native-ci/github-output.txt: trim trailing whitespace. - tests/fixtures/scenarios/native-ci/github-step-summary.txt: trim trailing whitespace. The fixture files are runtime outputs set via GITHUB_OUTPUT and GITHUB_STEP_SUMMARY env vars during the native-ci test scenarios and are only checked via file_contains substring assertions, so trimming trailing whitespace is safe. Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(snapshots): regenerate help snapshots for --skip-hooks global flag The new --skip-hooks global flag added in pkg/flags/global_builder.go appears in every command's --help output. Regenerated the 39 affected golden snapshots so TestCLICommands passes on Linux, macOS, and Windows. Also includes: - pkg/hooks/hooks_test.go: save and restore prior viper "skip-hooks" value in TestRunAll_SkipHooksBypassesPreflightBinaryCheck to avoid cross-test viper leakage. - website/src/data/roadmap.js: minor copy edit to custom-hooks milestone. Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(ci): update test workflow checkout actions * test(hooks): assert normalized legacy hook kind * test: increase hooks coverage * ci: disable checkout credential persistence * ci: pin workflow actions * docs: clarify custom hook outputs * docs: rewrite tool-deps PRD as requirements; split scanner kinds; document hook env var lifetime and --all Rewrite docs/prd/tool-dependencies-integration.md to state requirements and per-feature implementation status instead of narrating its own history. The PRD now leads with a Requirements & Implementation Status table that flags each requirement as Implemented or Not implemented with a code reference. Implementation Plan phases carry Status annotations. Success Criteria are plain numbered items, not a completion tracker. Split the lumped trivy/checkov/kics section in website/docs/stacks/hooks.mdx into three separate sections, one per kind, each with a definition list documenting that scanner's command, args, output handling, on_failure default, runtime requirements, and kind-specific quirks (Checkov's SSL_CERT_FILE workaround, KICS's KICS_QUERIES_PATH and curated registry override). Expand the ATMOS_OUTPUT_DIR / ATMOS_OUTPUT_FILE env-var entries to spell out the per-hook-invocation contract: fresh os.MkdirTemp("atmos-hook-*") directory created before the subprocess runs, deleted automatically when the hook returns, never shared between sibling hooks. Add a new "Hooks with --all" subsection covering per-component firing in dependency order, per-component tool install, shared --skip-hooks, and on_failure:fail aborting the downstream traversal. Co-Authored-By: Claude Opus 4.7 <[email protected]> * docs(hooks): link examples to website routes; document override semantics; drop stream paragraph from changelog Switch the Examples list in website/docs/stacks/hooks.mdx from raw GitHub URLs to the website's /examples/<name> routes (the file-browser plugin already publishes them). Add an "Overriding Kind Defaults" section to hooks.mdx documenting that any field set on a hook (command, args, env, on_failure) overrides the named kind's default for that field. Includes a caution callout that args and env are full replacement — not merge — so overriding args requires restating the full default arg list. Three examples cover the common cases: bumping a scanner's severity threshold via args, making a finding block the run via on_failure, and injecting a tool config path via env. Code path: pkg/hooks/kind.go::ResolveDefaults. Drop the "Tool output streams naturally" subsection from the custom hooks changelog entry per review feedback. Co-Authored-By: Claude Opus 4.7 <[email protected]> * docs(hooks): signal overridable defaults up front in Built-in Kinds preamble The per-kind sections list "(default)" values without indicating they're customizable. Add a one-paragraph preamble under "Built-in Kinds" that tells readers every default is overridable and points to the override rules section before they read any individual kind. Co-Authored-By: Claude Opus 4.7 <[email protected]> * docs(blog): link custom-hooks examples to /examples routes; add docs ActionCard Swap the four GitHub example URLs in the custom-hooks changelog post to the website's /examples/<name> routes (already published by the file-browser plugin), matching the change in website/docs/stacks/hooks.mdx. Append an ActionCard at the bottom pointing readers from the changelog narrative to /stacks/hooks for the full reference (kinds, override semantics, lifecycle events, tool auto-install, --all / --skip-hooks). The remaining github.com URL in the "Try it" section stays — git clone needs the GitHub URL. Co-Authored-By: Claude Opus 4.7 <[email protected]> * docs(blog): add override-defaults chapter; wire ActionCard CTAs correctly Add an "Override any default" h3 between the built-in-kinds and bring-your-own-command sections, matching the chapter style of "Workdir compatible". The new chapter shows that command, args, env, and on_failure are all overridable on built-in kinds, with a worked example (Trivy with HIGH,CRITICAL severity and on_failure: fail) and a call-out that args/env are full replacement, not merge — linking to the override docs at /stacks/hooks#overriding-kind-defaults. Fix the closing ActionCard so the CTA buttons actually render. The component reads ctaText/ctaLink and secondaryCtaText/secondaryCtaLink, not href. The card now renders a primary "Read the docs" CTA to /stacks/hooks and a secondary "Browse examples" CTA to /examples/hooks-trivy. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 <[email protected]> Co-authored-by: Andriy Knysh <[email protected]>
|
These changes were released in v1.220.0-rc.2. |
Problem
Local commands could still fall back to the default CI identity (
terraform-ci/gcp-wif) even when the user explicitly selected a local identity such asterraform/gcp-adc.This showed up in several related paths:
atmos terraform apply ... --identity terraformand-i terraformcould lose the explicit identity during Terraform argument reconstruction and then authenticate with the default identity.terraform-ciWIF authentication errors even when the command later succeeded with the intended local identity.atmos terraform output ... --format json -i terraformbypassed the normal Terraform auth setup and called formatted output resolution without the activeAuthManager/AuthContext.!terraform.stateevaluations could receive stack info without the active auth manager, so nested state reads could still resolve backend credentials from the default identity instead of the explicit command identity.atmos ansible playbook ... --identity terraformdid not propagate the selected identity into stack processing before YAML functions ran, so Ansible-driven components using!terraform.statecould still try the default Terraform CI WIF identity.Fixed Issues
--identity/-ivalues through both Cobra/flag-registry parsing and the legacy raw-arg parsing path.--identity=,-i=, and--identity=false.terraform-cipreflight auth noise.terraform outputand passes bothAuthContextandAuthManagerinto output resolution.AuthManagerfromProcessComponentConfigintoConfigAndStacksInfo, allowing!terraform.stateto inherit the selected identity context.--identity/ATMOS_IDENTITYwhile deliberately leaving Ansible's-ishorthand reserved for inventory.!terraform.statecan use the requested identity.Verification
rtk proxy go build -o build/atmos .rtk go test ./cmd/ansible ./pkg/component/ansible ./pkg/flags ./internal/exec ./pkg/hooks -run 'TestAnsible|TestBuildConfigAndStacksInfo|TestGetLongIdentityFromArgs|TestProcessStacksWithAuth|TestParseGlobalFlags|TestSetupTerraformAuth|TestProcessComponentConfig_PropagatesAuthManager|TestProcessComponentConfig_AuthManagerGuardBranches|TestProcessCommandLineArgs_EmptyIdentityFlagIsExplicitSelect|TestProcessCommandLineArgs_TerraformIdentityFlag_Issue2392|TestProcessArgsAndFlags_IdentityFlag|TestRunCIHooks_LocalRunSkipsExperimentalGate|TestRunCIHooks_ForwardsErrorAndExitCode|TestRunCIHooks_NilAtmosConfig|TestRunCIHooks_ExperimentalDisableReturnsError'--identity terraform.-i terraform --format json.identity "terraform"/provider=gcp-adc; remaining OAuth access was environment/network dependent, not a fallback toterraform-ci.Summary by CodeRabbit
New Features
-ishorthand for--identity(supports-i value,-i=value, and explicit-empty-i=to trigger interactive selection).Improvements
Bug Fixes
-lock=false) is not mis-consumed as an identity value.Tests