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

fix: Handle TF_DATA_DIR and Error Logging for !terraform.output #1037

Closed
wants to merge 8 commits into from

Conversation

milldr
Copy link
Member

@milldr milldr commented Feb 7, 2025

what

  • Check if TF_DATA_DIR is set when running !terraform.output
  • Adding additional logging for handling errors in terraform output

why

  • If TF_DATA_DIR is set, we need to clear the correct environment when reseting workspaces
  • Debugging errors in Spacelift when running !terraform.outputs

references

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error messages with additional context for improved troubleshooting.
    • Corrected a typo in error output for clearer notifications.
  • Chores
    • Refined the cleanup process to verify file existence before deletion and to respect dynamic environment configurations.
    • Updated logging mechanism for improved consistency and clarity across the application.

@mergify mergify bot added triage Needs triage wip Work in Progress: Not ready for final review or merge labels Feb 7, 2025
@milldr milldr changed the title (WIP) Error Logging for !terraform.output fix: Handle TF_DATA_DIR and Error Logging for !terraform.output Feb 7, 2025
@mergify mergify bot removed the wip Work in Progress: Not ready for final review or merge label Feb 7, 2025
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 7, 2025
@mergify mergify bot removed the triage Needs triage label Feb 7, 2025
@mergify mergify bot added the triage Needs triage label Feb 7, 2025
@milldr milldr marked this pull request as ready for review February 7, 2025 21:24
@milldr milldr requested a review from a team as a code owner February 7, 2025 21:24
Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

📝 Walkthrough

Walkthrough

This pull request updates the logging and error handling mechanisms in the internal Terraform helper functions. The execTerraformOutput and GetTerraformOutput functions now utilize a structured logging framework, replacing previous utility-based logging. Additionally, the cleanTerraformWorkspace function has been modified to check for file existence before deletion and to log actions accordingly, improving the overall clarity and reliability of logging throughout the codebase.

Changes

File(s) Change Summary
internal/exec/terraform_outputs.go Updated logging in execTerraformOutput and GetTerraformOutput to use structured logging with enhanced error context.
internal/exec/terraform_utils.go Refactored cleanTerraformWorkspace: retrieves TF_DATA_DIR, checks file existence before deletion, and updates logging to structured format.

Suggested labels

patch

Suggested reviewers

  • osterman
  • aknysh
  • milldr
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 7, 2025
@mergify mergify bot removed the triage Needs triage label Feb 7, 2025
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: 0

🧹 Nitpick comments (1)
internal/exec/terraform_utils.go (1)

45-69: Consider handling file permission errors explicitly.

While the error handling is good, it would be helpful to distinguish between permission errors and other types of errors when checking and deleting files.

Here's a suggested improvement:

 	if _, err := os.Stat(filePath); err == nil {
 		l.Debug("Terraform environment file found. Proceeding with deletion.",
 			"file", filePath,
 		)
 		if err := os.Remove(filePath); err != nil {
+			if os.IsPermission(err) {
+				l.Debug("Permission denied when deleting Terraform environment file.",
+					"file", filePath,
+					"error", err,
+				)
+			} else {
 				l.Debug("Failed to delete Terraform environment file.",
 					"file", filePath,
 					"error", err,
 				)
+			}
 		} else {
 			l.Debug("Successfully deleted Terraform environment file.",
 				"file", filePath,
 			)
 		}
 	} else if os.IsNotExist(err) {
 		l.Debug("Terraform environment file not found. No action needed.",
 			"file", filePath,
 		)
+	} else if os.IsPermission(err) {
+		l.Debug("Permission denied when checking Terraform environment file.",
+			"file", filePath,
+			"error", err,
+		)
 	} else {
 		l.Debug("Error checking Terraform environment file.",
 			"file", filePath,
 			"error", err,
 		)
 	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a9e74ff and 317ff02.

📒 Files selected for processing (1)
  • internal/exec/terraform_utils.go (4 hunks)
🧰 Additional context used
📓 Learnings (1)
internal/exec/terraform_utils.go (1)
Learnt from: aknysh
PR: cloudposse/atmos#759
File: internal/exec/terraform.go:366-368
Timestamp: 2024-11-12T05:52:05.088Z
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.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (3)
internal/exec/terraform_utils.go (3)

8-8: LGTM! Good addition of semantic logging.

The import of charmbracelet/log aligns with the team's direction to use semantic logging for better observability.


28-44: LGTM! Robust handling of TF_DATA_DIR and paths.

The changes properly handle the TF_DATA_DIR environment variable and ensure correct path resolution, which aligns with the PR objectives.


92-94: LGTM! Consistent semantic logging.

The logging changes consistently use semantic logging with appropriate context across functions, which improves debugging capabilities.

Also applies to: 117-119

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 7, 2025
@mergify mergify bot removed the triage Needs triage label Feb 7, 2025
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

🧹 Nitpick comments (2)
internal/exec/terraform_outputs.go (2)

83-83: Consider adding more context to debug logs.

While the logging statements are clear, they could benefit from additional context fields.

Consider enhancing the debug logs with more structured fields:

-l.Debug("Writing the backend config to file:", "file", backendFileName)
+l.Debug("Writing the backend config to file:", "file", backendFileName, "component", component, "stack", stack)

-l.Debug("Wrote the backend config to file:", "file", backendFileName)
+l.Debug("Wrote the backend config to file:", "file", backendFileName, "component", component, "stack", stack)

-l.Debug("Writing the provider overrides to file:", "file", providerOverrideFileName)
+l.Debug("Writing the provider overrides to file:", "file", providerOverrideFileName, "component", component, "stack", stack)

-l.Debug("Wrote the provider overrides to file:", "file", providerOverrideFileName)
+l.Debug("Wrote the provider overrides to file:", "file", providerOverrideFileName, "component", component, "stack", stack)

Also applies to: 105-105, 114-114, 122-122


259-262: Consider using a helper function for error handling.

The error handling pattern is repeated in multiple places. Consider extracting it into a helper function.

Create a helper function:

func handleTerraformError(p *tea.Program, spinnerDone chan struct{}, message string, err error, component string, stack string) {
    p.Quit()
    <-spinnerDone
    fmt.Printf("\r✗ %s\n", message)
    l.Error("Terraform operation failed", "component", component, "stack", stack, "error", err)
    os.Exit(1)
}

Then use it in all three places:

-p.Quit()
-<-spinnerDone
-fmt.Printf("\r✗ %s\n", message)
-l.Error("Failed to describe the component", "component", component, "stack", stack, "error", err)
-os.Exit(1)
+handleTerraformError(p, spinnerDone, message, err, component, stack)

Also applies to: 270-273, 286-289

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 317ff02 and 2c02448.

📒 Files selected for processing (1)
  • internal/exec/terraform_outputs.go (16 hunks)
🧰 Additional context used
🪛 GitHub Check: Build (macos-latest, macos)
internal/exec/terraform_outputs.go

[failure] 236-236:
undefined: l.Trace


[failure] 319-319:
undefined: u.Exit

🪛 GitHub Check: Build (ubuntu-latest, linux)
internal/exec/terraform_outputs.go

[failure] 236-236:
undefined: l.Trace


[failure] 319-319:
undefined: u.Exit

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (2)
internal/exec/terraform_outputs.go (2)

6-6: LGTM! Good choice of logging package.

The addition of os package and structured logging using github.com/charmbracelet/log aligns well with modern logging practices.

Also applies to: 17-17


136-136: Verify TF_DATA_DIR handling in cleanTerraformWorkspace.

As per PR objectives, this change should handle TF_DATA_DIR environment variable.

Let's verify the implementation:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check if cleanTerraformWorkspace handles TF_DATA_DIR

# Search for TF_DATA_DIR handling
rg -A 5 "TF_DATA_DIR" .

# Check cleanTerraformWorkspace implementation
ast-grep --pattern 'func cleanTerraformWorkspace($_, $_) {
  $$$
}'

Length of output: 8195


TF_DATA_DIR handling in cleanTerraformWorkspace verified

The cleanTerraformWorkspace function (in internal/exec/terraform_utils.go, lines 27–70) retrieves TF_DATA_DIR via os.Getenv, defaults to ".terraform" when empty, and then normalizes the path as expected. This satisfies the PR objective regarding TF_DATA_DIR handling.

err,
))
l.Error("Error evaluating terraform output", "output", output, "component", component, "stack", stack, "error", err)
u.Exit(1)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined u.Exit function.

The static analysis indicates that u.Exit is undefined.

Replace with the standard os.Exit:

-u.Exit(1)
+os.Exit(1)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
u.Exit(1)
os.Exit(1)
🧰 Tools
🪛 GitHub Check: Build (macos-latest, macos)

[failure] 319-319:
undefined: u.Exit

🪛 GitHub Check: Build (ubuntu-latest, linux)

[failure] 319-319:
undefined: u.Exit

@@ -235,7 +233,7 @@
if !CheckTTYSupport() {
// set tea.WithInput(nil) workaround tea program not run on not TTY mod issue
opts = []tea.ProgramOption{tea.WithoutRenderer(), tea.WithInput(nil)}
u.LogTrace("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.")
l.Trace("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined l.Trace method.

The static analysis indicates that l.Trace is undefined.

Replace with the correct logging level:

-l.Trace("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.")
+l.Debug("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
l.Trace("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.")
l.Debug("No TTY detected. Falling back to basic output. This can happen when no terminal is attached or when commands are pipelined.")
🧰 Tools
🪛 GitHub Check: Build (macos-latest, macos)

[failure] 236-236:
undefined: l.Trace

🪛 GitHub Check: Build (ubuntu-latest, linux)

[failure] 236-236:
undefined: l.Trace

@aknysh aknysh marked this pull request as draft February 8, 2025 13:53
Comment on lines +260 to +261
l.Error("Failed to describe the component", "component", component, "stack", stack, "error", err)
os.Exit(1)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
l.Error("Failed to describe the component", "component", component, "stack", stack, "error", err)
os.Exit(1)
l.Fatal("Failed to describe the component", "component", component, "stack", stack, "error", err)

Comment on lines +271 to +272
l.Error("Failed to get remote state backend static type outputs", "error", err)
os.Exit(1)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
l.Error("Failed to get remote state backend static type outputs", "error", err)
os.Exit(1)
l.Fatal("Failed to get remote state backend static type outputs", "error", err)

Comment on lines +287 to +288
l.Error("Failed to execute terraform output", "component", component, "stack", stack, "error", err)
os.Exit(1)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
l.Error("Failed to execute terraform output", "component", component, "stack", stack, "error", err)
os.Exit(1)
l.Fatal("Failed to execute terraform output", "component", component, "stack", stack, "error", err)

Comment on lines +318 to +319
l.Error("Error evaluating terraform output", "output", output, "component", component, "stack", stack, "error", err)
u.Exit(1)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
l.Error("Error evaluating terraform output", "output", output, "component", component, "stack", stack, "error", err)
u.Exit(1)
l.Fatal("Error evaluating terraform output", "output", output, "component", component, "stack", stack, "error", err)

Comment on lines +339 to +340
l.Error("Error evaluating the 'static' remote state backend output", "output", output, "component", component, "stack", stack, "error", err)
os.Exit(1)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
l.Error("Error evaluating the 'static' remote state backend output", "output", output, "component", component, "stack", stack, "error", err)
os.Exit(1)
l.Fatal("Error evaluating the 'static' remote state backend output", "output", output, "component", component, "stack", stack, "error", err)

@aknysh aknysh closed this in #1038 Feb 10, 2025
@mergify mergify bot removed the triage Needs triage label Feb 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants