Skip to content

fix(terraform): preserve explicit identity and auth context for local runs - #2348

Merged
Andriy Knysh (aknysh) merged 12 commits into
cloudposse:mainfrom
shirkevich:fix/terraform-identity-ci-preflight-noise
May 23, 2026
Merged

Andriy Knysh (aknysh) merged 12 commits into
cloudposse:mainfrom
shirkevich:fix/terraform-identity-ci-preflight-noise

Conversation

@shirkevich

@shirkevich Mikhail Shirkov (shirkevich) commented Apr 21, 2026 •

Copy link
Copy Markdown
Collaborator

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 as terraform / gcp-adc.

This showed up in several related paths:

  • atmos terraform apply ... --identity terraform and -i terraform could lose the explicit identity during Terraform argument reconstruction and then authenticate with the default identity.
  • Local Terraform commands could run the CI hook path first, producing noisy terraform-ci WIF authentication errors even when the command later succeeded with the intended local identity.
  • atmos terraform output ... --format json -i terraform bypassed the normal Terraform auth setup and called formatted output resolution without the active AuthManager / AuthContext.
  • !terraform.state evaluations 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 terraform did not propagate the selected identity into stack processing before YAML functions ran, so Ansible-driven components using !terraform.state could still try the default Terraform CI WIF identity.

Fixed Issues

  • Preserves explicit Terraform --identity / -i values through both Cobra/flag-registry parsing and the legacy raw-arg parsing path.
  • Normalizes Terraform identity edge cases consistently, including --identity=, -i=, and --identity=false.
  • Keeps CLI-provided identity values ahead of default/profile-selected identities when Cobra reports the optional-value sentinel.
  • Skips CI hook execution for normal local non-CI runs unless CI mode is explicitly forced, removing local terraform-ci preflight auth noise.
  • Initializes Terraform auth for formatted terraform output and passes both AuthContext and AuthManager into output resolution.
  • Propagates the active AuthManager from ProcessComponentConfig into ConfigAndStacksInfo, allowing !terraform.state to inherit the selected identity context.
  • Adds shared component auth setup for non-Terraform command paths that need authenticated YAML functions.
  • Adds Ansible-specific identity handling that supports long-form --identity / ATMOS_IDENTITY while deliberately leaving Ansible's -i shorthand reserved for inventory.
  • Runs Ansible stack processing with the selected auth manager before YAML function evaluation, so Ansible playbooks using !terraform.state can use the requested identity.

Verification

  • Rebuilt the binary with rtk proxy go build -o build/atmos .
  • Focused regression suite passed: 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'
  • Downstream local Terraform apply path was verified with explicit --identity terraform.
  • Downstream formatted Terraform output path was verified with explicit -i terraform --format json.
  • Downstream Ansible dry-run path was verified to select identity "terraform" / provider=gcp-adc; remaining OAuth access was environment/network dependent, not a fallback to terraform-ci.

Summary by CodeRabbit

  • New Features

    • Added -i shorthand for --identity (supports -i value, -i=value, and explicit-empty -i= to trigger interactive selection).
  • Improvements

    • More robust identity resolution across commands and env vars; explicit-empty identity is preserved.
    • Auth manager is now propagated into output and component command flows for consistent auth behavior.
    • Hook discovery avoids rendering templates; CI hooks skip when no CI provider detected.
  • Bug Fixes

    • Fixed parsing so a following native flag (e.g., -lock=false) is not mis-consumed as an identity value.
  • Tests

    • Expanded test coverage for identity parsing, auth propagation, hooks, and CI registry behavior.

Review Change Stack

…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
@shirkevich
Mikhail Shirkov (shirkevich) requested a review from a team as a code owner April 21, 2026 16:19
@atmos-pro

atmos-pro Bot commented Apr 21, 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 Apr 21, 2026
@coderabbitai

coderabbitai Bot commented Apr 21, 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: f835eb25-0a26-44bd-be84-9020d5bfcb15

