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

feat: TF_CLI_ARGS_* Handling #898

Merged
merged 19 commits into from
Jan 7, 2025
Merged

feat: TF_CLI_ARGS_* Handling #898

merged 19 commits into from
Jan 7, 2025

Conversation

milldr
Copy link
Member

@milldr milldr commented Dec 27, 2024

what

  • Added logic and warning messages when the user specifies any TF_CLI_* environment variable, since this may conflict with Atmos behavior.
  • Added to 2 places: terraform shell and to any terraform command, since these are handled separately
  • Append any TF_CLI env vars to the determined TF_CLI env var for terraform shell

why

  • When executing Terraform Shell, we should append generate var file to the (if) specified env var rather than overwriting it
  • When executing Terraform, var files are already appended (merged). We should add a warning nonetheless

references

atmos terraform shell

2025-01-02 18 37 16

atmos terraform plan

2025-01-02 18 36 15

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced logging to alert users about potential conflicts with Terraform environment variables.
    • Improved handling of -var-file arguments to respect existing configurations.
    • Introduced a new function for merging environment variables, ensuring Atmos-specific variables take precedence.
  • Bug Fixes

    • Enhanced management of Terraform command-line arguments to prevent unintentional overwriting of variable files.

@mergify mergify bot added the triage Needs triage label Dec 27, 2024
@milldr milldr added minor New features that do not break anything and removed triage Needs triage labels Dec 27, 2024
@milldr milldr marked this pull request as ready for review December 27, 2024 15:15
@milldr milldr requested a review from a team as a code owner December 27, 2024 15:15
Copy link
Contributor

coderabbitai bot commented Dec 27, 2024

📝 Walkthrough

Walkthrough

The pull request modifies the handling of Terraform command-line arguments and environment variables within the Atmos shell utility functions. It introduces a structured approach to manage -var-file arguments and implements a warning system for existing environment variables. The changes ensure that existing configurations are respected, preventing unintentional overwrites and enhancing logging for potential conflicts with Terraform-related environment variables.

Changes

File Change Summary
internal/exec/shell_utils.go Updated execTerraformShellCommand to improve handling of -var-file arguments for Terraform commands. Added mergeEnvVars function.
internal/exec/terraform.go Introduced logging for environment variables starting with TF_ to warn users about potential conflicts.

Assessment against linked issues

Objective Addressed Explanation
Warn about TF_CLI_ env variable replacement [DEV-2793]
Append to existing environment variables instead of replacing

Possibly related PRs

Suggested reviewers

  • Gowiem
  • osterman

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4587133 and accde7a.

📒 Files selected for processing (1)
  • internal/exec/shell_utils.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Acceptance Tests (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (4)
internal/exec/shell_utils.go (4)

230-234: LGTM! Clean and efficient implementation.

The code efficiently handles Terraform commands that require var-file configuration. The slice-based approach makes it easy to maintain and extend the list of commands.


271-272: LGTM! Proper environment variable handling.

The code correctly uses mergeEnvVars to ensure that component environment variables take precedence while preserving system environment variables.

Also applies to: 278-278


359-367: Consider handling quoted values in TF_CLI_ARGS_ variables.*

The current implementation assumes space-separated values, but TF_CLI_ARGS_* variables might contain quoted values. Consider adding special handling for quoted arguments.

Run this script to check for potential issues with quoted values:


336-382: Consider adding unit tests for environment variable merging.

The mergeEnvVars function handles complex environment variable merging logic, especially for TF_CLI_ARGS_* variables. While the implementation looks solid, it would benefit from comprehensive unit tests to verify the behavior of:

  1. System environment variable preservation
  2. Atmos-specific variable precedence
  3. TF_CLI_ARGS_* variable merging

Would you like me to help generate unit tests for this function?

Here's a script to verify the current test coverage:

✅ Verification successful

Unit tests needed for environment variable merging - No existing tests found 💪

The verification confirms there are no existing tests in the internal/exec package. Given the critical nature of environment variable handling, especially for Terraform CLI arguments, adding comprehensive tests is indeed important for reliability.

  • No test file exists at internal/exec/shell_utils_test.go
  • No environment-related tests found in the package

I can help create unit tests that cover:

  1. System environment preservation
  2. Atmos variable precedence
  3. TF_CLI_ARGS_* merging logic
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any existing tests for mergeEnvVars
rg -l "func.*Test.*mergeEnvVars" 

# Look for any existing environment variable related tests
rg -l "os\.Setenv.*TF_CLI_ARGS" 

Length of output: 68


Script:

#!/bin/bash
# Find all test files in the internal/exec directory
fd ".*_test\.go$" internal/exec/

# Look for any test functions that deal with environment variables
rg -l "func.*Test.*Env" internal/exec/

# Look for environment-related test utilities
rg -l "test.*env" -t go internal/exec/

# Check if there's any existing test infrastructure
cat internal/exec/shell_utils_test.go 2>/dev/null || echo "File not found"

Length of output: 224


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

262-264: Catching var-file collisions in component environment ensures thorough coverage.
These lines do a great job of warning users when environment-level settings might be overridden.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1aa75c6 and 42c3026.

📒 Files selected for processing (2)
  • internal/exec/shell_utils.go (1 hunks)
  • internal/exec/terraform.go (1 hunks)
🔇 Additional comments (4)
internal/exec/shell_utils.go (3)

188-190: Neat definition of terraform commands.
This approach centralizes the commands that may require var-file handling, simplifying future maintenance and extension.


191-197: Clear warning message for potential collisions.
It is helpful to log a warning whenever these TF_CLI_ARGS variables contain a “-var-file” argument, reducing user confusion.


198-200: Appending the var file reference to each command is straightforward.
Ensure users understand that this logic overrides any existing “-var-file” specification at runtime.

internal/exec/terraform.go (1)

248-257: Collisions detection is consistent with shell_utils.
Capturing conflicts across both the shell and terraform commands maintains consistent user visibility.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 27, 2024
@osterman
Copy link
Member

osterman commented Dec 30, 2024

Here's the misunderstanding.

  1. execTerraformShellCommand is only called for atmos terraform shell (in your screenshots you're running other commands)
  2. The 5th argument is the var file.
  3. When running atmos terraform shell, it will squash the TF_CLI_ARG_* environment variables. Not just when we're passing a -var-file. E.g. Setting TF_CLI_ARG_plan=-non-existant-flag will break Terraform. Atmos warning that the ENV is set, will alert the user during debugging.

Here are the new requirements

  1. Anytime we execute terraform we should probably warn emit a warning if any of these variables are set, as it can change the deterministic behavior of atmos
  2. Modify execTerraformShellCommand so that it does not squash the values of TF_CLI_ARG_* and instead appends (with a space) to it.

internal/exec/terraform.go Outdated Show resolved Hide resolved
internal/exec/shell_utils.go Outdated Show resolved Hide resolved
internal/exec/terraform.go Outdated Show resolved Hide resolved
@milldr milldr changed the title feat: TF_CLI_ARGS_* Handling for -var-file feat: TF_CLI_ARGS_* Handling Jan 2, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 2, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 2, 2025
internal/exec/terraform.go Outdated Show resolved Hide resolved
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 3, 2025
internal/exec/shell_utils.go Outdated Show resolved Hide resolved
internal/exec/terraform.go Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 7, 2025
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 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/shell_utils.go (1)

356-385: Well-structured environment variable merging function!

The implementation is clean and handles the merging of environment variables effectively. However, consider adding error handling for malformed environment variables.

 func mergeEnvVars(baseEnv, overrideEnv []string) []string {
     envMap := make(map[string]string)
 
     // Parse base environment variables
     for _, env := range baseEnv {
         if parts := strings.SplitN(env, "=", 2); len(parts) == 2 {
             envMap[parts[0]] = parts[1]
+        } else {
+            // Log malformed environment variables
+            u.LogWarning(atmosConfig, fmt.Sprintf("Skipping malformed environment variable: %s", env))
         }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b8c2511 and 4587133.

📒 Files selected for processing (1)
  • internal/exec/shell_utils.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (3)
internal/exec/shell_utils.go (3)

281-283: Excellent use of environment variable merging!

The approach ensures that component-specific variables take precedence while preserving system environment variables.


290-298: Good debugging support!

The debug logging of merged environment variables helps with troubleshooting.


230-251: Strong approach to handling TF_CLI_ARGS!

The implementation correctly preserves existing TF_CLI_ARGS values while appending Atmos-specific var-file arguments. The warning message helps users understand potential conflicts.

However, consider adding validation for the existing arguments to prevent invalid combinations:

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 7, 2025
@milldr milldr merged commit 23507ab into main Jan 7, 2025
44 checks passed
@milldr milldr deleted the feat/DEV-2793_dont-squash-tfcli branch January 7, 2025 23:51
Copy link

github-actions bot commented Jan 8, 2025

These changes were released in v1.139.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.

3 participants