Skip to content

Support !terraform.state on GCS Backends - #1393

Merged
Andriy Knysh (aknysh) merged 17 commits into
cloudposse:mainfrom
shirkevich:terraform-state-gcs
Oct 28, 2025
Merged

Andriy Knysh (aknysh) merged 17 commits into
cloudposse:mainfrom
shirkevich:terraform-state-gcs

Conversation

@shirkevich

@shirkevich Mikhail Shirkov (shirkevich) commented Aug 6, 2025 •

Copy link
Copy Markdown
Collaborator

Add GCS backend support to !terraform.state YAML function

what

  • Add Google Cloud Storage (GCS) backend support to !terraform.state Atmos YAML function
  • Implement performance optimizations (client caching, retry logic, extended timeouts)
  • Create unified Google Cloud authentication system for consistency across GCP services
  • Update documentation with GCS backend usage examples and authentication methods

why

The !terraform.state YAML function allows reading the outputs (remote state) of components in Atmos stack manifests directly from the configured Terraform/OpenTofu backends.

Previously, the !terraform.state YAML function only supported:

  • local (Terraform and OpenTofu)
  • s3 (Terraform and OpenTofu)

This PR adds support for:

  • gcs (Google Cloud Storage - Terraform and OpenTofu)

With GCS backend support, users can now leverage the high-performance !terraform.state function instead of the slower !terraform.output or !store functions when using Google Cloud Storage for Terraform state storage.

Implementation Details

GCS Backend Features

  • Full Authentication Support: JSON credentials, service account file paths, and Google Application Default Credentials (ADC)
  • Service Account Impersonation: Support for impersonate_service_account configuration
  • Performance Optimizations:
    • Client caching to avoid recreating GCS clients for repeated operations
    • Retry logic with exponential backoff (up to 3 attempts) for transient failures
    • Extended timeouts (30 seconds) to match S3 backend performance
  • Robust Error Handling: Graceful handling of missing state files and detailed error context
  • Resource Management: Proper cleanup and explicit resource management

Usage

The GCS backend works seamlessly with existing !terraform.state syntax:

# Get the `output` of the `component` in the current stack
subnet_id: !terraform.state vpc private_subnet_id

# Get the `output` of the `component` in the provided `stack` 
vpc_id: !terraform.state vpc dev-us-east-1 vpc_id

# Get complex outputs using YQ expressions
first_subnet: !terraform.state vpc .private_subnet_ids[0]

GCS Backend Configuration

The GCS backend supports all standard Terraform GCS backend configurations:

# atmos.yaml
components:
  terraform:
    backend_type: gcs
    backend:
      gcs:
        bucket: "my-terraform-state-bucket"
        prefix: "terraform/state"
        
        # Authentication options (choose one):
        
        # Option 1: JSON credentials content
        credentials: |
          {
            "type": "service_account",
            "project_id": "my-project",
            ...
          }
          
        # Option 2: Service account file path  
        credentials: "/path/to/service-account.json"
        
        # Option 3: Use Application Default Credentials (ADC)
        # (no credentials field needed - uses environment/metadata)
        
        # Optional: Service account impersonation
        impersonate_service_account: "[email protected]"

Performance Benefits

Compared to !terraform.output, the !terraform.state function with GCS backend:

  • ✅ No Terraform execution - Reads state directly from GCS
  • ✅ No provider initialization - Skips all module and provider setup
  • ✅ No varfile generation - Bypasses Terraform configuration preparation
  • ✅ Cached clients - Reuses GCS clients for multiple operations
  • ✅ Parallel execution - Multiple state reads can happen concurrently

Testing

  • Comprehensive Test Suite: 100% test coverage for all new functionality
  • Mock Implementations: Complete interface-based testing for GCS operations
  • Authentication Testing: Validates all credential types and authentication flows
  • Error Scenario Coverage: Tests for missing files, network failures, and invalid configurations
  • Caching Validation: Ensures client caching works correctly across operations
  • Retry Logic Testing: Validates exponential backoff and failure recovery

Backward Compatibility

  • ✅ No breaking changes to existing configurations
  • ✅ Existing backends (local, s3) remain unchanged
  • ✅ Same function syntax - no new parameters or options required
  • ✅ Graceful fallbacks - continues to work with !terraform.output and !store functions

Files Changed

Core Implementation

  • internal/terraform_backend/terraform_backend_gcs.go - GCS backend implementation
  • internal/terraform_backend/terraform_backend_gcs_test.go - Comprehensive test suite
  • internal/terraform_backend/terraform_backend_registry.go - Register GCS backend
  • internal/terraform_backend/terraform_backend_utils.go - Updated error messages

Unified Authentication System

  • internal/gcp/auth.go - New unified Google Cloud authentication (created)
  • internal/gcp/auth_test.go - Authentication tests (created)
  • pkg/store/google_secret_manager_store.go - Updated to use unified auth
  • internal/gcp_utils/gcp_utils.go - Removed (replaced by unified auth)

Configuration & Documentation

  • internal/exec/terraform_generate_backend.go - GCS backend validation
  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx - Updated documentation
  • errors/errors.go - Added GCS-specific error types
  • go.mod - Added GCS storage dependency

Migration Guide

For users currently using !terraform.output or !store with GCS-stored state:

Before (slower)

# Using !terraform.output (requires Terraform execution)
vpc_id: !terraform.output vpc dev-us-east-1 vpc_id

# Using !store (requires separate state management)  
vpc_id: !store google-secret-manager dev/vpc/vpc_id

After (faster)

# Using !terraform.state (direct GCS state access)
vpc_id: !terraform.state vpc dev-us-east-1 vpc_id

Simply update your backend configuration to use gcs and replace function calls - no other changes needed!

Summary by CodeRabbit

  • New Features

    • GCS-backed Terraform state support and unified Google Cloud authentication integration.
  • Bug Fixes

    • Stricter backend config validation with clearer error responses and updated supported-backends messaging.
  • Tests

    • Comprehensive unit tests added for GCS backend behavior and GCP authentication handling.

…Google Cloud auth

Performance Improvements:
- Add client caching to avoid recreating GCS clients for repeated operations
- Implement retry logic with exponential backoff (up to 3 attempts)
- Extend timeouts to 30 seconds to match S3 backend performance
- Add comprehensive debug logging for better troubleshooting

Unified Google Cloud Authentication:
- Create internal/gcp package for unified authentication across all GCP services
- Support both JSON credentials and file paths consistently
- Leverage Google's Application Default Credentials (ADC) automatically
- Unify authentication between GCS backend and Secret Manager store
- Remove duplicate authentication logic and improve maintainability

Enhanced Error Handling:
- Improve resource cleanup (explicit close instead of defer in loops)
- Add detailed error context and logging
- Better handling of transient failures and missing files

Test Coverage:
- Add comprehensive test suite for unified authentication (4 test functions)
- Enhance GCS backend tests with retry and caching scenarios
- Maintain 100% backward compatibility with existing configurations

This brings GCS backend performance and reliability in line with S3 backend
while establishing a foundation for consistent Google Cloud integrations.
@shirkevich
Mikhail Shirkov (shirkevich) requested a review from a team as a code owner August 6, 2025 10:51
@mergify mergify Bot added the triage Needs triage label Aug 6, 2025
@coderabbitai

coderabbitai Bot commented Aug 6, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds Google Cloud Storage (GCS) Terraform backend support plus shared GCP authentication utilities, new error sentinels, backend registration/validation updates, client caching and retry logic, and accompanying unit tests and store integration changes.

Changes

Cohort / File(s) Summary
Error definitions
errors/errors.go
Added error sentinels: ErrCreateGCSClient, ErrGetObjectFromGCS, ErrReadGCSObjectBody, ErrGCSBucketRequired, ErrInvalidBackendConfig.
Dependencies
go.mod
Added cloud.google.com/go/storage v1.51.0 as a direct requirement (moved from indirect).
GCP auth utilities
internal/gcp/auth.go, internal/gcp/auth_test.go
New AuthOptions and GetClientOptions to unify GCP client option creation (supports JSON creds, file path, ADC); helpers to extract credentials from backend/store; unit tests covering behaviors.
GCS backend implementation
internal/terraform_backend/terraform_backend_gcs.go, internal/terraform_backend/terraform_backend_gcs_test.go
New GCS backend reader with pluggable client/bucket/object interfaces, credential/impersonation extraction, per-backend client cache, per-attempt timeouts and retry logic, detailed error wrapping; extensive unit tests and mocks exercising success, error, retry, caching, and config validation paths.
Backend registry & utils
internal/terraform_backend/terraform_backend_registry.go, internal/terraform_backend/terraform_backend_utils.go
Registered ReadTerraformBackendGCS for cfg.BackendTypeGCS; updated unsupported-backend message to include gcs.
Backend generation validation
internal/exec/terraform_generate_backend.go
Switched to backend type constant for S3 check and added GCS bucket presence validation that returns the new wrapped error sentinel when missing.
Store integration
pkg/store/google_secret_manager_store.go
Replaced manual option.WithCredentialsJSON handling with call to gcp.GetClientOptions using centralized auth logic.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Reg as Backend Registry
    participant GCS as ReadTerraformBackendGCS
    participant Cache as Client Cache
    participant Auth as GCP Auth (GetClientOptions)
    participant GCloud as Google Cloud Storage

    App->>Reg: Request backend reader (GCS)
    Reg->>GCS: ReadTerraformBackendGCS(componentSections)
    GCS->>Cache: Lookup client (hash(credentials+impersonation))
    alt client cached
        Cache-->>GCS: Return cached GCSClient
    else create client
        GCS->>Auth: GetClientOptions(AuthOptions{Credentials})
        Auth-->>GCS: []option.ClientOption (JSON/file/ADC)
        GCS->>GCloud: Create storage.Client (with timeout)
        GCloud-->>GCS: GCSClient
        GCS->>Cache: Store client with key
    end
    GCS->>GCS: Compute object path (prefix + workspace)
    GCS->>GCloud: Bucket(name).Object(path).NewReader(ctx)
    alt Success
        GCloud-->>GCS: Reader -> bytes
        GCS-->>App: Return state bytes
    else NotFound
        GCloud-->>GCS: NotFound
        GCS-->>App: Return nil (no error)
    else Transient error
        GCS->>GCS: Retry up to maxRetries (per-attempt timeout)
        GCloud-->>GCS: Success or persistent error
        GCS-->>App: Return bytes or wrapped error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

  • Areas needing extra attention:
    • internal/terraform_backend/terraform_backend_gcs.go — client caching, timeout/retry logic, interface abstractions, error wrapping.
    • internal/gcp/auth.go — credential detection (JSON vs path vs ADC) and produced client options.
    • Tests in internal/terraform_backend/terraform_backend_gcs_test.go — verify mocks, transient error simulation, and caching behavior for correctness.

Possibly related PRs

Suggested reviewers

  • aknysh
  • osterman

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Support !terraform.state on GCS Backends" directly and clearly summarizes the primary objective of this changeset: enabling Google Cloud Storage backend support for the Atmos !terraform.state YAML function. The title is concise, specific about what's being added (GCS backend support) and where it applies (the !terraform.state function), and avoids generic or noisy language. The title accurately reflects the scope of changes across multiple files including GCS backend implementation, authentication support, error handling, and backend registry updates.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a583986 and b3d52de.

📒 Files selected for processing (2)
  • errors/errors.go (1 hunks)
  • internal/exec/terraform_generate_backend.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/exec/terraform_generate_backend.go
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: Define interfaces for major functionality and use dependency injection to enable testability.
Generate mocks using go.uber.org/mock/mockgen via //go:generate directives (never manual mocks).
Prefer functional Options pattern instead of functions with many parameters for configuration.
Use context.Context only for cancellation, deadlines/timeouts, and request-scoped values; never for configuration or dependencies; context should be the first parameter.
All comments must end with periods (godot linter).
Preserve helpful existing comments; update them to match code when refactoring; only remove when incorrect, redundant, or code removed.
Organize imports in three groups (stdlib, third-party, Atmos) separated by blank lines and sorted alphabetically; maintain aliases cfg, log, u, errUtils.
Add defer perf.Track(atmosConfig, "pkg.FuncName")() (or nil if no atmosConfig) plus a blank line at the start of all public functions for performance tracking.
Use static errors from errors/errors.go; wrap with fmt.Errorf("%w") for chaining; use errors.Join for independent errors; avoid dynamic errors and string comparison; use errors.Is for checks.
Never use //revive:disable:file-length-limit to bypass file size limits; keep files small and focused (<600 lines).
Environment variables must be bound with viper.BindEnv using ATMOS_ prefix (e.g., viper.BindEnv("ATMOS_VAR", "ATMOS_VAR", "FALLBACK")).
Ensure cross-platform compatibility: use filepath.Join instead of hardcoded path separators and prefer SDKs over shelling out to binaries.

Files:

  • errors/errors.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • errors/errors.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
errors/errors.go (1)

73-80: LGTM! Well-structured GCS error sentinels.

The new GCS errors follow Go conventions and mirror the existing S3/Azure patterns nicely. Naming is consistent, messages are clear, and placement alongside other backend errors makes sense.


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

🧹 Nitpick comments (5)
internal/gcp/auth.go (1)

17-18: Track the impersonation TODO.

The service account impersonation feature is noted but not implemented. This is fine for the initial implementation.

Would you like me to create an issue to track adding service account impersonation support in a follow-up PR?

internal/terraform_backend/terraform_backend_gcs.go (1)

159-165: Service account impersonation needs implementation.

The TODO for impersonation is logged but not implemented. This aligns with the TODO in the auth package.

Would you like me to help implement service account impersonation using google.golang.org/api/impersonate in a follow-up PR?

internal/terraform_backend/terraform_backend_gcs_test.go (3)

48-52: Move mock client creation outside the loop.

The mock client doesn't change between test cases.

+	mockClient := &mockGCSClient{}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
-			// Create a mock client that should never be called due to validation errors
-			mockClient := &mockGCSClient{}
-
 			result, err := tb.ReadTerraformBackendGCSInternal(mockClient, &tt.componentData, &tt.gcsBackend)

126-126: Inconsistent test function naming.

Use consistent naming - either TestReadTerraformBackendGCSInternal or keep underscores for all similar tests.


347-349: Use consistent assertion style.

Consider using assert package for consistency with other tests.

-			if got != tt.expected {
-				t.Errorf("GetGCSBackendCredentials() = %v, want %v", got, tt.expected)
-			}
+			assert.Equal(t, tt.expected, got, "GetGCSBackendCredentials() should return expected value")

And similarly for line 384-386:

-			if got != tt.expected {
-				t.Errorf("GetGCSBackendImpersonateServiceAccount() = %v, want %v", got, tt.expected)
-			}
+			assert.Equal(t, tt.expected, got, "GetGCSBackendImpersonateServiceAccount() should return expected value")

Also applies to: 384-386

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 641039f and fa0383c.

📒 Files selected for processing (11)
  • errors/errors.go (1 hunks)
  • go.mod (1 hunks)
  • internal/exec/terraform_generate_backend.go (1 hunks)
  • internal/gcp/auth.go (1 hunks)
  • internal/gcp/auth_test.go (1 hunks)
  • internal/terraform_backend/terraform_backend_gcs.go (1 hunks)
  • internal/terraform_backend/terraform_backend_gcs_test.go (1 hunks)
  • internal/terraform_backend/terraform_backend_registry.go (1 hunks)
  • internal/terraform_backend/terraform_backend_utils.go (1 hunks)
  • pkg/store/google_secret_manager_store.go (2 hunks)
  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.go

📄 CodeRabbit Inference Engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

Files:

  • internal/exec/terraform_generate_backend.go
  • internal/terraform_backend/terraform_backend_utils.go
  • internal/terraform_backend/terraform_backend_registry.go
  • pkg/store/google_secret_manager_store.go
  • internal/gcp/auth.go
  • errors/errors.go
  • internal/terraform_backend/terraform_backend_gcs.go
  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
go.mod

📄 CodeRabbit Inference Engine (.cursor/rules/atmos-rules.mdc)

Manage dependencies with Go modules

Files:

  • go.mod
website/**

📄 CodeRabbit Inference Engine (.cursor/rules/atmos-rules.mdc)

website/**: Update website documentation in the website/ directory when adding new features
Follow the website's documentation structure and style
Keep website code in the website/ directory
Follow the existing website architecture and style
Document new features on the website
Include examples and use cases in website documentation

Files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
**/*_test.go

📄 CodeRabbit Inference Engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for testing multiple scenarios
Include integration tests for command flows
Test CLI end-to-end when possible
Use test fixtures for complex inputs
Consider using testify/mock for creating mock implementations

Files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
🧠 Learnings (51)
📓 Common learnings
Learnt from: Listener430
PR: cloudposse/atmos#934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
Learnt from: mcalhoun
PR: cloudposse/atmos#963
File: website/docs/core-concepts/projects/configuration/stores.mdx:286-286
Timestamp: 2025-04-25T20:54:19.701Z
Learning: For the AWS SSM Parameter Store implementation in Atmos, support for `read_role_arn` and `write_role_arn` options is essential to enable cross-account access, allowing users to run operations like `terraform plan` in multiple accounts while accessing values across keystores. Azure Key Vault would need similar capabilities for cross-tenant/subscription authentication.
📚 Learning: in `internal/exec/terraform.go`, skipping stack validation when help flags are present is not necess...
Learnt from: aknysh
PR: cloudposse/atmos#825
File: internal/exec/terraform.go:30-30
Timestamp: 2024-12-07T16:19:01.683Z
Learning: In `internal/exec/terraform.go`, skipping stack validation when help flags are present is not necessary.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: the variable `shouldcheckstack` in `executeterraform` controls whether validation is performed....
Learnt from: osterman
PR: cloudposse/atmos#727
File: internal/exec/terraform.go:65-66
Timestamp: 2024-10-31T19:23:45.538Z
Learning: The variable `shouldCheckStack` in `ExecuteTerraform` controls whether validation is performed.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: in the go function `processtagterraformoutput` in `internal/exec/yaml_func_terraform_output.go`, par...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: internal/exec/yaml_func_terraform_output.go:35-40
Timestamp: 2024-11-30T22:07:08.610Z
Learning: In the Go function `processTagTerraformOutput` in `internal/exec/yaml_func_terraform_output.go`, parameters cannot contain spaces. The code splits the input by spaces, and if the parameters contain spaces, `len(parts) != 3` will fail and show an error to the user.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: the "executeatmosvalidateschemacmd" function in internal/exec/validate_schema.go has been reviewed a...
Learnt from: samtholiya
PR: cloudposse/atmos#1147
File: internal/exec/validate_schema.go:42-57
Timestamp: 2025-04-11T22:06:46.999Z
Learning: The "ExecuteAtmosValidateSchemaCmd" function in internal/exec/validate_schema.go has been reviewed and confirmed to have acceptable cognitive complexity despite static analysis warnings. The function uses a clean structure with only three if statements for error handling and delegates complex operations to helper methods.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: in `internal/exec/terraform_clean.go`, the function `determinecleanpath` is necessary and should not...
Learnt from: haitham911
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:215-223
Timestamp: 2024-10-27T04:41:49.199Z
Learning: In `internal/exec/terraform_clean.go`, the function `determineCleanPath` is necessary and should not be removed.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: in `cmd/version.go`, when handling the `--check` flag in the `versioncmd`, avoid using `checkforatmo...
Learnt from: Listener430
PR: cloudposse/atmos#844
File: cmd/version.go:34-44
Timestamp: 2024-12-13T15:28:13.630Z
Learning: In `cmd/version.go`, when handling the `--check` flag in the `versionCmd`, avoid using `CheckForAtmosUpdateAndPrintMessage(cliConfig)` as it updates the cache timestamp, which may not be desired in this context.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: in `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate va...
Learnt from: Listener430
PR: cloudposse/atmos#825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Applied to files:

  • internal/exec/terraform_generate_backend.go
📚 Learning: in the go code for `componentfunc` in `internal/exec/template_funcs_component.go`, the function `cle...
Learnt from: aknysh
PR: cloudposse/atmos#775
File: internal/exec/template_funcs_component.go:157-159
Timestamp: 2024-11-12T03:16:02.910Z
Learning: In the Go code for `componentFunc` in `internal/exec/template_funcs_component.go`, the function `cleanTerraformWorkspace` does not return errors, and it's acceptable if the file does not exist. Therefore, error handling for `cleanTerraformWorkspace` is not needed.

Applied to files:

  • internal/exec/terraform_generate_backend.go
  • internal/terraform_backend/terraform_backend_utils.go
  • internal/terraform_backend/terraform_backend_gcs.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: when specifying color values in functions like `confirmdeleteterraformlocal` in `internal/exec/terra...
Learnt from: osterman
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:233-235
Timestamp: 2024-10-31T19:25:41.298Z
Learning: When specifying color values in functions like `confirmDeleteTerraformLocal` in `internal/exec/terraform_clean.go`, avoid hardcoding color values. Instead, use predefined color constants or allow customization through configuration settings to improve accessibility and user experience across different terminals and themes.

Applied to files:

  • internal/exec/terraform_generate_backend.go
  • internal/terraform_backend/terraform_backend_utils.go
📚 Learning: in `internal/exec/terraform.go`, the workspace cleaning code under both the general execution path a...
Learnt from: aknysh
PR: cloudposse/atmos#759
File: internal/exec/terraform.go:366-368
Timestamp: 2024-11-02T15:35:09.958Z
Learning: In `internal/exec/terraform.go`, the workspace cleaning code under both the general execution path and within the `case "init":` block is intentionally duplicated because the code execution paths are different. The `.terraform/environment` file should be deleted before executing `terraform init` in both scenarios to ensure a clean state.

Applied to files:

  • internal/exec/terraform_generate_backend.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to go.mod : manage dependencies with go modules...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to go.mod : Manage dependencies with Go modules

Applied to files:

  • go.mod
📚 Learning: go version 1.23.0 was deliberately introduced by the maintainer (aknysh) in january 2025. while this...
Learnt from: aknysh
PR: cloudposse/atmos#944
File: go.mod:3-3
Timestamp: 2025-01-17T00:21:32.987Z
Learning: Go version 1.23.0 was deliberately introduced by the maintainer (aknysh) in January 2025. While this might be a pre-release or development version of Go, it has been approved for use in this project.

Applied to files:

  • go.mod
📚 Learning: the project uses go version 1.23.0 which has been confirmed by the maintainer to be working in produ...
Learnt from: aknysh
PR: cloudposse/atmos#944
File: go.mod:3-3
Timestamp: 2025-01-17T00:21:32.987Z
Learning: The project uses Go version 1.23.0 which has been confirmed by the maintainer to be working in production for months. Do not flag this as an invalid Go version.

Applied to files:

  • go.mod
📚 Learning: when replacing significant dependencies like `go-getter` that require extensive changes, prefer to a...
Learnt from: aknysh
PR: cloudposse/atmos#768
File: internal/exec/vendor_model_component.go:3-20
Timestamp: 2024-11-18T13:59:10.824Z
Learning: When replacing significant dependencies like `go-getter` that require extensive changes, prefer to address them in separate PRs.

Applied to files:

  • go.mod