📥 Commits

Reviewing files that changed from the base of the PR and between 7fd2b5d and f2dcc98.

📒 Files selected for processing (2)
  • cmd/ansible/ansible.go
  • cmd/ansible/ansible_test.go

📝 Walkthrough

Walkthrough

Adds -i shorthand and precedence-aware identity parsing, preserves explicit-empty sentinel, threads AuthManager through output and component flows, adjusts hook template processing and CI gating, and adds tests and test helpers covering these behaviors.

Changes

Identity shorthand and authentication pipeline

Layer / File(s) Summary
Identity flag constants and basic registration
pkg/config/const.go, cmd/terraform/flags.go, cmd/identity_helpers.go
Adds short-form identity constants and updates flag registration and short-form parsing to reference config constants.
Identity shorthand and precedence parsing in CLI utils
internal/exec/cli_utils.go, internal/exec/cli_utils_identity_test.go, internal/exec/cli_utils_test.go
Extends CLI parsing to support -i/--identity (space and equals forms), detects explicitly empty sentinel (--identity=/-i=), resolves final identity by Cobra explicitness → raw args → env, and fixes optional-value stripping.
Global flag lookup and inheritance
pkg/flags/global_registry.go, pkg/flags/global_registry_test.go
Adds lookupCommandFlag using pflag to detect explicit Changed state across command hierarchy and uses it when parsing identity and pager NoOptDefVal values.
Ansible command identity resolution
cmd/ansible/ansible.go, cmd/ansible/ansible_test.go
Registers identity flag on Ansible command, implements resolution helpers that integrate parsed flag state, raw args, and env var into buildConfigAndStacksInfo, and adds tests.
AuthManager propagation through output pipeline
cmd/terraform/output.go, cmd/terraform/output_test.go, internal/exec/terraform_execute_helpers.go, internal/exec/terraform_output_getter.go
Return and thread authManager from prepareOutputContext into output retrieval; add indirection variables for test stubbing and exported CLI auth wrappers with perf tracking; update tests to assert authManager propagation.
Component-level authentication setup
internal/exec/utils.go, pkg/component/ansible/executor.go, pkg/component/ansible/executor_test.go
Persist AuthManager into ConfigAndStacksInfo and conditionally setup component auth in Ansible executor so stack processing receives the auth manager; add gomock-based tests.

Hook template processing and CI provider improvements

Layer / File(s) Summary
Hook template and CI provider improvements
pkg/hooks/hooks.go, pkg/ci/registry_provider.go
Disable template processing during hook discovery and skip CI hooks early when not running in CI (unless forced); add SwapRegistryForTest for test isolation.
Hook and CI tests and fixtures
pkg/hooks/hooks_test.go, tests/fixtures/scenarios/native-ci/*
Add tests to validate non-processing of hook templates and CI gating; update native CI fixtures/step-summary outputs to reflect resource changes in plan output.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • cloudposse/atmos#1735: Modifies --identity/-i parsing and sentinel handling; closely related to precedence and sentinel fixes.
  • cloudposse/atmos#2412: Overlaps identity parsing normalization and --identity=false handling.
  • cloudposse/atmos#1475: Prior work on identity CLI parsing and propagation into ConfigAndStacksInfo.

Suggested labels

patch

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.29% 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 summarizes the main objective: fixing regressions where explicit local identities were lost, causing fallback to CI identities.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

📥 Commits

Reviewing files that changed from the base of the PR and between c1bb921 and d6672dd.

📒 Files selected for processing (9)
  • internal/exec/cli_utils.go
  • internal/exec/cli_utils_identity_test.go
  • internal/exec/cli_utils_test.go
  • internal/exec/utils.go
  • internal/exec/utils_authmanager_propagation_test.go
  • pkg/hooks/hooks.go
  • pkg/hooks/hooks_test.go
  • tests/fixtures/scenarios/native-ci/github-output.txt
  • tests/fixtures/scenarios/native-ci/github-step-summary.txt

Comment thread internal/exec/cli_utils.go Resolved
Comment thread internal/exec/cli_utils.go Resolved
Comment thread pkg/hooks/hooks_test.go Resolved
@shirkevich Mikhail Shirkov (shirkevich) changed the title fix(terraform): preserve explicit identity and skip local CI preflight auth fix(terraform): preserve explicit identity and auth context for local runs Apr 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
internal/exec/terraform_execute_helpers.go (1)

132-135: Add perf tracking to the exported helper.

SetupTerraformAuthForCLI is a new public entry point and delegates to untracked auth setup work, so add perf.Track here.

♻️ 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.AuthManager being 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

📥 Commits

Reviewing files that changed from the base of the PR and between d6672dd and c4102dd.

📒 Files selected for processing (3)
  • cmd/terraform/output.go
  • cmd/terraform/output_test.go
  • internal/exec/terraform_execute_helpers.go

Comment thread cmd/terraform/output_test.go Resolved
- 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.

@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

🧹 Nitpick comments (7)
cmd/terraform/output_test.go (1)

20-27: Helper looks solid.

initOutputTestIO cleanly bootstraps the IO/UI singletons and registers data.Reset via t.Cleanup. One small thought: if ui exposes 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 != nil and GetStackInfo() returns a non-nil AuthContext. The guarded branches in internal/exec/utils.go (lines 195-201) — authManager == nil, GetStackInfo() == nil, and managerStackInfo.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 redundant defer 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 for preferArgsIdentityOverSelectValue.

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 -i shorthand to a cfg constant.

cfg.IdentityFlag is used everywhere else for the long form, but -i is hardcoded as a raw string here, and again at lines 569, 580, and 706. A small cfg.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.go already has testSaveAndClearRegistry / testRestoreRegistry doing essentially the same thing with a different shape (returning the map vs. a restore closure). Now that SwapRegistryForTest exists, 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

📥 Commits

Reviewing files that changed from the base of the PR and between c4102dd and 353725e.

📒 Files selected for processing (9)
  • cmd/terraform/output.go
  • cmd/terraform/output_test.go
  • internal/exec/cli_utils.go
  • internal/exec/cli_utils_identity_test.go
  • internal/exec/cli_utils_test.go
  • internal/exec/terraform_execute_helpers.go
  • internal/exec/utils_authmanager_propagation_test.go
  • pkg/ci/registry_provider.go
  • pkg/hooks/hooks_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/terraform/output.go

Comment thread pkg/hooks/hooks_test.go Resolved

@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

🧹 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 as defer SwapRegistryForTest()() (or restore := 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 -i shorthand.

The logic now handles -i, -i=value, and -i value symmetrically 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.

initOutputTestIO mutates process-global IO and UI singletons via data.InitWriter / ui.InitFormatter and resets them on cleanup. If a future test in this package ever calls t.Parallel() (or another helper initializes these singletons concurrently), the Reset cleanups can race with another in-flight test. Worth a brief comment here noting "do not call t.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

📥 Commits

Reviewing files that changed from the base of the PR and between 353725e and 016bd3f.

📒 Files selected for processing (11)
  • cmd/auth.go
  • cmd/auth_exec.go
  • cmd/auth_shell.go
  • cmd/identity_flag.go
  • cmd/terraform/flags.go
  • cmd/terraform/output_test.go
  • internal/exec/cli_utils.go
  • internal/exec/utils_authmanager_propagation_test.go
  • pkg/ci/registry_provider_test.go
  • pkg/config/const.go
  • pkg/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

Comment thread pkg/ci/registry_provider_test.go Resolved
coderabbitai[bot]
coderabbitai Bot previously approved these changes Apr 27, 2026
@aknysh

Copy link
Copy Markdown
Member

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
@github-actions github-actions Bot added size/l Large size PR and removed size/m Medium size PR labels May 20, 2026
@shirkevich

Copy link
Copy Markdown
Collaborator Author

CodeRabbit (@coderabbitai) review

@coderabbitai

coderabbitai Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 016bd3f and 7fd2b5d.

📒 Files selected for processing (21)
  • cmd/ansible/ansible.go
  • cmd/ansible/ansible_test.go
  • cmd/identity_helpers.go
  • cmd/terraform/flags.go
  • cmd/terraform/output.go
  • cmd/terraform/output_test.go
  • internal/exec/cli_utils.go
  • internal/exec/cli_utils_identity_test.go
  • internal/exec/cli_utils_test.go
  • internal/exec/terraform_execute_helpers.go
  • internal/exec/terraform_output_getter.go
  • internal/exec/terraform_output_getter_test.go
  • internal/exec/utils.go
  • pkg/ci/registry_provider_test.go
  • pkg/component/ansible/executor.go
  • pkg/component/ansible/executor_test.go
  • pkg/config/const.go
  • pkg/flags/global_registry.go
  • pkg/flags/global_registry_test.go
  • pkg/hooks/hooks.go
  • pkg/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

Comment thread cmd/ansible/ansible_test.go Resolved
Comment thread cmd/ansible/ansible.go Resolved
@shirkevich

Copy link
Copy Markdown
Collaborator Author

Andriy Knysh (@aknysh) ready for review

@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label May 23, 2026
@codecov

codecov Bot commented May 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.41379% with 48 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.24%. Comparing base (fdaca44) to head (d945f2c).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
cmd/terraform/output.go 15.38% 11 Missing ⚠️
cmd/ansible/ansible.go 81.25% 5 Missing and 4 partials ⚠️
internal/exec/cli_utils.go 78.04% 5 Missing and 4 partials ⚠️
internal/exec/terraform_execute_helpers.go 14.28% 6 Missing ⚠️
pkg/component/ansible/executor.go 61.53% 3 Missing and 2 partials ⚠️
pkg/flags/global_registry.go 84.00% 2 Missing and 2 partials ⚠️
cmd/identity_helpers.go 0.00% 3 Missing ⚠️
pkg/terraform/output/get.go 50.00% 1 Missing ⚠️

❌ 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

Impacted file tree graph

@@            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     
Flag Coverage Δ
unittests 78.24% <72.41%> (+0.03%) ⬆️

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

Files with missing lines Coverage Δ
cmd/terraform/flags.go 100.00% <100.00%> (ø)
internal/exec/terraform_output_getter.go 100.00% <100.00%> (ø)
internal/exec/utils.go 85.03% <100.00%> (+1.91%) ⬆️
pkg/ci/registry_provider.go 100.00% <100.00%> (ø)
pkg/hooks/hooks.go 81.13% <100.00%> (+0.54%) ⬆️
pkg/terraform/output/executor.go 88.84% <100.00%> (ø)
pkg/terraform/output/get.go 90.62% <50.00%> (ø)
cmd/identity_helpers.go 39.02% <0.00%> (ø)
pkg/flags/global_registry.go 98.47% <84.00%> (-1.53%) ⬇️
pkg/component/ansible/executor.go 42.61% <61.53%> (+1.18%) ⬆️
... and 4 more

... and 7 files with indirect coverage changes

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

@aknysh Andriy Knysh (aknysh) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@aknysh
Andriy Knysh (aknysh) merged commit cee5479 into cloudposse:main May 23, 2026
62 of 65 checks passed
@atmos-pro

atmos-pro Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

Note

Atmos Pro  

Waiting for your GitHub Actions workflow to upload affected stacks.
Learn More.

Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request May 23, 2026
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]>
Andriy Knysh (aknysh) added a commit that referenced this pull request May 25, 2026
…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]>
@github-actions

Copy link
Copy Markdown

These changes were released in v1.220.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/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants