Skip to content

fix: pass extra_args when fetching dependencies outputs #4416

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

head-gardener
Copy link

@head-gardener head-gardener commented Jun 13, 2025

Description

Fixes #2598.

TerragruntOptions.ExtraArgs isn't being included in the options being passed to tf.RunCommandWithOutput. In this PR I copied over the ExtraArgs logic from run.go and that fixed the issue.

The code from run.go can't be included directly because of a dependency cycle and I can't find a place to put it. Do you have any ideas? Also let me now if there is any documentation I can/need to update and if you want a test for this specific case.

TODOs

Read the Gruntwork contribution guidelines.

  • I authored this code entirely myself
  • I am submitting code based on open source software (e.g. MIT, MPL-2.0, Apache)]
  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Include release notes. If this PR is backward incompatible, include a migration guide.
  • Move ExtraArgs logic somewhere.

Release Notes (draft)

Fix optimized output fetchers to use terraform:extra_arguments configuration

Migration Guide

If you had previously set disable_dependency_optimization to bypass this issue you may unset it now.

Summary by CodeRabbit

  • Refactor
    • Improved handling of Terraform command-line arguments and environment variables for dependencies, streamlining configuration management.
  • New Features
    • Enhanced support for custom Terraform CLI arguments and environment variables, with better filtering based on the specific command.
  • Bug Fixes
    • Resolved an issue where certain variable files could cause problems during apply or destroy commands.

Copy link

vercel bot commented Jun 13, 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 Jun 13, 2025 0:37am

Copy link
Contributor

coderabbitai bot commented Jun 13, 2025

📝 Walkthrough

Walkthrough

The code refactors dependency output retrieval functions to accept a unified *TerragruntConfig parameter instead of separate IAM role options. It introduces helper functions to correctly filter and merge Terraform CLI arguments and environment variables from extra_arguments, ensuring these are preserved when executing Terraform commands, including within dependency blocks.

Changes

Files / Grouped Files Change Summary
config/dependency.go Refactored functions to use *TerragruntConfig for IAM role and remote state options; added helpers for filtering/merging Terraform extra arguments and environment variables; updated logic to ensure proper propagation of env vars in dependency scenarios.
(standard library import) Added maps import for map copying functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant DependencyHandler
    participant TerragruntOptions
    participant TerragruntConfig

    Caller->>DependencyHandler: getTerragruntOutputJSON(ctx, logger, config)
    DependencyHandler->>TerragruntConfig: Access ExtraArgs and IAMRoleOptions
    DependencyHandler->>DependencyHandler: FilterTerraformExtraArgs(...)
    DependencyHandler->>DependencyHandler: filterTerraformEnvVarsFromExtraArgs(...)
    DependencyHandler->>TerragruntOptions: setupTerragruntOptionsForBareTerraform(...)
    TerragruntOptions->>DependencyHandler: Return options with merged CLI args and env vars
    DependencyHandler->>Caller: Return output JSON
Loading

Assessment against linked issues

Objective Addressed Explanation
Preserve and merge extra_arguments.env_vars correctly when dependency blocks are used (#2598)
Ensure environment variables from extra_arguments are applied for authentication in all dependency scenarios (#2598)
Evaluate and apply extra_arguments.env_vars regardless of dependency declaration, enabling context propagation (#2598)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this 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 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: 2

🧹 Nitpick comments (1)
config/dependency.go (1)

1139-1150: Order of CLI-argument insertion may override user flags

InsertTerraformCliArgs(args...) appends to the end of the existing slice.
If the original command already carried an explicit flag (e.g. -lock=false) the later append silently overrides earlier semantics. Consider detecting duplicates and preserving the user-supplied order/precedence.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27aeb16 and 3bd3062.

📒 Files selected for processing (1)
  • config/dependency.go (8 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/dependency.go
🔇 Additional comments (2)
config/dependency.go (2)

7-11: maps import requires Go ≥1.20 – double-check the tool-chain

The new standard-library package maps was introduced in Go 1.20.
Please ensure that:

  1. go.mod declares at least go 1.20.
  2. CI / build images are updated accordingly, otherwise builds will fail.

1153-1154: IAM-role precedence subtly changed

MergeIAMRoleOptions(targetConfig.GetIAMRoleOptions(), targetTGOptions.OriginalIAMRoleOptions) now gives config-file directives precedence over CLI. Historically CLI flags take priority. Confirm this reversal is intended; otherwise invert the parameters.

Comment on lines +1102 to +1119
func filterTerraformEnvVarsFromExtraArgs(terragruntOptions *options.TerragruntOptions, terragruntConfig *TerragruntConfig) map[string]string {
out := map[string]string{}
cmd := terragruntOptions.TerraformCliArgs.First()

for _, arg := range terragruntConfig.Terraform.ExtraArgs {
if arg.EnvVars == nil {
continue
}

for _, argcmd := range arg.Commands {
if cmd == argcmd {
maps.Copy(out, *arg.EnvVars)
}
}
}

return out
}
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

Potential panic: maps.Copy on a nil destination map

targetTGOptions.Env might be nil (common when TG is instantiated programmatically).
maps.Copy(dst, src) panics when dst is nil. Initialising the map fixes this.

 func filterTerraformEnvVarsFromExtraArgs(terragruntOptions *options.TerragruntOptions, terragruntConfig *TerragruntConfig) map[string]string {
-    out := map[string]string{}
+    out := make(map[string]string)

and in the caller (setupTerragruntOptionsForBareTerraform):

- maps.Copy(targetTGOptions.Env, filterTerraformEnvVarsFromExtraArgs(targetTGOptions, targetConfig))
+ if targetTGOptions.Env == nil {
+     targetTGOptions.Env = make(map[string]string)
+ }
+ maps.Copy(targetTGOptions.Env, filterTerraformEnvVarsFromExtraArgs(targetTGOptions, targetConfig))

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In config/dependency.go around lines 1102 to 1119, the function
filterTerraformEnvVarsFromExtraArgs initializes the destination map 'out'
correctly, but the caller function setupTerragruntOptionsForBareTerraform might
be passing a nil map to maps.Copy, causing a panic. To fix this, ensure that any
map passed as the destination to maps.Copy is properly initialized before the
call. Specifically, initialize targetTGOptions.Env as an empty map if it is nil
before copying environment variables into it.

Comment on lines +1062 to +1100
func FilterTerraformExtraArgs(l log.Logger, opts *options.TerragruntOptions, terragruntConfig *TerragruntConfig) []string {
out := []string{}
cmd := opts.TerraformCliArgs.First()

for _, arg := range terragruntConfig.Terraform.ExtraArgs {
for _, argCmd := range arg.Commands {
if cmd == argCmd {
lastArg := opts.TerraformCliArgs.Last()
skipVars := (cmd == tf.CommandNameApply || cmd == tf.CommandNameDestroy) && util.IsFile(lastArg)

// The following is a fix for GH-493.
// If the first argument is "apply" and the second argument is a file (plan),
// we don't add any -var-file to the command.
if arg.Arguments != nil {
if skipVars {
// If we have to skip vars, we need to iterate over all elements of array...
for _, a := range *arg.Arguments {
if !strings.HasPrefix(a, "-var") {
out = append(out, a)
}
}
} else {
// ... Otherwise, let's add all the arguments
out = append(out, *arg.Arguments...)
}
}

if !skipVars {
varFiles := arg.GetVarFiles(l)
for _, file := range varFiles {
out = append(out, "-var-file="+file)
}
}
}
}
}

return out
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Nil–safety & duplication in FilterTerraformExtraArgs

  1. terragruntConfig is dereferenced without a nil check; the helper is currently only called from a guarded site, but adding a check makes it future-proof.
  2. opts.TerraformCliArgs.First() / Last() can return an empty string when the slice is empty – guarding avoids misleading matches.
  3. Returned slice can contain duplicated flags when multiple extra_arguments blocks target the same command. Consider a map[string]struct{} to de-dup.
+ if terragruntConfig == nil || terragruntConfig.Terraform == nil {
+     return nil
+ }
  cmd := opts.TerraformCliArgs.First()
-           if cmd == argCmd {
+           if cmd != "" && cmd == argCmd {
📝 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
func FilterTerraformExtraArgs(l log.Logger, opts *options.TerragruntOptions, terragruntConfig *TerragruntConfig) []string {
out := []string{}
cmd := opts.TerraformCliArgs.First()
for _, arg := range terragruntConfig.Terraform.ExtraArgs {
for _, argCmd := range arg.Commands {
if cmd == argCmd {
lastArg := opts.TerraformCliArgs.Last()
skipVars := (cmd == tf.CommandNameApply || cmd == tf.CommandNameDestroy) && util.IsFile(lastArg)
// The following is a fix for GH-493.
// If the first argument is "apply" and the second argument is a file (plan),
// we don't add any -var-file to the command.
if arg.Arguments != nil {
if skipVars {
// If we have to skip vars, we need to iterate over all elements of array...
for _, a := range *arg.Arguments {
if !strings.HasPrefix(a, "-var") {
out = append(out, a)
}
}
} else {
// ... Otherwise, let's add all the arguments
out = append(out, *arg.Arguments...)
}
}
if !skipVars {
varFiles := arg.GetVarFiles(l)
for _, file := range varFiles {
out = append(out, "-var-file="+file)
}
}
}
}
}
return out
}
func FilterTerraformExtraArgs(l log.Logger, opts *options.TerragruntOptions, terragruntConfig *TerragruntConfig) []string {
// Nil‐safety: guard against future calls with a nil config or missing Terraform block
if terragruntConfig == nil || terragruntConfig.Terraform == nil {
return nil
}
out := []string{}
cmd := opts.TerraformCliArgs.First()
for _, arg := range terragruntConfig.Terraform.ExtraArgs {
for _, argCmd := range arg.Commands {
// Avoid matching on an empty cmd (First() can return "")
if cmd != "" && cmd == argCmd {
lastArg := opts.TerraformCliArgs.Last()
skipVars := (cmd == tf.CommandNameApply || cmd == tf.CommandNameDestroy) && util.IsFile(lastArg)
// The following is a fix for GH-493.
// If the first argument is "apply" and the second argument is a file (plan),
// we don't add any -var-file to the command.
if arg.Arguments != nil {
if skipVars {
// If we have to skip vars, we need to iterate over all elements of array...
for _, a := range *arg.Arguments {
if !strings.HasPrefix(a, "-var") {
out = append(out, a)
}
}
} else {
// ... Otherwise, let's add all the arguments
out = append(out, *arg.Arguments...)
}
}
if !skipVars {
varFiles := arg.GetVarFiles(l)
for _, file := range varFiles {
out = append(out, "-var-file="+file)
}
}
}
}
}
return out
}
🤖 Prompt for AI Agents
In config/dependency.go around lines 1062 to 1100, add a nil check for
terragruntConfig at the start of FilterTerraformExtraArgs to prevent
dereferencing nil. Also, check if opts.TerraformCliArgs.First() and Last()
return empty strings before using them to avoid incorrect matches. Finally,
replace the output slice with a map to track added arguments and prevent
duplicates, then convert the map keys back to a slice before returning.

@head-gardener
Copy link
Author

Regarding CodeRabbit and SonarCloud feedback: this code is copied verbatim from run.go, I need help figuring out where I can put it so that both run and config can access it. Otherwise the feedback isn't actionable

@yhakbar
Copy link
Collaborator

yhakbar commented Jun 13, 2025

Hey @head-gardener ,

I think this issue is going to take us a while to get to. There are a lot of implications to the subsystem that you're editing here, and we need to tread carefully to make sure we understand all the implications of this change. Please have patience with us.

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.

Terraform extra_arguments ENV Variables lost if dependency block is added
2 participants