Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean Terraform workspace before executing terraform init in the atmos.Component template function #775

Merged
merged 10 commits into from
Nov 12, 2024

Conversation

aknysh
Copy link
Member

@aknysh aknysh commented Nov 12, 2024

what

  • Clean Terraform workspace before executing terraform init in the atmos.Component template function

why

When using multiple backends for the same component (e.g. separate backends per tenant or account), and if an Atmos command was executed that selected a Terraform workspace, Terraform will prompt the user to select one of the following workspaces:

 1. default
 2. <the previously used workspace>

The prompt forces the user to always make a selection (which is error-prone), and also makes it complicated when running on CI/CD.

This PR adds the logic that deletes the .terraform/environment file from the component directory before executing terraform init when executing the atmos.Component template function. It allows executing the atmos.Component function for a component in different Terraform workspaces without Terraform asking to select a workspace. The .terraform/environment file contains the name of the currently selected workspace, helping Terraform identify the active workspace context for managing your infrastructure.

Summary by CodeRabbit

Release Notes

  • New Features

    • Updated Atmos tool version to enhance functionality.
    • Improved logging and path handling in Terraform workspace cleanup.
    • Expanded documentation for Atlantis integration, detailing configuration methods and workflows.
  • Bug Fixes

    • Upgraded dependency versions to address potential issues and improve performance.
  • Documentation

    • Enhanced clarity and examples in the Atlantis integration documentation.

@aknysh aknysh added the minor New features that do not break anything label Nov 12, 2024
@aknysh aknysh self-assigned this Nov 12, 2024
@aknysh aknysh requested review from a team as code owners November 12, 2024 00:27
@aknysh aknysh requested review from Gowiem and jamengual November 12, 2024 00:27
@aknysh aknysh requested review from osterman and removed request for Gowiem and jamengual November 12, 2024 00:27
Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

📝 Walkthrough

Walkthrough

This pull request includes updates to a Dockerfile and several Go files, primarily focusing on version upgrades for the Atmos tool and various dependencies. The Dockerfile's Atmos version is updated from 1.100.0 to 1.105.0. The go.mod file sees multiple dependency version updates. Additionally, the cleanTerraformWorkspace function is modified to accept a new parameter, enhancing its logging capabilities. Documentation for the Atlantis integration is also significantly revised to clarify configuration options and processes.

Changes

File Path Change Summary
examples/quick-start-advanced/Dockerfile Updated ATMOS_VERSION from 1.100.0 to 1.105.0.
go.mod Updated dependency versions: bubbletea from v1.1.2 to v1.2.1, terraform-config-inspect to v0.0.0-20241107133921-3adb156ecfe2, go-wordwrap to v1.0.1, and x/ansi to v0.4.5.
internal/exec/template_funcs_component.go Added invocation of cleanTerraformWorkspace before terraform init in componentFunc.
internal/exec/terraform.go Updated cleanTerraformWorkspace call to include cliConfig as a parameter.
internal/exec/terraform_utils.go Updated cleanTerraformWorkspace signature to accept cliConfig, improved path handling and logging.
website/docs/integrations/atlantis.mdx Enhanced documentation for Atlantis integration, detailing configuration methods and examples.

Possibly related PRs

Suggested reviewers

  • osterman
  • johncblandii

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
internal/exec/terraform_utils.go (2)

28-31: Consider enhancing error handling and validation.

While the implementation is functional, there are a few improvements that could make it more robust:

  1. Error handling: Consider logging errors instead of silently ignoring them
  2. Path validation: Add checks for the component path existence
  3. Debug message: Include the purpose of the deletion in the log message

Here's a suggested improvement:

 func cleanTerraformWorkspace(cliConfig schema.CliConfiguration, componentPath string) {
+    if _, err := os.Stat(componentPath); err != nil {
+        u.LogDebug(cliConfig, fmt.Sprintf("Component path does not exist: '%s'", componentPath))
+        return
+    }
     filePath := filepath.Join(componentPath, ".terraform", "environment")
-    u.LogDebug(cliConfig, fmt.Sprintf("\nDeleting Terraform environment file:\n'%s'", filePath))
+    u.LogDebug(cliConfig, fmt.Sprintf("\nDeleting Terraform workspace environment file to ensure clean workspace selection:\n'%s'", filePath))
-    _ = os.Remove(filePath)
+    if err := os.Remove(filePath); err != nil && !os.IsNotExist(err) {
+        u.LogDebug(cliConfig, fmt.Sprintf("Failed to delete environment file: %v", err))
+    }
 }

Line range hint 23-31: Well-implemented solution that aligns with PR objectives!

The implementation effectively addresses the workspace selection issue by cleaning up the environment file before terraform init. The added documentation comment clearly explains the purpose and behavior.

Consider documenting this behavior in the user guide, as it changes how workspace selection works, which could be important for users managing multiple backends.

examples/quick-start-advanced/Dockerfile (1)

9-9: Consider adding version constraint documentation

Consider adding a comment explaining the minimum version required for the workspace cleaning feature. This helps future maintainers understand version constraints.

+# Minimum version required for Terraform workspace cleaning feature
 ARG ATMOS_VERSION=1.105.0
internal/exec/template_funcs_component.go (1)

157-157: Add a detailed comment explaining the workspace cleanup strategy

The current comment could be more informative about why this cleanup is necessary and its implications.

Consider expanding the comment:

-// Before executing `terraform init`, delete the `.terraform/environment` file from the component directory
+// Clean up the workspace state before terraform init to prevent workspace selection prompts
+// when using multiple backends. This ensures a clean state for workspace initialization
+// and prevents conflicts between different tenant/account configurations.
internal/exec/terraform.go (1)

Line range hint 1-500: Consider breaking down the large ExecuteTerraform function.

The ExecuteTerraform function is quite lengthy (500+ lines) and handles multiple responsibilities. This makes it harder to maintain and test.

Consider breaking it down into smaller, focused functions:

  1. prepareWorkspace: Handle workspace setup, variable files, and backend configuration
  2. executeTerraformInit: Handle the init logic
  3. executeTerraformWorkspace: Handle workspace selection
  4. executeTerraformCommand: Handle the main command execution
  5. cleanupArtifacts: Handle post-execution cleanup

This would improve:

  • Code readability
  • Testability (each function can be tested independently)
  • Maintainability (changes would be localized to specific functions)
  • Reusability (functions could be used independently)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d502eb0 and c94c016.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (6)
  • examples/quick-start-advanced/Dockerfile (1 hunks)
  • go.mod (3 hunks)
  • internal/exec/template_funcs_component.go (1 hunks)
  • internal/exec/terraform.go (2 hunks)
  • internal/exec/terraform_utils.go (2 hunks)
  • website/docs/integrations/atlantis.mdx (1 hunks)
🔇 Additional comments (6)
internal/exec/terraform_utils.go (1)

4-11: LGTM! Good choice using filepath for cross-platform compatibility.

The switch from path to filepath is a solid improvement for cross-platform support. The added imports align perfectly with the new functionality.

internal/exec/template_funcs_component.go (1)

Line range hint 157-186: Verify workspace handling across different scenarios

The interaction between the new cleanup step and the subsequent workspace operations needs verification, especially for edge cases.

Let's inspect the codebase for potential issues:

✅ Verification successful

Based on the search results, I can now provide a final response since I have enough information about the workspace handling implementation:

Workspace cleanup and selection flow is properly implemented

The cleanTerraformWorkspace function is specifically designed to handle workspace state by removing the .terraform/environment file before workspace operations. This prevents workspace selection prompts when switching between different backends.

The subsequent workspace operations follow a clear pattern:

  • First attempts to create new workspace
  • Falls back to selecting existing workspace if creation fails
  • Proper error handling and logging at each step
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for workspace-related error handling patterns
# Look for similar workspace cleanup patterns and error handling

# Search for workspace-related operations
rg -A 3 "workspace" --type go

# Look for similar cleanup patterns
rg -A 3 "cleanTerraformWorkspace" --type go

# Check for related test cases
rg -A 5 "TestComponent.*Workspace" --type go

Length of output: 59543

go.mod (2)

25-25: Verify terraform-config-inspect version compatibility.

The update to a newer development version of terraform-config-inspect aligns with the PR's objective of enhancing Terraform workspace management. However, using a development version (commit hash) requires verification.

✅ Verification successful

Terraform-config-inspect update is safe to proceed

The version update from 6714b46f5fe4 to 3adb156ecfe2 only includes a single commit that pins action references, with no breaking changes or significant modifications to the codebase. This change is purely for CI/CD security improvements and does not affect the library's functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the terraform-config-inspect version compatibility
# Test: Check for any breaking changes in the commit diff

# Get the changes between the old and new commits
gh api repos/hashicorp/terraform-config-inspect/compare/6714b46f5fe4...3adb156ecfe2 \
  --jq '.commits[].commit.message'

# Look for any potential breaking changes in the code
rg -i "break|deprecat|remov|chang" \
  --glob '!{*.md,*.txt,*.json,*.yaml,*.yml}' \
  --type go

Length of output: 12634


12-12: Review bubbletea version upgrade impact.

The upgrade from v1.1.2 to v1.2.1 of bubbletea could introduce breaking changes in the terminal UI components.

✅ Verification successful

Bubbletea upgrade is safe to proceed

The upgrade from v1.1.2 to v1.2.1 is a minor version bump that follows semantic versioning. The codebase's usage of bubbletea is focused on standard features:

  • Basic program initialization with tea.NewProgram
  • Core event handling (WindowSize, Mouse, Key events)
  • Standard Model interface implementation (Init, Update, View)
  • Common mouse/keyboard interactions

These are stable APIs that don't typically change in minor versions. The codebase shows a history of smooth bubbletea upgrades through multiple versions without requiring implementation changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of bubbletea version upgrade
# Test: Look for any uses of potentially changed APIs

# Search for bubbletea usage patterns
ast-grep --pattern 'tea.NewProgram($_)'

# Look for any Model implementations
ast-grep --pattern 'type $_ struct {
  $$$
}

func ($m $_) Init() tea.Cmd {
  $$$
}'

Length of output: 128


Script:

#!/bin/bash
# Let's try a different approach using ripgrep to find bubbletea usage

# Search for bubbletea imports
rg "github.com/charmbracelet/bubbletea" -A 3

# Search for tea package usage
rg "tea\." -A 3

# Look for Model interface implementations
rg "func.*Model" -A 3

# Check git history for previous version
git log -p go.mod | grep -A 3 -B 3 "bubbletea"

Length of output: 23635

internal/exec/terraform.go (1)

288-288: 🛠️ Refactor suggestion

Consolidate duplicate workspace cleanup calls.

The workspace cleanup is performed twice:

  1. Before executing terraform init when runTerraformInit is true (line 288)
  2. In the init case of the switch statement (line 372)

Since the second cleanup would never be reached when runTerraformInit is true, we should consolidate these calls to avoid confusion and potential maintenance issues.

Consider consolidating the cleanup logic into a single location before the terraform init execution:

 	if runTerraformInit {
+		// Clean the workspace before executing `terraform init`
+		cleanTerraformWorkspace(cliConfig, componentPath)
+
 		initCommandWithArguments := []string{"init"}
 		if info.SubCommand == "workspace" || cliConfig.Components.Terraform.InitRunReconfigure {
 			initCommandWithArguments = []string{"init", "-reconfigure"}
 		}

-		// Before executing `terraform init`, delete the `.terraform/environment` file from the component directory
-		cleanTerraformWorkspace(cliConfig, componentPath)
-
 		err = ExecuteShellCommand(
 			// ...
 		)
 		if err != nil {
 			return err
 		}
 	}

 	// ... switch statement ...
 	case "init":
-		// Before executing `terraform init`, delete the `.terraform/environment` file from the component directory
-		cleanTerraformWorkspace(cliConfig, componentPath)
-
 		if cliConfig.Components.Terraform.InitRunReconfigure {
 			allArgsAndFlags = append(allArgsAndFlags, []string{"-reconfigure"}...)
 		}

Also applies to: 372-372

⛔ Skipped due to learnings
Learnt from: aknysh
PR: cloudposse/atmos#759
File: internal/exec/terraform.go:366-368
Timestamp: 2024-11-10T04:31:24.849Z
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.
website/docs/integrations/atlantis.mdx (1)

676-676: LGTM on version update, let's verify consistency.

The update of ATMOS_VERSION to 1.105.0 looks good.

Let's verify version consistency across the documentation:

✅ Verification successful

Version update is consistent across documentation

The version update to 1.105.0 is the only explicit version reference in the documentation. Other occurrences of ATMOS_VERSION are template variables used in installation instructions, which dynamically reference whatever version is being installed. This maintains good documentation practices by having a single source of truth for the version number.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other version references in the documentation
# that might need to be updated for consistency

# Search for version references in documentation
rg -i "1\.10[0-9]\.[0-9]" docs/

Length of output: 33


Script:

#!/bin/bash
# The previous command failed because we need to search from the repository root
# and include the website directory

# Search for version references in all documentation files
rg -i "1\.10[0-9]\.[0-9]" website/docs/

# Also search for any other ATMOS_VERSION references
rg "ATMOS_VERSION" website/docs/

Length of output: 669

examples/quick-start-advanced/Dockerfile Show resolved Hide resolved
internal/exec/template_funcs_component.go Show resolved Hide resolved
@aknysh aknysh merged commit 74516e6 into main Nov 12, 2024
23 checks passed
@aknysh aknysh deleted the update-atmos-component-template-func branch November 12, 2024 13:23
Copy link

These changes were released in v1.105.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
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants