Skip to content

[WIP] Stacks RFC: values with dependencies #4056

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

cgetzen
Copy link

@cgetzen cgetzen commented Mar 20, 2025

Description

Easily pass values between unit definitions from the terragrunt.stack.hcl file while maintaining backwards compatibility with units.

Context:

  • Original Request: Now that stacks can create multiple instances of a single unit, should the coupling of implementation details with units be revisited? It feels at odds with the stack concept of dynamically setting up units.
  • Response: Can you think of a way to define dependencies for units inside the terragrunt.stack.hcl file that doesn't break this?
  • Solution Description: Continue to use the values file interface.

This PR implements the following format:

# terragrunt.stack.hcl

unit "dep" {
  source = "modules/imadep"
  path   = "imadep"
  mock_outputs = {
    output_b = "mock_b"
  }
}

unit "test" {
  source = "modules/test"
  path   = "test"
  values = {
    a = "a"
    b = unit.dep.output_b
  }
}


# .terragrunt-stack/test/terragrunt.values.hcl (auto-generated)

values {
    a = "a"
    b = dependency.dep.outputs.output_b
}

dependency "dep" {
  config_path   = "../imadep"
  mock_values = {
    output_b = "mock_b"
  }
}

Before merging:

  • Confirm that this behavior is in line with the Stacks RFC vision
  • Handle all error cases
  • Ensure performance is not degraded

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Added / Removed / Updated [X].

Migration Guide

Summary by CodeRabbit

  • New Features
    • Improved configuration block handling with dynamic label assignment for better clarity and error messaging.
    • Enhanced stack processing with refined dependency resolution and support for unit reference tracking for a more robust configuration experience.

Copy link

vercel bot commented Mar 20, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 26, 2025 9:50pm

Copy link
Contributor

coderabbitai bot commented Mar 20, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

The changes update label assignment and error handling in the Blocks method of the file parsing module and extend stack processing functionality. In the file parser, label names are dynamically set based on the block type, and error reporting for multiple blocks is simplified. In the stack module, a new field and struct are introduced to handle raw unit values and unit references. Function signatures are updated in several core routines to pass unit lists and local maps, enabling improved dependency resolution during configuration parsing.

Changes

File Path Change Summary
config/hclparse/file.go Updated the Blocks method in the File struct to dynamically assign label names for blocks ("dependency" sets {"name"}, "values" yields an empty slice, default sets {"name"}) and to incorporate the label names into the catalog schema. Error handling simplified by returning errors directly.
config/stack.go Added RawValues field in the Unit struct and introduced a new UnitReference struct. Modified function signatures in processComponent, writeValues, ReadValues, and processLocals to include parameters for unit lists and locals. Enhanced dependency block processing within ReadValues.

Sequence Diagram(s)

sequenceDiagram
    participant T as Stack Processor
    participant GU as generateUnits/Stacks
    participant PC as processComponent
    participant WV as writeValues
    participant RV as ReadValues
    participant U as Unit (with RawValues)

    T->>GU: Initiate stack processing (with list of units)
    GU->>PC: Process component with allUnits parameter
    PC->>U: Resolve unit references via UnitReference
    PC->>WV: Forward component data and unit list
    WV->>RV: Trigger writing to terragrunt.values.hcl
    RV->>U: Retrieve raw expressions using RawValues
    RV-->>T: Return evaluation context with resolved dependencies
Loading

Suggested reviewers

  • levkohimins
  • yhakbar

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai 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 (6)
config/hclparse/file.go (2)

78-88: Consider adjusting the switch block layout for clarity.

The static analysis tool flags the cuddling of the switch statement with the variable declaration. Although this is purely style-related, separating the variable declaration from the switch statement can improve readability:

-	var labelNames []string
-	switch name {
+	var labelNames []string

+	switch name {
    ...
}
🧰 Tools
🪛 golangci-lint (1.64.8)

79-79: switch statements should only be cuddled with variables switched

(wsl)


115-115: Consider using fmt.Errorf for concise error creation.

Instead of wrapping fmt.Sprintf inside errors.New, you can use fmt.Errorf directly:

-return nil, errors.New(fmt.Sprintf(multipleBlockDetailFmt, name))
+return nil, fmt.Errorf(multipleBlockDetailFmt, name)
config/stack.go (4)

229-238: Pre-allocate the units slice.

Since you know the length of stacks, you can optimize by pre-allocating:

-	var units []*Unit
+	units := make([]*Unit, 0, len(stacks))

for _, stack := range stacks {
    ...
}
🧰 Tools
🪛 golangci-lint (1.64.8)

230-230: Consider pre-allocating units

(prealloc)


274-274: Remove or utilize the new units field in componentToProcess.

This field is overshadowed by the allUnits parameter passed to processComponent. If you only need allUnits, the struct field can be removed to prevent confusion.

🧰 Tools
🪛 golangci-lint (1.64.8)

274-274: field units is unused

(unused)


389-400: Pass context more thoroughly if possible.

The static analysis tool hints that deeper calls (e.g., getOutputJSONWithCaching) might also need the context. Consider refactoring those calls to ensure they honor cancellation and deadlines.

🧰 Tools
🪛 golangci-lint (1.64.8)

389-389: Function getOutputJSONWithCaching->getTerragruntOutputJSON->cloneTerragruntOptionsForDependencyOutput->PartialParseConfigFile should pass the context parameter

(contextcheck)


390-390: only one cuddle assignment allowed before if statement

(wsl)


644-754: Consider further splitting or validating user expressions.

While the current approach for writing values and dependencies works well, you may want to:

  1. Split this function for better maintainability.
  2. Add guards or explicit checks for malicious inputs that might embed unexpected HCL code.

Otherwise, the logic is coherent and addresses the new requirement for unit dependencies.

🧰 Tools
🪛 golangci-lint (1.64.8)

716-716: assignments should only be cuddled with other assignments

(wsl)


728-728: branch statements should not be cuddled if block has more than two lines

(wsl)


686-686: ranges should only be cuddled with assignments used in the iteration

(wsl)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c715f9 and bd856a5.

📒 Files selected for processing (2)
  • config/hclparse/file.go (2 hunks)
  • config/stack.go (11 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • config/hclparse/file.go
  • config/stack.go
🧬 Code Definitions (1)
config/stack.go (7)
config/locals.go (6) (6)
  • err (59-59)
  • err (249-251)
  • err (253-255)
  • err (259-261)
  • _ (170-170)
  • diags (162-162)
config/parsing_context.go (9) (9)
  • ctx (63-66)
  • ctx (68-71)
  • ctx (73-76)
  • ctx (78-81)
  • ctx (84-88)
  • ctx (90-93)
  • ctx (95-98)
  • NewParsingContext (54-62)
  • ParsingContext (16-52)
options/options.go (13) (13)
  • opts (585-593)
  • opts (597-602)
  • opts (606-618)
  • opts (647-670)
  • opts (673-675)
  • opts (678-684)
  • opts (688-695)
  • opts (698-729)
  • opts (732-743)
  • opts (746-758)
  • opts (805-865)
  • opts (867-885)
  • TerragruntOptions (91-410)
config/config.go (5) (5)
  • configPath (667-667)
  • file (805-805)
  • DefaultTerragruntConfigPath (44-44)
  • config (776-776)
  • config (1021-1021)
config/hclparse/file.go (7) (7)
  • file (23-25)
  • file (28-52)
  • file (61-74)
  • file (77-119)
  • file (121-135)
  • file (137-139)
  • File (17-21)
config/config_helpers.go (1) (1)
  • createTerragruntEvalContext (145-228)
config/stack_validation.go (1) (1)
  • ValidateStackConfig (16-37)
🪛 golangci-lint (1.64.8)
config/hclparse/file.go

79-79: switch statements should only be cuddled with variables switched

(wsl)

config/stack.go

230-230: Consider pre-allocating units

(prealloc)


274-274: field units is unused

(unused)


389-389: Function getOutputJSONWithCaching->getTerragruntOutputJSON->cloneTerragruntOptionsForDependencyOutput->PartialParseConfigFile should pass the context parameter

(contextcheck)


461-461: Function getOutputJSONWithCaching->getTerragruntOutputJSON->cloneTerragruntOptionsForDependencyOutput->PartialParseConfigFile should pass the context parameter

(contextcheck)


511-511: assignments should only be cuddled with other assignments

(wsl)


516-516: return statements should not be cuddled if block has more than two lines

(wsl)


390-390: only one cuddle assignment allowed before if statement

(wsl)


553-553: type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors

(errorlint)


585-585: ranges should only be cuddled with assignments used in the iteration

(wsl)


603-603: assignments should only be cuddled with other assignments

(wsl)


594-594: ranges should only be cuddled with assignments used in the iteration

(wsl)


716-716: assignments should only be cuddled with other assignments

(wsl)


728-728: branch statements should not be cuddled if block has more than two lines

(wsl)


686-686: ranges should only be cuddled with assignments used in the iteration

(wsl)

🔇 Additional comments (10)
config/hclparse/file.go (1)

91-94: Looks good.

The dynamic assignment of Type and LabelNames aligns well with the rest of the code.

config/stack.go (9)

13-13: No issues with the additional import.

Adding "github.com/hashicorp/hcl/v2" for extended HCL usage is appropriate here.


45-49: Struct changes look good.

The RawValues field provides a place to store original expressions for each unit. Make sure it’s only used internally and handled carefully if user input can contain dangerous expressions.


60-64: Evaluate necessity of UnitReference struct.

Currently, UnitReference appears unused in this diff. If it's part of a planned feature, leaving it in is fine; otherwise, consider removing it to avoid dead code.


216-216: No concerns with passing units into processComponent.

This aligns with the new signature for improved dependency resolution.


277-277: Signature update is valid.

Accepting allUnits in processComponent ensures correct handling of references and dependencies.


402-516: Logic for reading stack values looks solid.

This correctly merges dependency outputs and the main values block. No immediate concerns.

🧰 Tools
🪛 golangci-lint (1.64.8)

461-461: Function getOutputJSONWithCaching->getTerragruntOutputJSON->cloneTerragruntOptionsForDependencyOutput->PartialParseConfigFile should pass the context parameter

(contextcheck)


511-511: assignments should only be cuddled with other assignments

(wsl)


516-516: return statements should not be cuddled if block has more than two lines

(wsl)


537-568: Locals processing is properly integrated.

Forwarding an empty map and decoding with the existing logic appears consistent with how the rest of the file handles locals.

🧰 Tools
🪛 golangci-lint (1.64.8)

553-553: type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors

(errorlint)


570-614: Raw expression extraction is handled properly.

Storing user-supplied expressions in RawValues is fine as implemented, assuming all usage is validated. This ensures references can be reconstructed accurately.

🧰 Tools
🪛 golangci-lint (1.64.8)

585-585: ranges should only be cuddled with assignments used in the iteration

(wsl)


603-603: assignments should only be cuddled with other assignments

(wsl)


594-594: ranges should only be cuddled with assignments used in the iteration

(wsl)


624-641: Relative path calculation is correct.

Using filepath.Abs and filepath.Rel is a standard approach for safe relative path derivation.

@yhakbar
Copy link
Collaborator

yhakbar commented Mar 21, 2025

Thanks for submitting this PoC, @cgetzen . It's a neat idea!

Please create an RFC following our GitHub issues based process so we can get more details on the design thought process, think through alternatives, etc. Make sure you link this PoC to it. It really helps to have something like this to understand how the implementation would work.

Regarding the design as-is: I don't think it would be a good idea to have dependencies in terragrunt.values.hcl files. They are intended to be flat, simple HCL attributes, making them easy to parse and work with. When you submit the RFC, I would encourage you to update the design to perhaps leverage a separate terragrunt.dependencies.hcl file or something (to be clear, I'm not saying that we'd accept a proposal that did that, I'm just saying it would be a preferred alternative to overloading the terragrunt.values.hcl file).

I'd also like to get a better understanding of the edge cases in this proposal: What if two dependencies are named the same thing across these different files? What's the behavior? Can the terragrunt.hcl file make reference to them? Are there any alternative designs that you think would work just as well? How are mock outputs handled?

@yhakbar yhakbar marked this pull request as draft March 21, 2025 14:04
This was referenced Mar 21, 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