Skip to content

Fix terraform backend subcommands not recognizing --stack - #2508

Merged
Andriy Knysh (aknysh) merged 12 commits into
mainfrom
copilot/fix-atmos-terraform-backend-subcommands
Jul 15, 2026
Merged

Andriy Knysh (aknysh) merged 12 commits into
mainfrom
copilot/fix-atmos-terraform-backend-subcommands

Conversation

Copilot AI commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

atmos terraform backend subcommands were rejecting invocations with --stack as “required flag not provided,” even when the flag was explicitly passed. This occurred because backend command parsing relied on parsed positional args/Viper state that did not consistently reflect subcommand CLI flag values.

  • Root cause and behavior correction

    • Backend subcommands now resolve effective flag values from the command’s changed Cobra flags (local/inherited) before fallback sources.
    • This prevents --stack (and related flags) from being dropped during backend subcommand execution.
  • Backend command updates

    • Updated create, update, delete, describe, and list RunE handlers to:
      • bind flags to Viper at execution time, and
      • use effective resolved values for downstream backend operations.
  • Shared flag-resolution helper

    • Added cmd/terraform/backend/flag_values.go with reusable helpers to read changed string/bool flags from local/inherited command flags, enabling consistent behavior across backend subcommands.
  • Regression coverage

    • Added a focused backend command regression test ensuring subcommands no longer fail with missing-stack errors when --stack is provided and that the resolved value flows into backend config initialization.
stack := getCommandFlagString(cmd, "stack")
if stack == "" {
    stack = v.GetString("stack")
}

Summary by CodeRabbit

  • New Features
    • Added configurable --error-mode handling for list and describe commands, supporting strict, warn, and silent.
    • Recoverable backend resolution errors can now continue processing and display (computed) values with optional summaries.
    • Added a backend provisioning example demonstrating Terraform backend create, update, and delete workflows using a local emulator.
  • Bug Fixes
    • Improved command-line flag precedence over configuration and environment settings.
  • Documentation
    • Added guidance, examples, and interactive demonstrations for graceful degradation and backend provisioning.

@atmos-pro

atmos-pro Bot commented May 24, 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.

Copilot AI linked an issue May 24, 2026 that may be closed by this pull request
@mergify mergify Bot added triage Needs triage wip Work in Progress: Not ready for final review or merge labels May 24, 2026
Copilot AI changed the title [WIP] Fix atmos terraform backend sub-commands not recognizing --stack flag Fix terraform backend subcommands not recognizing --stack May 24, 2026
@mergify mergify Bot removed the wip Work in Progress: Not ready for final review or merge label May 24, 2026
@github-actions github-actions Bot added the size/m Medium size PR label May 24, 2026
@osterman Erik Osterman (Cloud Posse) (osterman) added the patch A minor, backward compatible change label May 24, 2026
@github-actions

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@osterman

Copy link
Copy Markdown
Member

CodeRabbit (@coderabbitai) this does not appear like correct flag handling using our flag handler. Especially for identity. Can you confirm?

@coderabbitai

coderabbitai Bot commented May 24, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Let me examine the existing flag handling patterns and the new code in this PR.


🏁 Script executed:

#!/bin/bash
# Find the new flag_values.go file
fd "flag_values.go" --type f
echo "---"
# Find existing flag handler utilities
fd "flag" --type f | grep -i "flag" | head -30
echo "---"
# Look for identity flag handling patterns
rg -n "identity" --type go -C2 | grep -i "flag\|viper\|GetString\|stack" | head -40
echo "---"
# Look for existing flag resolution/handler utilities
rg -n "getCommandFlag\|GetChangedFlags\|resolveFlag\|flagValue" --type go -C3 | head -60

Length of output: 5257


🏁 Script executed:

#!/bin/bash
# Read the new flag_values.go
echo "=== cmd/terraform/backend/flag_values.go ==="
cat cmd/terraform/backend/flag_values.go

echo ""
echo "=== cmd/cmd_flag_utils.go ==="
cat cmd/cmd_flag_utils.go

echo ""
echo "=== cmd/flag_utils.go (first 100 lines) ==="
head -100 cmd/flag_utils.go

echo ""
echo "=== cmd/terraform/flags.go ==="
cat cmd/terraform/flags.go

echo ""
# Look for identity flag handling in the backend commands
echo "=== identity flag in backend ==="
rg -n "identity" cmd/terraform/backend/ --type go -C3

echo ""
# Look at the backend command files
echo "=== backend command files ==="
fd . cmd/terraform/backend/ --type f

Length of output: 63477


🏁 Script executed:

#!/bin/bash
# Look at the pkg/flags package to understand the StandardParser and identity handling
echo "=== pkg/flags directory ==="
fd . pkg/flags/ --type f | head -20

echo ""
echo "=== pkg/flags - identity handling ==="
rg -n "identity\|Identity\|IdentityFlag" pkg/flags/ --type go -C3 | head -60

echo ""
# How does identity get handled in other terraform commands (non-backend)?
echo "=== identity handling in other terraform commands ==="
rg -n "identity\|Identity" cmd/terraform/ --type go -l

echo ""
# Look at how StandardParser handles identity
echo "=== StandardParser identity ==="
rg -n "identity\|IdentityFlag\|ParseIdentity\|GetIdentity" pkg/ --type go -C3 | head -80

echo ""
# Look at how cmd_flag_utils is used for identity in other commands
echo "=== identity in other describe/terraform commands ==="
rg -n "identity" cmd/terraform/compat_flags.go cmd/terraform/flags.go -C3 2>/dev/null | head -40

echo ""
# Look at how the parser result handles identity vs what getCommandFlagString does
echo "=== result.Identity usage ==="
rg -n "result\.Identity\|\.Identity\.Value\(\)" --type go -C3 | head -40

echo ""
# Check if there's a special identity flag type (NoOptDefVal for interactive select)
echo "=== identity NoOptDefVal ==="
rg -n "NoOptDefVal\|IdentityFlagSelectValue\|IdentityFlagName" --type go -C3 | head -60

Length of output: 1747


🏁 Script executed:

#!/bin/bash
echo "=== pkg/flags/global/identity_selector.go ==="
cat pkg/flags/global/identity_selector.go

echo ""
echo "=== pkg/flags/global/flags.go ==="
cat pkg/flags/global/flags.go

echo ""
echo "=== pkg/flags/flag_parser.go (identity section) ==="
cat pkg/flags/flag_parser.go

echo ""
# How do non-backend terraform commands resolve identity?
echo "=== GetIdentityFromFlags or similar usage ==="
rg -n "GetIdentity\|ParseGlobalFlags\|IdentityFrom\|identity.*flag\|flag.*identity" --type go -C4 | head -80

echo ""
echo "=== pkg/config IdentityFlagName etc ==="
rg -n "IdentityFlagName\|IdentityFlagShortName\|IdentityFlagSelectValue" --type go -C2 | head -40

Length of output: 20237


🏁 Script executed:

#!/bin/bash
# Find ParseGlobalFlags
echo "=== ParseGlobalFlags implementation ==="
rg -n "func ParseGlobalFlags" --type go -C2 | head -20
echo ""
ast-grep --pattern 'func ParseGlobalFlags($$$) {
  $$$
}'

echo ""
echo "=== ParseGlobalFlags usage in pkg/flags ==="
rg -n "ParseGlobalFlags\|parseIdentityFlag\|GetIdentityFromFlag\|IdentitySelector" --type go -C3 | head -80

echo ""
# How does StandardParser handle identity?
echo "=== StandardParser implementation ==="
fd "standard_parser\|StandardParser" --type f
rg -n "StandardParser\|NewStandardParser" --type go -C3 | head -40

echo ""
# Check how auth.CreateAndAuthenticateManager handles the identity string vs IdentitySelector
echo "=== auth.CreateAndAuthenticateManager ==="
rg -n "CreateAndAuthenticateManager\|func.*CreateAnd" --type go -C5 | head -60

echo ""
# Check pkg/flags/options.go for how identity is parsed in StandardParser
echo "=== pkg/flags/options.go ==="
cat pkg/flags/options.go

Length of output: 13804


🏁 Script executed:

#!/bin/bash
echo "=== ParseGlobalFlags full implementation ==="
cat pkg/flags/global_registry.go

echo ""
echo "=== StandardParser Parse method and identity handling ==="
rg -n "func.*StandardParser\|func.*Parse\b" pkg/flags/ --type go -C3 | head -40

echo ""
# Look at how the backend commands register identity flag (via StandardParser)
echo "=== backend StandardParser identity registration ==="
rg -n "WithIdentityFlag\|StandardParser\|NewStandardParser\|identityFlag\|IdentityFlag" cmd/terraform/backend/ --type go -C3

echo ""
# Look at what result.Identity is in StandardParser - how it gets populated
echo "=== StandardParser result struct ==="
rg -n "type.*Result\|ParseResult\|Identity.*IdentitySelector\|struct.*Result" pkg/flags/ --type go -C5 | head -60

echo ""
# How does ParseGlobalFlags create IdentitySelector?
echo "=== global_registry identity parsing ==="
cat pkg/flags/global_registry.go | grep -A 30 "identity\|Identity" | head -80

Length of output: 16268


🏁 Script executed:

#!/bin/bash
echo "=== auth.CreateAndAuthenticateManager signature ==="
rg -n "func CreateAndAuthenticateManager" --type go -C10 | head -40

echo ""
echo "=== How backend_helpers.go uses ParseGlobalFlags ==="
grep -n "ParseGlobalFlags\|parseIdentity\|Identity\|IdentitySelector" cmd/terraform/backend/backend_helpers.go

echo ""
echo "=== StandardParser.Parse return type and result.Identity field ==="
rg -n "type StandardParser\|func.*StandardParser.*Parse\|ParseResult\|Result struct\|Identity.*IdentitySelector\|\.Identity " pkg/flags/ --type go -C5 | head -80

echo ""
# Check the interactive.go for StandardParser
echo "=== pkg/flags/interactive.go ==="
cat pkg/flags/interactive.go | head -120

Length of output: 7629


@osterman Confirmed — the identity flag handling in this PR is incorrect in multiple ways. The established path is parseIdentityFlag (called via flags.ParseGlobalFlags) and the new getCommandFlagString bypasses it. Here are the specific gaps:


1. Missing normalizeIdentityValue

parseIdentityFlag in pkg/flags/global_registry.go normalizes falsy strings ("false", "0", "no", "off") → cfg.IdentityFlagDisabledValue ("__DISABLED__"):

// pkg/flags/global_registry.go
if changed {
    value := flag.Value.String()
    return global.NewIdentitySelector(normalizeIdentityValue(value), true)
}

getCommandFlagString returns the raw Cobra string with no normalization — so --identity=false would pass "false" (not "__DISABLED__") into auth.CreateAndAuthenticateManager, breaking the disable-auth flow entirely.


2. Incomplete parent-chain traversal

lookupCommandFlag walks cmd.Flags(), cmd.InheritedFlags(), cmd.PersistentFlags(), and then climbs all parent commands' PersistentFlags(). getCommandFlagString only checks cmd.Flags() + cmd.InheritedFlags() — so flags registered on grandparent persistent flag sets are silently dropped.


3. ParseCommonFlags discards the ParseGlobalFlags result for identity

backend_helpers.go line 142 already calls flags.ParseGlobalFlags(cmd, v) (which correctly invokes parseIdentityFlag), but then line 144 throws the result away:

// backend_helpers.go
opts := &CommonOptions{
    Flags:    flags.ParseGlobalFlags(cmd, v),  // ← correctly resolves identity here
    Stack:    v.GetString("stack"),
    Identity: v.GetString("identity"),          // ← but then ignores it and reads Viper raw
}

v.GetString("identity") cannot distinguish "explicitly set to empty string" from "not set at all" — exactly the distinction IdentitySelector.IsProvided() / IsEmpty() / IsDisabled() / IsInteractiveSelector() is designed to carry.


4. Triple-fallback is fragile

The per-command pattern:

identity := getCommandFlagString(cmd, "identity")   // raw cobra
if identity == "" { identity = v.GetString("identity") }  // raw viper
// ... parse ...
if identity == "" { identity = result.Identity.Value() }  // StandardParser

…means that if ATMOS_IDENTITY is set in the environment, it wins over the explicitly-parsed result.Identity — and the interactive-select sentinel "__SELECT__" can leak through result.Identity.Value() into the raw-string path with no downstream handler for it.


What the fix should look like

ParseCommonFlags should source identity from the ParseGlobalFlags result it already computes, not from Viper directly:

func ParseCommonFlags(cmd *cobra.Command, parser *flags.StandardParser) (*CommonOptions, error) {
    v := viper.GetViper()
    if err := parser.BindFlagsToViper(cmd, v); err != nil {
        return nil, err
    }

    globalFlags := flags.ParseGlobalFlags(cmd, v) // already calls parseIdentityFlag
    opts := &CommonOptions{
        Flags:    globalFlags,
        Stack:    v.GetString("stack"),
        Identity: globalFlags.Identity.Value(), // normalized, parent-chain-aware
    }
    ...
}

And the per-command getCommandFlagString(cmd, "identity") pre-reads in backend_create.go, backend_update.go, etc. should be removed in favour of relying on result.Identity (from the StandardParser, which goes through the full pipeline) as the primary source, with flags.ParseGlobalFlags(cmd, v).Identity as the fallback.

@codecov

codecov Bot commented May 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.60322% with 91 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.89%. Comparing base (85a5194) to head (ed2e3d9).

Files with missing lines Patch % Lines
pkg/list/list_affected.go 0.00% 21 Missing ⚠️
internal/exec/describe_affected.go 56.25% 5 Missing and 2 partials ⚠️
internal/exec/describe_affected_helpers.go 66.66% 7 Missing ⚠️
cmd/list/components.go 64.70% 5 Missing and 1 partial ⚠️
cmd/list/settings.go 72.22% 5 Missing ⚠️
cmd/describe_affected.go 33.33% 2 Missing and 2 partials ⚠️
cmd/describe_dependents.go 75.00% 2 Missing and 2 partials ⚠️
cmd/describe_error_mode_flag.go 78.94% 2 Missing and 2 partials ⚠️
cmd/describe_stacks.go 75.00% 2 Missing and 2 partials ⚠️
cmd/terraform/backend/backend_create.go 60.00% 2 Missing and 2 partials ⚠️
... and 8 more

❌ Your patch check has failed because the patch coverage (75.60%) is below the target coverage (85.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2508      +/-   ##
==========================================
+ Coverage   81.85%   81.89%   +0.04%     
==========================================
  Files        1715     1719       +4     
  Lines      161896   162175     +279     
==========================================
+ Hits       132521   132818     +297     
+ Misses      22139    22097      -42     
- Partials     7236     7260      +24     
Flag Coverage Δ
unittests 81.89% <75.60%> (+0.04%) ⬆️

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

Files with missing lines Coverage Δ
cmd/list/error_mode.go 100.00% <100.00%> (ø)
cmd/list/flag_wrappers.go 100.00% <100.00%> (ø)
cmd/list/stacks.go 74.03% <100.00%> (+0.90%) ⬆️
cmd/terraform/backend/backend_helpers.go 78.41% <100.00%> (+27.79%) ⬆️
errors/errors.go 100.00% <ø> (ø)
internal/exec/describe_affected_utils.go 77.77% <100.00%> (+0.26%) ⬆️
internal/exec/describe_affected_utils_2.go 79.62% <100.00%> (+0.04%) ⬆️
...ternal/exec/describe_stacks_component_processor.go 95.59% <100.00%> (+0.13%) ⬆️
internal/exec/yaml_func_utils.go 80.78% <100.00%> (+1.54%) ⬆️
pkg/degradation/degradation.go 100.00% <100.00%> (ø)
... and 21 more

... and 9 files with indirect coverage changes

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

Copilot AI and others added 3 commits July 13, 2026 00:56
…ul degradation

- Continue the terraform backend subcommand stack-flag fix: tighten flag_values
  parsing/validation and simplify backend_create/delete/describe/list/update and
  their tests around the new flag handling.
- Add `--on-error=warn` for `list stacks/components/settings` so a recoverable
  !terraform.state/!terraform.output failure (unprovisioned backend) degrades to
  null with a warning instead of aborting the whole listing; default `strict`
  behavior is unchanged. See docs/fixes/2026-07-13-list-on-error-graceful-degradation.md.
- Add a backend-provisioning example/demo cast illustrating the new behavior.
@osterman
Erik Osterman (Cloud Posse) (osterman) force-pushed the copilot/fix-atmos-terraform-backend-subcommands branch from 55f180c to f074dea Compare July 13, 2026 13:15
@mergify

mergify Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Important

Cloud Posse Engineering Team Review Required

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

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

@mergify mergify Bot added the needs-cloudposse Needs Cloud Posse assistance label Jul 13, 2026
@osterman
Erik Osterman (Cloud Posse) (osterman) marked this pull request as ready for review July 13, 2026 13:16
@github-actions github-actions Bot added size/xl Extra large size PR and removed size/m Medium size PR labels Jul 13, 2026
@mergify

mergify Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it @Copilot? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Jul 14, 2026
…raform-backend-subcommands

# Conflicts:
#	cmd/list/components.go
@mergify

mergify Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it @Copilot? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Jul 14, 2026
…raform-backend-subcommands

# Conflicts:
#	pkg/git/git.go

Copy link
Copy Markdown
Member

CodeRabbit (@coderabbitai) review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

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 commented Jul 15, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The change adds configurable graceful degradation for list and describe commands, propagates error-mode options through affected/dependent resolution, fixes backend CLI/Viper precedence, and adds a validated backend-provisioning example with CI coverage, documentation, and recordings.

Changes

Graceful degradation

Layer / File(s) Summary
Degradation contracts and YAML processing
internal/exec/..., pkg/degradation/..., pkg/schema/..., pkg/list/...
Recoverable Terraform state errors can render as (computed), collect warnings, and continue under warn or silent; strict behavior remains available.
Describe command error-mode wiring
cmd/describe_*.go, cmd/describe_error_mode_flag.go, cmd/describe_*_test.go
Describe commands accept, resolve, validate, and test --error-mode, environment, and configuration values.
List command integration
cmd/list/..., pkg/list/list_affected.go
List commands pass error options into stack processing and print summaries according to the selected mode.
Affected and dependent resolution
internal/exec/describe_affected*.go, internal/exec/describe_dependents.go
Error options flow through repository, clone, checkout, base-stack, and dependent-resolution paths.
Backend command flag precedence
cmd/terraform/backend/...
Backend commands prefer explicitly changed CLI flags over Viper values and use stack-aware authentication initialization.
Backend-provisioning example and validation
examples/backend-provisioning/..., demo/casts/..., .github/workflows/test.yml, website/...
Adds emulator-backed Terraform backend lifecycle configuration, cast generation and validation, CI matrices, documentation, and a terminal recording.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant ListDescribeCommand
  participant DescribeStacks
  participant YAMLResolver
  participant Collector
  CLI->>ListDescribeCommand: provide error-mode
  ListDescribeCommand->>DescribeStacks: resolve options and execute
  DescribeStacks->>YAMLResolver: resolve YAML functions
  YAMLResolver->>Collector: record recoverable warning
  YAMLResolver-->>DescribeStacks: return computed value
  DescribeStacks-->>ListDescribeCommand: render output
  ListDescribeCommand->>Collector: print warn summary
Loading

Possibly related PRs

  • cloudposse/atmos#2731 — Extends the root configuration schema with related list and describe error_mode support.

Suggested reviewers: osterman

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.40% 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 matches the primary backend CLI fix: subcommands now resolve explicit --stack values correctly.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch copilot/fix-atmos-terraform-backend-subcommands

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.

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

🧹 Nitpick comments (3)
examples/backend-provisioning/components/terraform/bucket/variables.tf (1)

1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Specify the variable type.

It is good practice to explicitly define the type for Terraform variables to ensure proper validation and clarity, even in examples.

💡 Proposed fix
 variable "stage" {
+  type        = string
   description = "The stage of the environment (e.g. dev, staging, prod)"
 }
🤖 Prompt for 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.

In `@examples/backend-provisioning/components/terraform/bucket/variables.tf`
around lines 1 - 3, Update the Terraform variable declaration for "stage" to
explicitly specify its type as a string, preserving the existing description.
cmd/terraform/backend/flag_values_test.go (1)

11-83: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Convert to table-driven tests.

The tests look good and properly isolate standard Cobra flag evaluation behavior. However, to fully align with the repository guidelines, consider refactoring these sequential t.Run blocks into a single slice of structs (table-driven design).

It's completely fine if you prefer to keep this as-is for these simple structural tests, but a table-driven approach scales better if more edge cases are added later.

🤖 Prompt for 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.

In `@cmd/terraform/backend/flag_values_test.go` around lines 11 - 83, Refactor
TestGetCommandFlagString and TestGetCommandFlagBool into table-driven tests
using slices of case structs, with each case retaining its command setup,
expected value, and changed state. Execute cases through a loop with t.Run,
preserving the existing local, inherited, unchanged, and missing-flag coverage
and assertions.

Source: Coding guidelines

cmd/list/settings.go (1)

73-77: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Avoid printing an extra newline on empty output.

If listSettingsWithOptions encounters a NoValuesFoundError, it returns an empty string for output. Passing this empty string to data.Writeln(output) below will print an unwanted extra newline to stdout, diverging from the previous behavior where data.Writeln was skipped entirely on empty results.

🛠️ Proposed fix
 		if err != nil {
 			return err
 		}
 		defer printErrorModeSummary(opts.ErrorMode, collector)
 
-		return data.Writeln(output)
+		if output != "" {
+			return data.Writeln(output)
+		}
+		return nil
 	},
🤖 Prompt for 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.

In `@cmd/list/settings.go` around lines 73 - 77, Guard the output-writing call
after listSettingsWithOptions so data.Writeln is invoked only when output is
non-empty. Preserve the existing error return and printErrorModeSummary
behavior, while keeping empty NoValuesFoundError results from emitting a
newline.
🤖 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/list/error_mode_test.go`:
- Around line 53-75: Strengthen TestPrintErrorModeSummary by injecting or
capturing the UI output writer, then assert that printErrorModeSummary emits the
expected warning summary for "warn" and emits no output for "silent" even when
warnings exist. Keep the strict nil-collector case, but ensure the warn and
silent subtests validate observable output rather than only absence of panics.

In `@cmd/list/settings.go`:
- Around line 176-181: Update the NoValuesFoundError handling in the surrounding
settings retrieval function to return the existing collector alongside the empty
output and nil error, rather than discarding it. Preserve the current error
return behavior for other errors and the normal output, collector, nil result
path.

In `@cmd/terraform/backend/backend_create.go`:
- Around line 40-43: The backend commands bypass normalized identity parsing by
directly reading the raw flag. In
cmd/terraform/backend/backend_create.go#L40-L43, use the normalized identity
returned by flags.ParseGlobalFlags(cmd, v); in
cmd/terraform/backend/backend_delete.go#L44-L47,
cmd/terraform/backend/backend_describe.go#L44-L47, and
cmd/terraform/backend/backend_update.go#L43-L46, remove the direct identity
pre-read so all commands preserve IdentitySelector normalization and parent
persistent flags.

In `@cmd/terraform/backend/backend_helpers_test.go`:
- Around line 75-89: The test
TestInitConfigAndAuth_FailsWhenAuthConfiguredButIdentityMissing must cover a
missing identity within configured authentication. Update its fixture or setup
to define auth with at least one identity, then pass a different nonexistent
identity and assert the intended identity-resolution error; otherwise rename the
test to reflect the ErrAuthNotConfigured scenario it currently exercises.

In `@cmd/terraform/backend/backend_list.go`:
- Around line 27-45: Update the backend list command to retain and consume the
ParsedConfig returned by listParser.Parse instead of rebuilding stack, identity,
and format through getCommandFlagString and Viper. Use the resolved values from
ParsedConfig so prompted values, parser precedence, and IdentitySelector
normalization are preserved, while continuing to process command-specific flags
through flags.NewStandardParser().

In `@cmd/terraform/backend/flag_values.go`:
- Around line 9-38: Update the identity flag handling in the relevant caller of
getCommandFlagString so it uses the parsed result.Flags.Identity (or parsed
global flags) rather than reading cmd.Flags() directly. Preserve normalized
boolean parsing so values such as false, 0, no, and off disable authentication
instead of being treated as literal identity values.

In `@demo/casts/atmos.d/examples/backend-provisioning/lifecycle.yaml`:
- Around line 84-89: Update the two re.sub regexes in the lifecycle sanitization
step to use correctly escaped raw-string patterns: match the literal registry
dots with \. and the tab delimiters with \t, so both the digest and runtime
container value are replaced in the generated cast.

In `@internal/exec/describe_stacks_test.go`:
- Around line 354-389: Strengthen the PrintErrorModeSummary tests to assert
observable output and warning metadata, not just panic safety or collection
length. Capture the relevant UI/stderr output for warn, silent, and strict
modes, verify the expected DegradationWarning fields and slice contents, and
update strict-mode assertions to require.ErrorIs(err,
errUtils.ErrTerraformStateNotProvisioned) while preserving no-output behavior
where required.

In `@internal/exec/describe_stacks.go`:
- Around line 214-220: Make warn-mode summary printing nil-safe by requiring a
non-nil collector before calling Summary() in exec.PrintErrorModeSummary; update
internal/exec/describe_stacks.go lines 214-220 accordingly. Also update
cmd/list/error_mode.go lines 34-39 to delegate to exec.PrintErrorModeSummary or
apply the same collector guard, preserving summary output when a collector
exists.
- Around line 18-20: Move the sentinel definition for ErrInvalidErrorMode from
the exec package into the shared errors/errors.go catalog, then expose the
exec-level ErrInvalidErrorMode as an alias to that shared sentinel to preserve
existing callers. Update references as needed so all paths compare against the
same error value.

In `@internal/exec/yaml_func_utils.go`:
- Around line 55-77: The lenient path must remain active when onWarning is nil;
normalize nil to a no-op callback before processNodesWithContext in
ProcessCustomYamlTagsLenient, while preserving silent degradation. Add a
regression case in internal/exec/yaml_func_utils_lenient_test.go:46-89 verifying
that a recoverable error with a nil callback yields
degradation.AtmosComputedValue{} and does not fail processing.

In `@website/docs/cli/commands/list/list-stacks.mdx`:
- Around line 125-128: Update the list-stacks documentation for the
error-handling option to use the implemented flag name --error-mode and
environment variable ATMOS_LIST_ERROR_MODE instead of --on-error and
ATMOS_LIST_ON_ERROR, while preserving the existing strict and warn behavior
descriptions.

---

Nitpick comments:
In `@cmd/list/settings.go`:
- Around line 73-77: Guard the output-writing call after listSettingsWithOptions
so data.Writeln is invoked only when output is non-empty. Preserve the existing
error return and printErrorModeSummary behavior, while keeping empty
NoValuesFoundError results from emitting a newline.

In `@cmd/terraform/backend/flag_values_test.go`:
- Around line 11-83: Refactor TestGetCommandFlagString and
TestGetCommandFlagBool into table-driven tests using slices of case structs,
with each case retaining its command setup, expected value, and changed state.
Execute cases through a loop with t.Run, preserving the existing local,
inherited, unchanged, and missing-flag coverage and assertions.

In `@examples/backend-provisioning/components/terraform/bucket/variables.tf`:
- Around line 1-3: Update the Terraform variable declaration for "stage" to
explicitly specify its type as a string, preserving the existing description.
🪄 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: 2d321d4b-cba1-476d-83ae-7c9034b7008b

📥 Commits

Reviewing files that changed from the base of the PR and between 1c00575 and 5a663c5.

📒 Files selected for processing (76)
  • .github/workflows/test.yml
  • cmd/describe_affected.go
  • cmd/describe_affected_test.go
  • cmd/describe_dependents.go
  • cmd/describe_dependents_test.go
  • cmd/describe_error_mode_flag.go
  • cmd/describe_error_mode_flag_test.go
  • cmd/describe_stacks.go
  • cmd/describe_stacks_test.go
  • cmd/list/affected.go
  • cmd/list/components.go
  • cmd/list/error_mode.go
  • cmd/list/error_mode_test.go
  • cmd/list/flag_wrappers.go
  • cmd/list/parse_options_test.go
  • cmd/list/settings.go
  • cmd/list/stacks.go
  • cmd/terraform/backend/backend_commands_test.go
  • cmd/terraform/backend/backend_create.go
  • cmd/terraform/backend/backend_delete.go
  • cmd/terraform/backend/backend_describe.go
  • cmd/terraform/backend/backend_helpers.go
  • cmd/terraform/backend/backend_helpers_test.go
  • cmd/terraform/backend/backend_list.go
  • cmd/terraform/backend/backend_update.go
  • cmd/terraform/backend/flag_values.go
  • cmd/terraform/backend/flag_values_test.go
  • demo/casts/atmos.d/examples/backend-provisioning/lifecycle.yaml
  • demo/casts/atmos.yaml
  • docs/fixes/2026-07-13-list-on-error-graceful-degradation.md
  • examples/README.md
  • examples/backend-provisioning/.gitignore
  • examples/backend-provisioning/README.md
  • examples/backend-provisioning/atmos.yaml
  • examples/backend-provisioning/components/terraform/bucket/.terraform.lock.hcl
  • examples/backend-provisioning/components/terraform/bucket/main.tf
  • examples/backend-provisioning/components/terraform/bucket/outputs.tf
  • examples/backend-provisioning/components/terraform/bucket/variables.tf
  • examples/backend-provisioning/components/terraform/bucket/versions.tf
  • examples/backend-provisioning/schemas/atmos-manifest.json
  • examples/backend-provisioning/stacks/catalog/demo.yaml
  • examples/backend-provisioning/stacks/catalog/emulator/aws.yaml
  • examples/backend-provisioning/stacks/deploy/dev/demo.yaml
  • examples/backend-provisioning/stacks/deploy/prod/demo.yaml
  • examples/backend-provisioning/stacks/deploy/staging/demo.yaml
  • internal/exec/describe_affected.go
  • internal/exec/describe_affected_authdisabled_test.go
  • internal/exec/describe_affected_helpers.go
  • internal/exec/describe_affected_test.go
  • internal/exec/describe_affected_utils.go
  • internal/exec/describe_affected_utils_2.go
  • internal/exec/describe_affected_utils_test.go
  • internal/exec/describe_dependents.go
  • internal/exec/describe_stacks.go
  • internal/exec/describe_stacks_component_processor.go
  • internal/exec/describe_stacks_component_processor_test.go
  • internal/exec/describe_stacks_test.go
  • internal/exec/yaml_func_utils.go
  • internal/exec/yaml_func_utils_context_test.go
  • internal/exec/yaml_func_utils_lenient_test.go
  • pkg/datafetcher/schema/config/global/1.0.json
  • pkg/degradation/degradation.go
  • pkg/degradation/degradation_test.go
  • pkg/flags/standard.go
  • pkg/flags/standard_test.go
  • pkg/list/column/column_test.go
  • pkg/list/format/table.go
  • pkg/list/format/table_test.go
  • pkg/list/list_affected.go
  • pkg/schema/schema.go
  • website/blog/2025-11-20-automatic-backend-provisioning.mdx
  • website/blog/2026-07-13-list-describe-graceful-degradation.mdx
  • website/docs/cli/commands/list/list-components.mdx
  • website/docs/cli/commands/list/list-settings.mdx
  • website/docs/cli/commands/list/list-stacks.mdx
  • website/static/casts/examples/backend-provisioning/lifecycle.cast

Comment thread cmd/list/error_mode_test.go Resolved
Comment thread cmd/list/settings.go Resolved
Comment thread cmd/terraform/backend/backend_create.go Resolved
Comment thread cmd/terraform/backend/backend_list.go Resolved
Comment thread internal/exec/describe_stacks_test.go Resolved
Comment thread internal/exec/describe_stacks.go Resolved
Comment thread internal/exec/describe_stacks.go Resolved
Comment thread internal/exec/yaml_func_utils.go Resolved
@aknysh
Andriy Knysh (aknysh) merged commit af5d3a7 into main Jul 15, 2026
87 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the copilot/fix-atmos-terraform-backend-subcommands branch July 15, 2026 12:58
@atmos-pro

atmos-pro Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label Jul 15, 2026
@github-actions

Copy link
Copy Markdown

These changes were released in v1.223.0.

This branch was successfully deployed

1 active deployment
preview — ed2e3d9e Deployed Jul 15, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

atmos terraform backend sub-commands do not work.

3 participants