📚 Learning: in the atmos project, gomplate v4 is imported with a blank import (`_ "github.com/hairyhenderson/gom...
Learnt from: aknysh
PR: cloudposse/atmos#1363
File: internal/exec/template_utils.go:18-18
Timestamp: 2025-07-05T20:59:02.914Z
Learning: In the Atmos project, gomplate v4 is imported with a blank import (`_ "github.com/hairyhenderson/gomplate/v4"`) alongside v3 imports to resolve AWS SDK version conflicts. V3 uses older AWS SDK versions that conflict with newer AWS modules used by Atmos. A full migration to v4 requires extensive refactoring due to API changes and should be handled in a separate PR.

Applied to files:

  • go.mod
  • internal/terraform_backend/terraform_backend_utils.go
  • pkg/store/google_secret_manager_store.go
  • internal/gcp/auth.go
📚 Learning: applies to **/*.go : use interfaces for external dependencies to facilitate mocking...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Use interfaces for external dependencies to facilitate mocking

Applied to files:

  • go.mod
  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: all code must pass golangci-lint checks...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: All code must pass golangci-lint checks

Applied to files:

  • go.mod
  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to **/*.go : use viper for managing configuration, environment variables, and flags...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Use Viper for managing configuration, environment variables, and flags

Applied to files:

  • go.mod
📚 Learning: go doesn't have a built-in secure string type. for sensitive data like tokens, using environment var...
Learnt from: samtholiya
PR: cloudposse/atmos#1077
File: pkg/downloader/custom_github_detector.go:47-68
Timestamp: 2025-02-20T18:33:16.567Z
Learning: Go doesn't have a built-in secure string type. For sensitive data like tokens, using environment variables (which are protected by the OS) is a common and secure practice.

Applied to files:

  • go.mod
  • pkg/store/google_secret_manager_store.go
📚 Learning: applies to **/*.go : use viper for configuration management...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Use Viper for configuration management

Applied to files:

  • go.mod
📚 Learning: the code in pkg/config/go-homedir is a direct fork of the mitchellh/go-homedir package and was inten...
Learnt from: osterman
PR: cloudposse/atmos#1139
File: pkg/config/go-homedir/homedir.go:183-196
Timestamp: 2025-03-12T21:38:42.699Z
Learning: The code in pkg/config/go-homedir is a direct fork of the mitchellh/go-homedir package and was intentionally imported as-is without modifications to maintain consistency with the original source. Security concerns or other improvements may be addressed in future PRs.

Applied to files:

  • go.mod
  • pkg/store/google_secret_manager_store.go
📚 Learning: applies to **/*.go : support configuration via files, environment variables, and flags...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Support configuration via files, environment variables, and flags

Applied to files:

  • go.mod
  • internal/gcp/auth.go
📚 Learning: the redis dependency (github.com/redis/go-redis/v9) in the atmos project is only used in tests, not ...
Learnt from: aknysh
PR: cloudposse/atmos#1274
File: go.mod:63-63
Timestamp: 2025-05-30T03:21:37.197Z
Learning: The redis dependency (github.com/redis/go-redis/v9) in the atmos project is only used in tests, not in production code.

Applied to files:

  • go.mod
  • pkg/store/google_secret_manager_store.go
📚 Learning: applies to **/*.go : provide clear error messages to users...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Provide clear error messages to users

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
  • errors/errors.go
📚 Learning: applies to **/*.go : use meaningful error messages...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Use meaningful error messages

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
  • errors/errors.go
📚 Learning: applies to **/*.go : consider using a custom error type for domain-specific errors...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Consider using a custom error type for domain-specific errors

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
  • errors/errors.go
📚 Learning: the error variable `errrelpath` is defined in `internal/exec/terraform_clean_util.go` and is used ac...
Learnt from: haitham911
PR: cloudposse/atmos#1195
File: internal/exec/terraform_clean.go:99-99
Timestamp: 2025-04-26T15:54:10.506Z
Learning: The error variable `ErrRelPath` is defined in `internal/exec/terraform_clean_util.go` and is used across files in the `exec` package, including in `terraform_clean.go`. This is part of an approach to standardize error handling in the codebase.

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
📚 Learning: in the go codebase for atmos, when reviewing functions like `checkatmosconfig` in `cmd/cmd_utils.go`...
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
  • pkg/store/google_secret_manager_store.go
  • errors/errors.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: in the 'atmos' project, when reviewing go code like `pkg/config/config.go`, avoid suggesting file si...
Learnt from: osterman
PR: cloudposse/atmos#808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
📚 Learning: in `cmd/cmd_utils.go`, it's acceptable to have hardcoded references to `atmos.yaml` in logs, and it'...
Learnt from: haitham911
PR: cloudposse/atmos#736
File: pkg/config/const.go:6-6
Timestamp: 2024-10-20T13:12:46.499Z
Learning: In `cmd/cmd_utils.go`, it's acceptable to have hardcoded references to `atmos.yaml` in logs, and it's not necessary to update them to use the `CliConfigFileName` constant.

Applied to files:

  • internal/terraform_backend/terraform_backend_utils.go
📚 Learning: applies to **/*.go : follow go's error handling idioms...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*.go : Follow Go's error handling idioms

Applied to files:

  • errors/errors.go
📚 Learning: in the `terraform.output.mdx` documentation file (`website/docs/core-concepts/stacks/yaml-functions/...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: website/docs/core-concepts/stacks/yaml-functions/terraform.output.mdx:0-0
Timestamp: 2024-12-03T04:01:16.446Z
Learning: In the `terraform.output.mdx` documentation file (`website/docs/core-concepts/stacks/yaml-functions/terraform.output.mdx`), the cache invalidation and cache scope behavior for the `!terraform.output` function are already described.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in `examples/tests/stacks/catalog/terraform/template-functions-test2/defaults.yaml`, `!exec atmos te...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: examples/tests/stacks/catalog/terraform/template-functions-test2/defaults.yaml:28-32
Timestamp: 2024-12-01T00:33:20.298Z
Learning: In `examples/tests/stacks/catalog/terraform/template-functions-test2/defaults.yaml`, `!exec atmos terraform output` is used in examples to demonstrate its usage, even though `!terraform.output` is the recommended approach according to the documentation.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the documentation for `!terraform.output`, warnings about template variable availability are alre...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: website/docs/core-concepts/stacks/yaml-functions/terraform.output.mdx:104-110
Timestamp: 2024-12-03T03:49:30.395Z
Learning: In the documentation for `!terraform.output`, warnings about template variable availability are already covered in other sections, so no need to suggest adding them here.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: the atmos yaml function `!env` is used to retrieve environment variables and assign them to sections...
Learnt from: aknysh
PR: cloudposse/atmos#0
File: :0-0
Timestamp: 2025-01-19T22:30:27.600Z
Learning: The Atmos YAML function `!env` is used to retrieve environment variables and assign them to sections in stack manifests. It supports both simple types (string, number, boolean) and complex types (JSON-encoded lists, maps, objects).

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: the atmos yaml function `!include` allows downloading local or remote files from different sources a...
Learnt from: aknysh
PR: cloudposse/atmos#0
File: :0-0
Timestamp: 2025-01-19T22:30:27.600Z
Learning: The Atmos YAML function `!include` allows downloading local or remote files from different sources and assigning their contents to sections in stack manifests. It supports various protocols (file, http, git, s3, etc.) and can filter content using YQ expressions.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the context of the atmos project, it's acceptable for functions like `execterraformoutput` to rem...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: internal/exec/terraform_utils.go:40-213
Timestamp: 2024-12-03T05:18:49.169Z
Learning: In the context of the Atmos project, it's acceptable for functions like `execTerraformOutput` to remain as single functions if they perform a single purpose, such as retrieving Terraform outputs for a component in a stack, even if the function is lengthy.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the `getstackterraformstatefolder` function, it's acceptable and not an error if no terraform sta...
Learnt from: haitham911
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:183-187
Timestamp: 2024-10-27T04:34:08.011Z
Learning: In the `getStackTerraformStateFolder` function, it's acceptable and not an error if no Terraform state folders are found for a stack.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: for the aws ssm parameter store implementation in atmos, support for `read_role_arn` and `write_role...
Learnt from: mcalhoun
PR: cloudposse/atmos#963
File: website/docs/core-concepts/projects/configuration/stores.mdx:286-286
Timestamp: 2025-04-25T20:54:19.701Z
Learning: For the AWS SSM Parameter Store implementation in Atmos, support for `read_role_arn` and `write_role_arn` options is essential to enable cross-account access, allowing users to run operations like `terraform plan` in multiple accounts while accessing values across keystores. Azure Key Vault would need similar capabilities for cross-tenant/subscription authentication.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the atmos project, a 5-minute timeout in the `execterraformoutput` function is acceptable for ret...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: internal/exec/terraform_utils.go:145-146
Timestamp: 2024-12-03T05:29:07.718Z
Learning: In the Atmos project, a 5-minute timeout in the `execTerraformOutput` function is acceptable for retrieving `terraform output` for a component in a stack.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: unit tests for remote state backend functionality are located in the `examples/tests` directory....
Learnt from: aknysh
PR: cloudposse/atmos#863
File: internal/exec/stack_utils.go:201-223
Timestamp: 2024-12-17T07:10:26.295Z
Learning: Unit tests for remote state backend functionality are located in the `examples/tests` directory.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: in `internal/exec/terraform_clean.go`, when `getstackterraformstatefolder` returns an error in the `...
Learnt from: haitham911
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:407-416
Timestamp: 2024-11-24T19:13:10.287Z
Learning: In `internal/exec/terraform_clean.go`, when `getStackTerraformStateFolder` returns an error in the `handleCleanSubCommand` function, the error is logged, and the process continues without returning the error.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: applies to **/*_test.go : every new feature must include comprehensive unit tests...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to **/*_test.go : test both happy paths and error conditions...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Test both happy paths and error conditions

Applied to files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to **/*_test.go : consider using testify/mock for creating mock implementations...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Consider using testify/mock for creating mock implementations

Applied to files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to **/*_test.go : use table-driven tests for testing multiple scenarios...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Use table-driven tests for testing multiple scenarios

Applied to files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to **/*_test.go : include integration tests for command flows...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Include integration tests for command flows

Applied to files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: applies to **/*_test.go : use test fixtures for complex inputs...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Use test fixtures for complex inputs

Applied to files:

  • internal/gcp/auth_test.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: the atmos codebase has a custom extension to *testing.t that provides a chdir method, allowing test ...
Learnt from: samtholiya
PR: cloudposse/atmos#1255
File: cmd/describe_affected_test.go:15-15
Timestamp: 2025-05-23T19:51:47.091Z
Learning: The atmos codebase has a custom extension to *testing.T that provides a Chdir method, allowing test functions to call t.Chdir() to change working directories during tests. This is used consistently across test files in the codebase.

Applied to files:

  • internal/gcp/auth_test.go
📚 Learning: ci should run unit tests, integration tests, golangci-lint, and coverage reporting...
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: CI should run unit tests, integration tests, golangci-lint, and coverage reporting

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs_test.go
🧬 Code Graph Analysis (2)
internal/terraform_backend/terraform_backend_utils.go (2)
errors/errors.go (1)
  • ErrUnsupportedBackendType (49-49)
internal/terraform_backend/terraform_backend_utils_test.go (1)
  • TestGetTerraformBackend (103-190)
pkg/store/google_secret_manager_store.go (1)
internal/gcp/auth.go (3)
  • GetClientOptions (32-48)
  • AuthOptions (10-19)
  • GetCredentialsFromStore (61-66)
🪛 LanguageTool
website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx

[style] ~24-~24: Consider using a more formal/concise alternative here.
Context: ...accordingly. If you are using backends other than the supported ones, consider the [__`!s...

(OTHER_THAN)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (16)
go.mod (1)

7-7: Clean dependency declaration for GCS support.

Moving cloud.google.com/go/storage from indirect to direct requirements properly reflects its usage in the new GCS backend implementation.

errors/errors.go (1)

54-57: Well-defined error variables for GCS backend operations.

The new error variables follow established patterns and provide clear, meaningful messages. The generic ErrInvalidBackendConfig is a nice addition that can be reused across backends.

internal/terraform_backend/terraform_backend_utils.go (1)

119-119: Error message updated to reflect GCS support.

Good maintenance - the error message now accurately lists all currently supported backend types.

internal/exec/terraform_generate_backend.go (1)

87-92: Proper validation for GCS backend configuration.

The validation follows the established pattern for S3 backend validation and ensures required configuration is present. Clear error messaging helps users understand what's missing.

internal/terraform_backend/terraform_backend_registry.go (1)

23-23: GCS backend registration completed.

This replaces the nil placeholder with the actual implementation, following the same pattern as other backend registrations. Clean integration.

pkg/store/google_secret_manager_store.go (1)

15-16: Clean integration of unified GCP authentication.

The refactoring to use the centralized authentication utilities is well done. It removes duplicate authentication logic and ensures consistent credential handling across GCP services.

Also applies to: 61-64

internal/gcp/auth.go (1)

1-48: Solid foundation for unified GCP authentication.

The authentication utility is well-structured with clear separation of concerns. The automatic handling of JSON vs file path credentials and fallback to ADC provides good flexibility.

internal/gcp/auth_test.go (1)

1-178: Comprehensive test coverage for authentication utilities.

The tests properly cover all credential scenarios and edge cases. Good use of table-driven tests as per project guidelines.

website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx (1)

16-27: Clear documentation for GCS backend support.

The documentation effectively explains the new GCS backend functionality with practical examples and comprehensive authentication options. The structure matches existing backend documentation patterns.

Also applies to: 356-398

internal/terraform_backend/terraform_backend_gcs.go (1)

113-136: Well-structured state reading implementation.

The separation between public and internal functions, proper backend extraction, and integration with the caching layer is clean and maintainable.

internal/terraform_backend/terraform_backend_gcs_test.go (6)

1-16: LGTM!

Package declaration and imports are properly structured.


69-124: Well-structured mock implementations.

Clean interface implementations with realistic GCS behavior simulation.


143-168: Good coverage of nested configuration scenario.

Tests realistic usage pattern from YAML functions.


170-204: Clean error injection mocks.

Effective design for testing various failure scenarios.


205-301: Comprehensive error scenario coverage.

Excellent table-driven tests covering all major error paths including gRPC errors, timeouts, and IO failures.


446-486: Excellent caching verification tests.

Properly validates cache key generation for different authentication configurations.

Critical fixes:
- Fix indentation issue in test assertions
- Replace len() with SHA256 hash for cache key security
- Fix context leak in retry loop by removing defer from loop

Code quality improvements:
- Move mock client creation outside test loop for performance
- Standardize test function naming (Test_* -> Test*)
- Use consistent assert.Equal() style instead of manual error checks
- Optimize resource management and prevent cache collisions

All tests pass with improved performance and security.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Aug 6, 2025
@mergify mergify Bot removed the triage Needs triage label Aug 6, 2025
- Remove impersonate_service_account from example configurations
- Update authentication methods to remove impersonation reference
- Add clear limitation notice that impersonation is not yet implemented
- Remove commented impersonation example in configuration

This ensures users understand current limitations and prevents
confusion about unsupported features.

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

🧹 Nitpick comments (1)
website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx (1)

360-377: Minor YAML hygiene for the example

The example is great, but two tiny tweaks improve copy-paste safety:

  1. credentials paths that start with / can break when the file isn’t present on a reader’s machine. Consider replacing with a placeholder environment variable reference to encourage best practice:
-          credentials: "/path/to/service-account-key.json"
+          credentials: "${GOOGLE_APPLICATION_CREDENTIALS}"
  1. Since the third argument is a YQ expression containing brackets, quoting it avoids accidental YAML parsing surprises:
-        public_subnet_id: !terraform.state subnets dev .subnet_ids[0]
+        public_subnet_id: !terraform.state subnets dev ".subnet_ids[0]"

Not critical, but they make the snippet safer for newcomers.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6fb4da5 and 99028cc.

📒 Files selected for processing (1)
  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
website/**

📄 CodeRabbit Inference Engine (.cursor/rules/atmos-rules.mdc)

website/**: Update website documentation in the website/ directory when adding new features
Follow the website's documentation structure and style
Keep website code in the website/ directory
Follow the existing website architecture and style
Document new features on the website
Include examples and use cases in website documentation

Files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
🧠 Learnings (11)
📓 Common learnings
Learnt from: Listener430
PR: cloudposse/atmos#934
File: tests/fixtures/scenarios/docs-generate/README.md.gotmpl:99-118
Timestamp: 2025-01-25T03:51:57.689Z
Learning: For the cloudposse/atmos repository, changes to template contents should be handled in dedicated PRs and are typically considered out of scope for PRs focused on other objectives.
Learnt from: mcalhoun
PR: cloudposse/atmos#963
File: website/docs/core-concepts/projects/configuration/stores.mdx:286-286
Timestamp: 2025-04-25T20:54:19.701Z
Learning: For the AWS SSM Parameter Store implementation in Atmos, support for `read_role_arn` and `write_role_arn` options is essential to enable cross-account access, allowing users to run operations like `terraform plan` in multiple accounts while accessing values across keystores. Azure Key Vault would need similar capabilities for cross-tenant/subscription authentication.
📚 Learning: in the `terraform.output.mdx` documentation file (`website/docs/core-concepts/stacks/yaml-functions/...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: website/docs/core-concepts/stacks/yaml-functions/terraform.output.mdx:0-0
Timestamp: 2024-12-03T04:01:16.446Z
Learning: In the `terraform.output.mdx` documentation file (`website/docs/core-concepts/stacks/yaml-functions/terraform.output.mdx`), the cache invalidation and cache scope behavior for the `!terraform.output` function are already described.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in `examples/tests/stacks/catalog/terraform/template-functions-test2/defaults.yaml`, `!exec atmos te...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: examples/tests/stacks/catalog/terraform/template-functions-test2/defaults.yaml:28-32
Timestamp: 2024-12-01T00:33:20.298Z
Learning: In `examples/tests/stacks/catalog/terraform/template-functions-test2/defaults.yaml`, `!exec atmos terraform output` is used in examples to demonstrate its usage, even though `!terraform.output` is the recommended approach according to the documentation.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the documentation for `!terraform.output`, warnings about template variable availability are alre...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: website/docs/core-concepts/stacks/yaml-functions/terraform.output.mdx:104-110
Timestamp: 2024-12-03T03:49:30.395Z
Learning: In the documentation for `!terraform.output`, warnings about template variable availability are already covered in other sections, so no need to suggest adding them here.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: the atmos yaml function `!env` is used to retrieve environment variables and assign them to sections...
Learnt from: aknysh
PR: cloudposse/atmos#0
File: :0-0
Timestamp: 2025-01-19T22:30:27.600Z
Learning: The Atmos YAML function `!env` is used to retrieve environment variables and assign them to sections in stack manifests. It supports both simple types (string, number, boolean) and complex types (JSON-encoded lists, maps, objects).

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: the atmos yaml function `!include` allows downloading local or remote files from different sources a...
Learnt from: aknysh
PR: cloudposse/atmos#0
File: :0-0
Timestamp: 2025-01-19T22:30:27.600Z
Learning: The Atmos YAML function `!include` allows downloading local or remote files from different sources and assigning their contents to sections in stack manifests. It supports various protocols (file, http, git, s3, etc.) and can filter content using YQ expressions.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the context of the atmos project, it's acceptable for functions like `execterraformoutput` to rem...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: internal/exec/terraform_utils.go:40-213
Timestamp: 2024-12-03T05:18:49.169Z
Learning: In the context of the Atmos project, it's acceptable for functions like `execTerraformOutput` to remain as single functions if they perform a single purpose, such as retrieving Terraform outputs for a component in a stack, even if the function is lengthy.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the `getstackterraformstatefolder` function, it's acceptable and not an error if no terraform sta...
Learnt from: haitham911
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:183-187
Timestamp: 2024-10-27T04:34:08.011Z
Learning: In the `getStackTerraformStateFolder` function, it's acceptable and not an error if no Terraform state folders are found for a stack.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: for the aws ssm parameter store implementation in atmos, support for `read_role_arn` and `write_role...
Learnt from: mcalhoun
PR: cloudposse/atmos#963
File: website/docs/core-concepts/projects/configuration/stores.mdx:286-286
Timestamp: 2025-04-25T20:54:19.701Z
Learning: For the AWS SSM Parameter Store implementation in Atmos, support for `read_role_arn` and `write_role_arn` options is essential to enable cross-account access, allowing users to run operations like `terraform plan` in multiple accounts while accessing values across keystores. Azure Key Vault would need similar capabilities for cross-tenant/subscription authentication.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: in the atmos project, a 5-minute timeout in the `execterraformoutput` function is acceptable for ret...
Learnt from: aknysh
PR: cloudposse/atmos#810
File: internal/exec/terraform_utils.go:145-146
Timestamp: 2024-12-03T05:29:07.718Z
Learning: In the Atmos project, a 5-minute timeout in the `execTerraformOutput` function is acceptable for retrieving `terraform output` for a component in a stack.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
📚 Learning: unit tests for remote state backend functionality are located in the `examples/tests` directory....
Learnt from: aknysh
PR: cloudposse/atmos#863
File: internal/exec/stack_utils.go:201-223
Timestamp: 2024-12-17T07:10:26.295Z
Learning: Unit tests for remote state backend functionality are located in the `examples/tests` directory.

Applied to files:

  • website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx
🪛 LanguageTool
website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx

[style] ~24-~24: Consider using a more formal/concise alternative here.
Context: ...accordingly. If you are using backends other than the supported ones, consider the [__`!s...

(OTHER_THAN)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
website/docs/core-concepts/stacks/yaml-functions/terraform.state.mdx (1)

381-397: Impersonation support is documented as “not yet implemented”, but the PR description says it IS implemented – please reconcile

The PR objectives explicitly list “service account impersonation” as a supported authentication method, yet this section:

  • omits impersonate_service_account from the auth-method list (Lines 384-387)
  • omits the parameter from the config table (Lines 390-394)
  • states in the note (Lines 395-397) that it “is parsed but not yet implemented”.

This directly contradicts the PR summary and will confuse users.

Suggested fix:

@@
-1. **Service Account Key File**: Specify the path to a service account JSON key file using the `credentials` parameter.
-2. **Default Credentials**: When no credentials are specified, the Google Cloud SDK default credentials are used.
-3. **Workload Identity** (GKE): Automatically uses the workload identity when running in GKE with Workload Identity enabled.
+1. **Service Account Key File** – specify the path to a service-account JSON key via `credentials`.
+2. **Default Credentials** – if `credentials` is omitted, Application-Default Credentials (ADC) are used.
+3. **Workload Identity** (GKE) – automatically picked up when running in clusters with WI enabled.
+4. **Service Account Impersonation** – set `impersonate_service_account` to the email of the target service account.
@@
-- `state_file`: Optional custom name for the state file (defaults to `default.tfstate`)
+- `state_file`: Optional custom name for the state file (defaults to `default.tfstate`)
+- `impersonate_service_account`: Optional service-account email to impersonate
@@
-:::note Current Limitations
-The `impersonate_service_account` parameter is parsed but not yet implemented. This feature is planned for a future release.
-:::
+:::tip
+`impersonate_service_account` is fully supported starting with this release.
+:::

Adjust wording if the implementation status is different, but ensure docs and code agree.

Likely an incorrect or invalid review comment.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Aug 6, 2025
@mergify mergify Bot removed the triage Needs triage label Aug 6, 2025
@mergify mergify Bot added the triage Needs triage label Aug 6, 2025
@mergify mergify Bot removed the triage Needs triage label Aug 6, 2025
@aknysh Andriy Knysh (aknysh) added the minor New features that do not break anything label Aug 8, 2025
Comment thread internal/gcp/auth_test.go Fixed
@codecov

codecov Bot commented Aug 8, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 51.26050% with 58 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.63%. Comparing base (1eda3a2) to head (b3d52de).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...nternal/terraform_backend/terraform_backend_gcs.go 41.48% 54 Missing and 1 partial ⚠️
internal/exec/terraform_generate_backend.go 25.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1393      +/-   ##
==========================================
- Coverage   68.69%   68.63%   -0.07%     
==========================================
  Files         376      378       +2     
  Lines       34041    34154     +113     
==========================================
+ Hits        23384    23440      +56     
- Misses       8471     8525      +54     
- Partials     2186     2189       +3     
Flag Coverage Δ
unittests 68.63% <51.26%> (-0.07%) ⬇️

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

Files with missing lines Coverage Δ
errors/errors.go 100.00% <ø> (ø)
internal/gcp/auth.go 100.00% <100.00%> (ø)
...al/terraform_backend/terraform_backend_registry.go 100.00% <100.00%> (ø)
...ernal/terraform_backend/terraform_backend_utils.go 90.32% <100.00%> (ø)
pkg/store/google_secret_manager_store.go 68.48% <100.00%> (ø)
internal/exec/terraform_generate_backend.go 50.00% <25.00%> (-2.73%) ⬇️
...nternal/terraform_backend/terraform_backend_gcs.go 41.48% <41.48%> (ø)

... and 2 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) commented Aug 8, 2025 •

Copy link
Copy Markdown
Member

@osterman Erik Osterman (Cloud Posse) (osterman) changed the title Terraform state gcs Support !terraform.state on GCS Backends Aug 14, 2025
@mergify mergify Bot added the conflict This PR has conflicts label Sep 6, 2025

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/exec/stack_processor_utils.go (1)

1282-1304: Fix AzureRM backend default key logic (missing or empty key).

The current condition only fires when the azurerm section is missing, skipping the case where it exists but lacks key. Also, use constants for backend names.

-                if finalComponentBackendType == cfg.BackendTypeAzurerm {
-                    if componentAzurerm, componentAzurermExists := componentBackendSection["azurerm"].(map[string]any); !componentAzurermExists {
-                        if _, componentAzurermKeyExists := componentAzurerm["key"].(string); !componentAzurermKeyExists {
+                if finalComponentBackendType == cfg.BackendTypeAzurerm {
+                    componentAzurerm, componentAzurermExists := componentBackendSection[cfg.BackendTypeAzurerm].(map[string]any)
+                    // Add default key when the azurerm section is missing OR when it exists but lacks `key`.
+                    if !componentAzurermExists || componentAzurerm["key"] == nil || componentAzurerm["key"] == "" {
                         azureKeyPrefixComponent := component
                         var keyName []string
                         if baseComponentName != "" {
                             azureKeyPrefixComponent = baseComponentName
                         }
-                            if globalAzurerm, globalAzurermExists := globalBackendSection["azurerm"].(map[string]any); globalAzurermExists {
-                                if _, globalAzurermKeyExists := globalAzurerm["key"].(string); globalAzurermKeyExists {
-                                    keyName = append(keyName, globalAzurerm["key"].(string))
-                                }
-                            }
+                        if globalAzurerm, globalAzurermExists := globalBackendSection[cfg.BackendTypeAzurerm].(map[string]any); globalAzurermExists {
+                            if v, ok := globalAzurerm["key"].(string); ok && v != "" {
+                                keyName = append(keyName, v)
+                            }
+                        }
                         componentKeyName := strings.Replace(azureKeyPrefixComponent, "/", "-", -1)
                         keyName = append(keyName, fmt.Sprintf("%s.terraform.tfstate", componentKeyName))
                         finalComponentBackend["key"] = strings.Join(keyName, "/")
-                        }
-                    }
+                    }
                 }
🧹 Nitpick comments (4)
internal/exec/stack_processor_utils.go (2)

1253-1266: Prefer constant for S3 backend type.

Use cfg.BackendTypeS3 instead of the string literal to align with the repo constants and recent CI guidance.

-                if finalComponentBackendType == "s3" {
+                if finalComponentBackendType == cfg.BackendTypeS3 {

1267-1281: Fix typo and punctuation in comments; keep linter happy.

"GSC" → "GCS" and end sentences with periods (godot).

-                // Google GSC backend
-                // Check if `backend` section has `prefix` for `gcs` backend type
-                // If it does not, use the component name instead
-                // https://developer.hashicorp.com/terraform/language/settings/backends/gcs
-                // https://developer.hashicorp.com/terraform/language/settings/backends/gcs#prefix
+                // Google GCS backend.
+                // Check if `backend` section has `prefix` for the GCS backend type.
+                // If it does not, use the component name instead.
+                // https://developer.hashicorp.com/terraform/language/settings/backends/gcs.
+                // https://developer.hashicorp.com/terraform/language/settings/backends/gcs#prefix.
internal/terraform_backend/terraform_backend_gcs_test.go (2)

198-203: End comment with a period (godot).

Keeps golangci-lint happy.

-// Simulate failure in io.ReadAll
+// Simulate failure in io.ReadAll.

395-405: Test name does not match behavior.

This path never simulates a transient failure; rename for clarity or make the client flaky.

-            name: "transient error with eventual success",
+            name: "success (no error path)",

If you prefer a real transient case, I can provide a flaky mock that fails once then succeeds.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 69482f2 and f7ad22f.

📒 Files selected for processing (4)
  • internal/exec/stack_processor_utils.go (2 hunks)
  • internal/exec/terraform_generate_backend.go (2 hunks)
  • internal/terraform_backend/terraform_backend_gcs.go (1 hunks)
  • internal/terraform_backend/terraform_backend_gcs_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/exec/terraform_generate_backend.go
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: Use Viper for managing configuration, environment variables, and flags
Use interfaces for external dependencies to facilitate mocking
All code must pass golangci-lint checks
Follow Go's error handling idioms
Use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider using a custom error type for domain-specific errors
Follow standard Go coding style
Use gofmt and goimports to format code
Prefer short, descriptive variable names
Use snake_case for environment variables
Document all exported functions, types, and methods
Document complex logic with inline comments
Follow Go's documentation conventions
Use Viper for configuration management
Support configuration via files, environment variables, and flags
Follow the precedence order: flags > environment variables > config file > defaults

Format Go code with gofumpt -w . and goimports -w .

**/*.go: All Go comments must be complete sentences ending with periods (enforced by golangci-lint godot).
Always wrap errors with a static error first using fmt.Errorf("%w: details", errUtils.ErrStaticError, ...); never return dynamic errors directly.
Bind environment variables with viper.BindEnv() and provide an ATMOS_ alternative for every env var.
Distinguish UI output (stderr) from structured logging; never use logging for UI prompts/errors; data/results go to stdout for piping.
Use structured logging without message interpolation and respect logging level hierarchy; logging must not affect execution.
Most text UI must go to stderr (e.g., utils.PrintfMessageToTUI or fmt.Fprintf(os.Stderr,...)); only data/results go to stdout.
For non-standard execution paths, capture telemetry with telemetry.CaptureCmd(cmd, err) or telemetry.CaptureCmdString("name", err); never capture user data.

Files:

  • internal/exec/stack_processor_utils.go
  • internal/terraform_backend/terraform_backend_gcs.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
**/*_test.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*_test.go: Every new feature must include comprehensive unit tests
Test both happy paths and error conditions
Use table-driven tests for testing multiple scenarios
Include integration tests for command flows
Test CLI end-to-end when possible
Use test fixtures for complex inputs
Consider using testify/mock for creating mock implementations

**/*_test.go: Use t.Skipf() with a clear reason when skipping tests; never use t.Skip() or t.Skipf() without a reason.
In TestMain, set a package-level skipReason for CLI-dependent tests and call os.Exit(m.Run()); do not use log.Fatal() for missing/stale binaries.
Mirror test files to implementation names (e.g., aws_ssm_store_test.go for aws_ssm_store.go) and co-locate tests with code.
New features must include comprehensive unit tests, and CLI features require integration tests using tests/ fixtures.

Files:

  • internal/terraform_backend/terraform_backend_gcs_test.go
🧠 Learnings (4)
📚 Learning: 2024-12-05T02:48:53.818Z
Learnt from: aknysh
PR: cloudposse/atmos#809
File: cmd/cmd_utils.go:470-477
Timestamp: 2024-12-05T02:48:53.818Z
Learning: The function `GetLatestGitHubRepoRelease` in the Go codebase already uses a context with a timeout, so wrapping it with an additional context is unnecessary.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2025-09-05T14:40:05.107Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-05T14:40:05.107Z
Learning: Applies to **/*.go : All Go comments must be complete sentences ending with periods (enforced by golangci-lint godot).

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: 2025-09-05T14:40:05.107Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-05T14:40:05.107Z
Learning: Applies to **/*_test.go : New features must include comprehensive unit tests, and CLI features require integration tests using tests/ fixtures.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs_test.go
📚 Learning: 2025-07-01T02:22:25.901Z
Learnt from: CR
PR: cloudposse/atmos#0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-07-01T02:22:25.901Z
Learning: Applies to **/*_test.go : Every new feature must include comprehensive unit tests

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs_test.go
🧬 Code graph analysis (3)
internal/exec/stack_processor_utils.go (1)
pkg/config/const.go (2)
  • BackendTypeGCS (86-86)
  • BackendTypeAzurerm (85-85)
internal/terraform_backend/terraform_backend_gcs.go (3)
internal/gcp/auth.go (3)
  • GetCredentialsFromBackend (52-57)
  • GetClientOptions (32-48)
  • AuthOptions (10-19)
internal/terraform_backend/terraform_backend_utils.go (3)
  • GetComponentBackend (31-36)
  • GetBackendAttribute (47-52)
  • GetTerraformWorkspace (15-20)
errors/errors.go (6)
  • ErrWrappingFormat (8-8)
  • ErrCreateGCSClient (54-54)
  • ErrStringWrappingFormat (9-9)
  • ErrInvalidBackendConfig (57-57)
  • ErrGetObjectFromGCS (55-55)
  • ErrReadGCSObjectBody (56-56)
internal/terraform_backend/terraform_backend_gcs_test.go (2)
errors/errors.go (1)
  • ErrInvalidBackendConfig (57-57)
internal/terraform_backend/terraform_backend_gcs.go (5)
  • ReadTerraformBackendGCSInternal (181-241)
  • GCSBucketHandle (49-51)
  • GCSObjectHandle (54-56)
  • GetGCSBackendCredentials (30-32)
  • GetGCSBackendImpersonateServiceAccount (36-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
internal/terraform_backend/terraform_backend_gcs.go (1)

163-170: Docs vs code: impersonation is logged as TODO.

PR summary says impersonation is supported; code logs it as “not yet implemented.” Please align implementation and docs or scope it for a follow-up.

@aknysh Andriy Knysh (aknysh) added no-release Do not create a new release (wait for additional code changes) and removed minor New features that do not break anything labels Sep 7, 2025
@aknysh

Copy link
Copy Markdown
Member

Mikhail Shirkov (@shirkevich) can you please resolve the conflicts, thanks

@gijsmin

Copy link
Copy Markdown

I like Atmos, but I really need GCS support to be able to use it, otherwise I'll have to go with Terragrunt, so any information when this is released?

@mergify mergify Bot removed the conflict This PR has conflicts label Sep 28, 2025

@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

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e39e239 and 6314e20.

📒 Files selected for processing (2)
  • go.mod (1 hunks)
  • internal/terraform_backend/terraform_backend_gcs.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • go.mod
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

**/*.go: All code must pass golangci-lint checks
Follow Go error handling idioms and use meaningful error messages
Wrap errors with context using fmt.Errorf("context: %w", err)
Consider custom error types for domain-specific errors
Follow standard Go coding style; run gofmt and goimports
Use snake_case for environment variables
Document complex logic with inline comments

**/*.go: All comments must end with periods.
Wrap all returned errors with static errors from errors/errors.go; never return dynamic errors directly.
Use fmt.Errorf with %w to wrap the static error first, then add context details.
Always bind environment variables via viper.BindEnv, providing an ATMOS_ alternative for each external var.
All new configurations must support Go templating using the shared FuncMap(); test template rendering with various contexts.
Prefer SDKs over shelling out to binaries; use standard library for cross-platform behavior (filepath.Join, os.PathSeparator, runtime.GOOS).
For non-standard execution paths, capture telemetry via telemetry.CaptureCmd or telemetry.CaptureCmdString without user data.

Files:

  • internal/terraform_backend/terraform_backend_gcs.go
**/!(*_test).go

📄 CodeRabbit inference engine (.cursor/rules/atmos-rules.mdc)

Document all exported functions, types, and methods with Go doc comments

Files:

  • internal/terraform_backend/terraform_backend_gcs.go
🧠 Learnings (8)
📚 Learning: 2024-12-05T02:48:53.818Z
Learnt from: aknysh
PR: cloudposse/atmos#809
File: cmd/cmd_utils.go:470-477
Timestamp: 2024-12-05T02:48:53.818Z
Learning: The function `GetLatestGitHubRepoRelease` in the Go codebase already uses a context with a timeout, so wrapping it with an additional context is unnecessary.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2025-09-26T05:52:03.918Z
Learnt from: CR
PR: cloudposse/atmos#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-26T05:52:03.918Z
Learning: Applies to **/*.go : All comments must end with periods.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2024-12-02T21:26:32.337Z
Learnt from: osterman
PR: cloudposse/atmos#808
File: pkg/config/config.go:478-483
Timestamp: 2024-12-02T21:26:32.337Z
Learning: In the 'atmos' project, when reviewing Go code like `pkg/config/config.go`, avoid suggesting file size checks after downloading remote configs if such checks aren't implemented elsewhere in the codebase.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2024-10-23T21:36:40.262Z
Learnt from: osterman
PR: cloudposse/atmos#740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2024-10-28T01:51:30.811Z
Learnt from: osterman
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:329-332
Timestamp: 2024-10-28T01:51:30.811Z
Learning: In the Atmos Go code, when deleting directories or handling file paths (e.g., in `terraform_clean.go`), always resolve the absolute path using `filepath.Abs` and use the logger `u.LogWarning` for logging messages instead of using `fmt.Printf`.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2024-10-31T19:25:41.298Z
Learnt from: osterman
PR: cloudposse/atmos#727
File: internal/exec/terraform_clean.go:233-235
Timestamp: 2024-10-31T19:25:41.298Z
Learning: When specifying color values in functions like `confirmDeleteTerraformLocal` in `internal/exec/terraform_clean.go`, avoid hardcoding color values. Instead, use predefined color constants or allow customization through configuration settings to improve accessibility and user experience across different terminals and themes.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2024-11-02T15:35:09.958Z
Learnt from: aknysh
PR: cloudposse/atmos#759
File: internal/exec/terraform.go:366-368
Timestamp: 2024-11-02T15:35:09.958Z
Learning: In `internal/exec/terraform.go`, the workspace cleaning code under both the general execution path and within the `case "init":` block is intentionally duplicated because the code execution paths are different. The `.terraform/environment` file should be deleted before executing `terraform init` in both scenarios to ensure a clean state.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
📚 Learning: 2024-11-12T03:16:02.910Z
Learnt from: aknysh
PR: cloudposse/atmos#775
File: internal/exec/template_funcs_component.go:157-159
Timestamp: 2024-11-12T03:16:02.910Z
Learning: In the Go code for `componentFunc` in `internal/exec/template_funcs_component.go`, the function `cleanTerraformWorkspace` does not return errors, and it's acceptable if the file does not exist. Therefore, error handling for `cleanTerraformWorkspace` is not needed.

Applied to files:

  • internal/terraform_backend/terraform_backend_gcs.go
🧬 Code graph analysis (1)
internal/terraform_backend/terraform_backend_gcs.go (4)
internal/gcp/auth.go (3)
  • GetCredentialsFromBackend (52-57)
  • GetClientOptions (32-48)
  • AuthOptions (10-19)
internal/terraform_backend/terraform_backend_utils.go (3)
  • GetComponentBackend (31-36)
  • GetBackendAttribute (47-52)
  • GetTerraformWorkspace (15-20)
pkg/config/const.go (1)
  • BackendTypeGCS (86-86)
errors/errors.go (6)
  • ErrWrappingFormat (8-8)
  • ErrCreateGCSClient (60-60)
  • ErrStringWrappingFormat (9-9)
  • ErrInvalidBackendConfig (63-63)
  • ErrGetObjectFromGCS (61-61)
  • ErrReadGCSObjectBody (62-62)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
internal/terraform_backend/terraform_backend_gcs.go (1)

192-200: Default empty workspace to "default".

An empty workspace maps to ".tfstate", which skips the actual "default.tfstate" object. Please set the workspace to "default" when GetTerraformWorkspace returns an empty string so default-workspace stacks load correctly.

Apply this diff:

  workspace := GetTerraformWorkspace(componentSections)
+ if workspace == "" {
+ 	workspace = "default"
+ }

@aknysh

Copy link
Copy Markdown
Member

Mikhail Shirkov (@shirkevich) please resolve the conflicts and address the AI comments, thanks

@shirkevich

Copy link
Copy Markdown
Collaborator Author

Andriy Knysh (@aknysh) addressed AI comments and resolved the conflicts

@aknysh Andriy Knysh (aknysh) added minor New features that do not break anything and removed no-release Do not create a new release (wait for additional code changes) labels Oct 28, 2025
coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 28, 2025

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

Mikhail Shirkov (@shirkevich) thanks for the PR.
We currently can't test it in a real system, we'll merge it, if you find any issues, please open a PR to fix

@aknysh
Andriy Knysh (aknysh) merged commit b1068c1 into cloudposse:main Oct 28, 2025
@github-actions

Copy link
Copy Markdown

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

@shirkevich

Copy link
Copy Markdown
Collaborator Author

I've tested it locally, will test it after release in production. Thanks for merging!

@github-actions

Copy link
Copy Markdown

These changes were released in v1.196.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants