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

Update Atmos YAML functions #1038

Merged
merged 28 commits into from
Feb 10, 2025
Merged

Update Atmos YAML functions #1038

merged 28 commits into from
Feb 10, 2025

Conversation

aknysh
Copy link
Member

@aknysh aknysh commented Feb 8, 2025

what

  • Handle environment variables (set in the env section) when running !terraform.output and atmos.Component
  • If TF_DATA_DIR environment variable is set, clear the correct environment folder when reseting Terraform workspaces
  • Additional logging for handling errors in terraform output
  • Refactor the spinner logic

why

  • If the component referred in !terraform.output and atmos.Component functions sets environment variables (in the env section), set the environment variables in the process running !terraform.output and atmos.Component functions
  • Correctly handle the TF_DATA_DIR environment variable when reseting Terraform workspaces in the !terraform.output and atmos.Component functions
  • Additional logging for debugging
  • Refactor the spinner logic - separate the spinner logic into reusable functions so it can be used in many commands

related

Summary by CodeRabbit

Summary by CodeRabbit

  • Chores

    • Updated the core Docker image and dependency versions for improved compatibility.
  • New Features

    • Introduced a revamped progress spinner that delivers clearer, more reliable feedback during operations.
    • Added new environment variables to enhance configuration options for testing.
    • Included an environment variable to control logging levels during test executions.
  • Refactor

    • Enhanced error logging and environment management in Terraform workflows, contributing to greater stability and easier troubleshooting.
    • Improved utility functions for better type handling and clarity in code.

@aknysh aknysh added the patch A minor, backward compatible change label Feb 8, 2025
@aknysh aknysh self-assigned this Feb 8, 2025
Copy link

mergify bot commented Feb 8, 2025

Important

Cloud Posse Engineering Team Review Required

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

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

@mergify mergify bot added the needs-cloudposse Needs Cloud Posse assistance label Feb 8, 2025
aknysh and others added 2 commits February 8, 2025 22:43
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 9, 2025
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 9, 2025
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 9, 2025
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 9, 2025
@aknysh aknysh marked this pull request as ready for review February 10, 2025 04:01
@aknysh aknysh requested a review from a team as a code owner February 10, 2025 04:01
Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

📝 Walkthrough

Walkthrough

This change updates version numbers in the Dockerfile and go.mod, introduces new spinner management functions, and refactors spinner usage in the validate stacks command. It also improves environment variable handling and logging in Terraform outputs and workspace cleanup, and adds a new environment variable section in a YAML configuration file.

Changes

File(s) Change Summary
examples/quick-start-advanced/Dockerfile, go.mod Updated GEODESIC version from 3.4.0 to 4.0.1 in the Dockerfile and bumped the bubblezone dependency in go.mod to a newer version.
internal/exec/spinner_utils.go, internal/exec/validate_stacks.go Introduced new spinner management functions (NewSpinner, RunSpinner, StopSpinner) and refactored spinner usage in the ExecuteValidateStacksCmd implementation.
internal/exec/terraform_outputs.go, internal/exec/terraform_utils.go Enhanced environment variable handling and logging; improved workspace file deletion checks and standardized logging messages.
tests/.../terraform/template-functions-test/defaults.yaml Added new environment variables (TEST1: a and TEST2: b) to the settings configuration.
tests/test-cases/atmos-functions.yaml Introduced environment variable ATMOS_LOGS_LEVEL set to Debug in test cases related to the Terraform output function.

Sequence Diagram(s)

sequenceDiagram
    participant Cmd as ExecuteValidateStacksCmd
    participant SpinnerUtil as SpinnerUtils
    participant TeaProg as tea.Program

    Cmd->>SpinnerUtil: NewSpinner(message)
    SpinnerUtil-->>Cmd: spinner instance
    Cmd->>SpinnerUtil: RunSpinner(spinner, spinnerChan, message)
    par Spinner Running...
        TeaProg-->>SpinnerUtil: Spinner active
    end
    Cmd->>SpinnerUtil: StopSpinner(spinner, spinnerChan)
    SpinnerUtil-->>Cmd: Spinner stopped
Loading

Possibly related PRs

  • feat: add spinner during atmos validate stacks operations #1005: The changes in the main PR, which involve updating the spinner management in the internal/exec/validate_stacks.go file, are directly related to the modifications made in the retrieved PR that also enhance the spinner functionality within the same function.

Suggested labels

minor

Suggested reviewers

  • osterman
✨ 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.

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 (2)
internal/exec/spinner_utils.go (1)

65-75: Consider adding context for cancellation.

While the current implementation is solid, consider adding context support for better control over spinner lifecycle.

-func RunSpinner(p *tea.Program, spinnerChan chan struct{}, message string) {
+func RunSpinner(ctx context.Context, p *tea.Program, spinnerChan chan struct{}, message string) {
 	go func() {
 		defer close(spinnerChan)
+		done := make(chan error, 1)
+		go func() {
+			_, err := p.Run()
+			done <- err
+		}()
+		
+		select {
+		case <-ctx.Done():
+			p.Quit()
+			<-done
+		case err := <-done:
+			if err != nil {
+				fmt.Println(message)
+				l.Error("Failed to run spinner:", "error", err)
+			}
+		}
-		if _, err := p.Run(); err != nil {
-			fmt.Println(message)
-			l.Error("Failed to run spinner:", "error", err)
-		}
 	}()
}
internal/exec/terraform_outputs.go (1)

234-250: Consider using defer for environment cleanup.

While the current implementation works, using defer would ensure cleanup even in case of early returns.

 func execTerraformOutput(...) (map[string]any, error) {
 	outputProcessed := map[string]any{}
 	envVarsSaved := make(map[string]any)
+	defer func() {
+		for k, v := range envVarsSaved {
+			if v != nil {
+				vStr := fmt.Sprint(v)
+				l.Debug(fmt.Sprintf("Restoring environment variable %s=%s", k, vStr))
+				_ = os.Setenv(k, fmt.Sprintf("%v", vStr))
+			} else {
+				l.Debug(fmt.Sprintf("Unsetting environment variable %s", k))
+				_ = os.Unsetenv(k)
+			}
+		}
+	}()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e7897bf and 7696cd4.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • examples/quick-start-advanced/Dockerfile (1 hunks)
  • go.mod (1 hunks)
  • internal/exec/spinner_utils.go (2 hunks)
  • internal/exec/terraform_outputs.go (12 hunks)
  • internal/exec/terraform_utils.go (4 hunks)
  • internal/exec/validate_stacks.go (1 hunks)
  • tests/fixtures/scenarios/complete/stacks/catalog/terraform/template-functions-test/defaults.yaml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • go.mod
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Acceptance Tests (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (10)
internal/exec/spinner_utils.go (2)

44-63: LGTM! Well-structured spinner initialization.

The function handles both TTY and non-TTY environments gracefully, with proper error handling and logging.


77-81: LGTM! Clean spinner termination.

The function properly handles spinner cleanup and waits for completion.

internal/exec/terraform_utils.go (3)

29-42: LGTM! Robust environment variable handling.

The code properly handles TF_DATA_DIR environment variable with appropriate fallback to .terraform.


43-44: LGTM! Safe file path construction.

Using filepath.Join and filepath.Clean ensures safe and platform-independent path handling.


46-59: LGTM! Comprehensive error handling and logging.

The code properly checks file existence and handles all possible error cases with appropriate logging.

internal/exec/terraform_outputs.go (2)

53-79: LGTM! Thorough environment variable management.

The code properly saves, sets, and restores environment variables, ensuring clean process environment.


275-283: LGTM! Clean spinner implementation.

The code properly initializes and manages spinner lifecycle with appropriate logging level checks.

internal/exec/validate_stacks.go (1)

31-37: LGTM! Clean spinner integration.

The code properly uses the new spinner utilities with appropriate cleanup using defer.

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

2-2: Update Geodesic Version.
The GEODESIC_VERSION is now set to 4.0.1, which aligns with the new tool improvements. Please verify that the new version is fully compatible with your build and runtime environments, as this change could introduce differences in behavior.

tests/fixtures/scenarios/complete/stacks/catalog/terraform/template-functions-test/defaults.yaml (1)

35-37: New Environment Variables Added.
The addition of the env section with TEST1: a and TEST2: b is a clear step towards enhancing configuration management for the testing environment. Confirm that downstream components correctly reference these variables during execution.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 10, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 10, 2025
Copy link
Member

@osterman osterman left a comment

Choose a reason for hiding this comment

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

Wait, I don't understand why we are manipulating the env of the patent process, when exec can set it for the child process.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 10, 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 (3)
pkg/utils/map_utils.go (1)

45-55: Consider adding error handling for non-string keys.

The function silently skips keys that can't be converted to strings. Consider either:

  1. Returning an error when non-string keys are encountered
  2. Adding logging to track skipped keys
 func MapOfInterfaceKeysToMapOfStringKeys(input map[any]any) map[string]any {
 	converted := make(map[string]any, len(input))
 	for key, value := range input {
 		strKey, ok := key.(string)
-		if ok {
-			converted[strKey] = value
-		}
+		if !ok {
+			l.Debug("Skipping non-string key", "key", key)
+			continue
+		}
+		converted[strKey] = value
 	}
 	return converted
 }
internal/exec/terraform_outputs.go (2)

189-190: Consider using consistent error logging format.

The error logging format varies between lines 189 and 202. Standardize on the structured format:

-				l.Error("Error converting output to YAML:", "error", err2)
+				l.Error("failed to convert output to YAML", "error", err2)

Also applies to: 202-203


197-198: Consider using consistent debug logging format.

The debug logging format varies between using fmt.Sprintf and structured logging. Standardize on the structured format:

-			l.Debug(fmt.Sprintf("Converting the variable '%s' with the value\n%s\nfrom JSON to Go data type\n", k, s))
+			l.Debug("Converting variable from JSON to Go data type", "key", k, "value", s)

Also applies to: 205-206

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44d0f4c and 87821f2.

📒 Files selected for processing (2)
  • internal/exec/terraform_outputs.go (10 hunks)
  • pkg/utils/map_utils.go (2 hunks)
🧰 Additional context used
📓 Learnings (1)
internal/exec/terraform_outputs.go (1)
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.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (3)
pkg/utils/map_utils.go (1)

38-43: LGTM! Clean and efficient implementation.

The function efficiently uses lo.MapEntries for map transformation and properly handles string conversion using fmt.Sprintf.

internal/exec/terraform_outputs.go (2)

128-140: LGTM! Well-implemented environment variables handling.

The code properly:

  • Checks for the existence of the env section
  • Converts environment variables to the correct format
  • Sets them in the Terraform executor
  • Includes debug logging

241-249: LGTM! Clean spinner implementation.

The spinner implementation:

  • Properly initializes and cleans up resources
  • Only shows spinner for appropriate log levels
  • Uses defer for guaranteed cleanup

@aknysh aknysh requested a review from osterman February 10, 2025 05:46
Copy link
Member

@osterman osterman left a comment

Choose a reason for hiding this comment

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

LGTM

@aknysh aknysh merged commit ccb55ec into main Feb 10, 2025
44 checks passed
@aknysh aknysh deleted the update-yaml-funcs-4 branch February 10, 2025 13:26
@mergify mergify bot removed the needs-cloudposse Needs Cloud Posse assistance label Feb 10, 2025
Copy link

These changes were released in v1.160.3.

Cerebrovinny added a commit that referenced this pull request Feb 10, 2025
* updates

* updates

* updates

* updates

* updates

* updates

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* Update internal/exec/terraform_outputs.go

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

---------

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
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.")
fmt.Println(message)
if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug {
Copy link
Member

Choose a reason for hiding this comment

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

This conditional does not belong here. It undoes the feature here: #947

p.Quit()
<-spinnerDone
fmt.Printf("\r✓ %s\n", message)
if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug {
Copy link
Member

Choose a reason for hiding this comment

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

This conditional does not belong here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
patch A minor, backward compatible change
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants