terragrunt

package module
v2.0.0-beta.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

Terragrunt Module

Testing library for Terragrunt configurations in Go. Provides helpers for running Terragrunt commands for single units, across multiple modules (run-all), and stack-based workflows.

Requirements

  • Terragrunt binary in PATH
  • OpenTofu or Terraform binary in PATH (Terragrunt is a wrapper and requires one of these)

To specify which binary to use (terraform vs opentofu):

// Option 1: Via environment variable
options := &terragrunt.Options{
    TerragruntDir: "/path/to/config",
    EnvVars: map[string]string{
        "TERRAGRUNT_TFPATH": "/usr/local/bin/tofu",  // or "TG_TF_PATH"
    },
}

// Option 2: Via command-line flag
options := &terragrunt.Options{
    TerragruntDir:  "/path/to/config",
    TerragruntArgs: []string{"--tf-path", "/usr/local/bin/tofu"},
}

Quick Start

Single Unit
import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terragrunt/v2"
    "github.com/stretchr/testify/assert"
)

func TestSingleUnit(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../path/to/terragrunt/unit",
    }

    defer terragrunt.DestroyContext(t, ctx, options)
    terragrunt.InitAndApplyContext(t, ctx, options)

    // Get a specific output as JSON
    vpcOutput := terragrunt.OutputJSONContext(t, ctx, options, "vpc_id")
    assert.Contains(t, vpcOutput, "vpc-")
}
Multiple Modules (--all)
func TestTerragruntApply(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../path/to/terragrunt/config",
    }

    defer terragrunt.DestroyAllContext(t, ctx, options)
    terragrunt.ApplyAllContext(t, ctx, options)
}

Key Concepts

Options Struct

The Options struct has two distinct parts:

  1. Test Framework Configuration (NOT passed to terragrunt CLI):

    • TerragruntDir - where to run terragrunt (required)
    • TerragruntBinary - binary name (default: "terragrunt")
    • EnvVars - environment variables
    • Logger - custom logger for output
    • MaxRetries, TimeBetweenRetries - retry settings
    • RetryableTerraformErrors - map of error patterns to retry messages
    • WarningsAsErrors - map of warning patterns to treat as errors
    • BackendConfig - backend configuration passed to init
    • PluginDir - plugin directory passed to init
    • Stdin - stdin reader for commands
  2. Command-Line Arguments (passed to terragrunt):

    • TerragruntArgs - global terragrunt flags (e.g., --log-level, --no-color)
    • TerraformArgs - command-specific OpenTofu/Terraform flags (e.g., -upgrade)
Error-Returning Variants (E-suffix)

Every function has an E-suffix variant that returns an error instead of calling t.Fatal on failure. For example:

  • ApplyContext(t, ctx, options) calls t.Fatal on error
  • ApplyContextE(t, ctx, options) returns (string, error) for custom error handling

Use E variants when you need to test error cases or handle failures gracefully:

_, err := terragrunt.ApplyContextE(t, t.Context(), options)
require.Error(t, err)
TerragruntArgs vs TerraformArgs

Arguments are passed in this order:

terragrunt [TerragruntArgs] --non-interactive run -- <command> [TerraformArgs]

Example:

options := &terragrunt.Options{
    TerragruntDir:  "/path/to/config",
    TerragruntArgs: []string{"--log-level", "error"},  // Global TG flags
    TerraformArgs:  []string{"-upgrade"},              // OpenTofu/Terraform flags
}
// Executes: terragrunt --log-level error --non-interactive run -- init -upgrade

Functions

Single-Unit Commands

Run terragrunt commands against a single unit (one terragrunt.hcl directory):

  • InitContext(t, ctx, options) - Initialize configuration
  • ApplyContext(t, ctx, options) - Apply changes
  • DestroyContext(t, ctx, options) - Destroy resources
  • PlanContext(t, ctx, options) - Generate and show execution plan
  • PlanExitCodeContext(t, ctx, options) - Plan and return exit code (0=no changes, 2=changes, other=error)
  • ValidateContext(t, ctx, options) - Validate configuration
  • OutputJSONContext(t, ctx, options, key) - Get output as JSON (specific key or all outputs)
Convenience Wrappers

Run init + command in a single call:

  • InitAndApplyContext(t, ctx, options) - Init then apply
  • InitAndPlanContext(t, ctx, options) - Init then plan
  • InitAndValidateContext(t, ctx, options) - Init then validate
Run Command
  • RunContext(t, ctx, options, tgArgs, tfArgs) - Run any OpenTofu/Terraform command via terragrunt run [tgArgs...] -- [tfArgs...]

The -- separator disambiguates Terragrunt flags (like --all) from OpenTofu/Terraform flags. The OpenTofu/Terraform command (e.g. "apply") should be the first element of tfArgs.

Run --all Commands

Work with implicit stacks (multiple units in a directory):

  • ApplyAllContext(t, ctx, options) - Apply all modules with dependencies
  • DestroyAllContext(t, ctx, options) - Destroy all modules with dependencies
  • PlanAllExitCodeContext(t, ctx, options) - Plan all and return exit code (0=no changes, 2=changes, other=error)
  • ValidateAllContext(t, ctx, options) - Validate all modules
  • RunAllContext(t, ctx, options, command) - Deprecated: use RunContext with --all in tgArgs instead. Run any OpenTofu/Terraform command with --all flag
  • OutputAllJSONContext(t, ctx, options) - Get all outputs as raw JSON string (note: returns separate JSON objects per module)
HCL Commands

Terragrunt HCL tooling commands:

  • FormatAllContext(t, ctx, options) - Format all terragrunt.hcl files (terragrunt hcl format)
  • HclValidateContext(t, ctx, options) - Validate terragrunt.hcl syntax and configuration (terragrunt hcl validate)
Configuration Commands
  • RenderContext(t, ctx, options) - Render resolved terragrunt configuration as HCL
  • RenderJSONContext(t, ctx, options) - Render resolved terragrunt configuration as JSON
  • GraphContext(t, ctx, options) - Output dependency graph in DOT format
Stack Commands

Work with explicit stacks (a directory with a terragrunt.stack.hcl file):

  • StackGenerateContext(t, ctx, options) - Generate stack from stack.hcl
  • StackRunContext(t, ctx, options) - Run command on generated stack
  • StackCleanContext(t, ctx, options) - Remove .terragrunt-stack directory
  • StackOutputContext(t, ctx, options, key) - Get stack output value
  • StackOutputJSONContext(t, ctx, options, key) - Get stack output as JSON
  • StackOutputAllContext(t, ctx, options) - Get all stack outputs as map
  • StackOutputListAllContext(t, ctx, options) - Get list of all output variable names

Examples

See the examples directory for complete working examples:

Testing with Dependencies
func TestStack(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../live/prod",
    }

    // Apply respects dependency order
    terragrunt.ApplyAllContext(t, ctx, options)
    defer terragrunt.DestroyAllContext(t, ctx, options)

    // Verify infrastructure
    // ... your assertions here
}
Using Custom Arguments
func TestWithCustomArgs(t *testing.T) {
    t.Parallel()

    options := &terragrunt.Options{
        TerragruntDir:  "../config",
        TerragruntArgs: []string{"--log-level", "error", "--no-color"},
        TerraformArgs:  []string{"-upgrade"},
    }

    terragrunt.InitContext(t, t.Context(), options)
}
Testing Stack Outputs
func TestStackOutput(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../stack",
    }

    applyOpts := &terragrunt.Options{
        TerragruntDir: "../stack",
        TerraformArgs: []string{"apply"},
    }
    destroyOpts := &terragrunt.Options{
        TerragruntDir: "../stack",
        TerraformArgs: []string{"destroy"},
    }

    terragrunt.StackRunContext(t, ctx, applyOpts)
    defer terragrunt.StackRunContext(t, ctx, destroyOpts)

    // Get specific output
    vpcID := terragrunt.StackOutputContext(t, ctx, options, "vpc_id")
    assert.NotEmpty(t, vpcID)

    // Get all outputs
    outputs := terragrunt.StackOutputAllContext(t, ctx, options)
    assert.Contains(t, outputs, "vpc_id")
}
Checking Plan Exit Code
func TestInfrastructureUpToDate(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../prod",
    }

    // First apply
    terragrunt.ApplyAllContext(t, ctx, options)
    defer terragrunt.DestroyAllContext(t, ctx, options)

    // Plan should show no changes (exit code 0)
    exitCode := terragrunt.PlanAllExitCodeContext(t, ctx, options)
    assert.Equal(t, 0, exitCode, "No changes expected")
}
Using Run for Flexibility
func TestCustomCommand(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../modules",
    }

    // Run any OpenTofu/Terraform command with --all
    terragrunt.RunContext(t, ctx, options, []string{"--all"}, []string{"refresh"})

    // Verify state is current
    output := terragrunt.RunContext(t, ctx, options, []string{"--all"}, []string{"show"})
    assert.Contains(t, output, "expected-resource")
}
Validating Stack Output Keys
func TestStackOutputKeys(t *testing.T) {
    t.Parallel()

    ctx := t.Context()

    options := &terragrunt.Options{
        TerragruntDir: "../stack",
    }

    applyOpts := &terragrunt.Options{
        TerragruntDir: "../stack",
        TerraformArgs: []string{"apply"},
    }
    destroyOpts := &terragrunt.Options{
        TerragruntDir: "../stack",
        TerraformArgs: []string{"destroy"},
    }

    terragrunt.StackRunContext(t, ctx, applyOpts)
    defer terragrunt.StackRunContext(t, ctx, destroyOpts)

    // Get list of all output keys
    keys := terragrunt.StackOutputListAllContext(t, ctx, options)

    // Verify required outputs exist
    assert.Contains(t, keys, "vpc_id")
    assert.Contains(t, keys, "subnet_ids")
}
Using Filters (Terragrunt v0.97.0+)
options := &terragrunt.Options{
    TerragruntDir:  "../live/prod",
    TerragruntArgs: []string{"--filter", "{./vpc}"},  // Only apply vpc
}
terragrunt.ApplyAllContext(t, t.Context(), options)

Not Supported

This module does NOT have dedicated helpers for:

  • import, refresh, show, state, test commands
  • backend, exec, catalog, scaffold commands
  • Discovery commands (find, list)
  • Configuration commands (info)

For these commands, use RunContext / RunContextE or run terragrunt directly via the shell module.

Compatibility

Tested with Terragrunt v1.0.x. Earlier v0.x versions may work but are not guaranteed.

Migration from terraform Module

The following functions were previously in the terraform module and have been moved here. The deprecated versions have been removed from the terraform module.

Removed (terraform module) Replacement (terragrunt module)
TgApplyAll / TgApplyAllE ApplyAll / ApplyAllE
TgDestroyAll / TgDestroyAllE DestroyAll / DestroyAllE
TgPlanAllExitCode / TgPlanAllExitCodeE PlanAllExitCode / PlanAllExitCodeE
ValidateInputs / ValidateInputsE HclValidate / HclValidateE

Note: ValidateInputs specifically checked input alignment. For equivalent behavior, pass TerraformArgs: []string{"--inputs"} to HclValidate.

More Info

Documentation

Overview

Package terragrunt provides test helpers for running Terragrunt commands.

This package wraps the Terragrunt CLI to simplify integration testing of Terragrunt configurations. It supports both single-unit testing and multi-unit stack testing with dependency management.

For single-unit testing, you can use either this package or the terraform package with TerraformBinary set to "terragrunt". For stack testing with --all commands, use the dedicated functions in this package such as ApplyAllContextE and DestroyAllContextE.

Index

Constants

View Source
const (
	DefaultTerragruntBinary = "terragrunt"
	NonInteractiveFlag      = "--non-interactive"
	TerragruntLogFormatKey  = "TG_LOG_FORMAT"
	TerragruntLogCustomKey  = "TG_LOG_CUSTOM_FORMAT"
	TerragruntNoTipsKey     = "TG_NO_TIPS"
	DefaultLogFormat        = "key-value"
	DefaultLogCustomFormat  = "%msg(color=disable)"
)

Key concepts: - Options: Configure HOW the test framework executes tg (directories, retry logic, logging) - TerragruntArgs: Global terragrunt flags (e.g., --log-level, --no-color) - TerraformArgs: Command-specific OpenTofu/Terraform args (e.g., -upgrade for init, or the command itself for stack run) - Use Options.TerragruntDir to specify WHERE to run tg

Example:

ctx := t.Context()

// For init with OpenTofu/Terraform flags
InitContextE(t, ctx, &Options{
    TerragruntDir: "/path/to/config",
    TerragruntArgs: []string{"--log-level", "info"},
    TerraformArgs: []string{"-upgrade=true"},
})

// For run-all with global flags
ApplyAllContextE(t, ctx, &Options{
    TerragruntDir: "/path/to/config",
    TerragruntArgs: []string{"--no-color"},
})

Constants for test framework configuration and environment variables

Variables

View Source
var ErrEmptyTfArgs = errors.New("tfArgs cannot be empty; at minimum, an OpenTofu/Terraform command (e.g. \"apply\") is required")

ErrEmptyTfArgs is returned when tfArgs is empty in a call that requires at least one OpenTofu/Terraform command argument (e.g. "apply", "plan").

View Source
var ErrMissingTerragruntDir = errors.New("TerragruntDir is required")

ErrMissingTerragruntDir is returned when the required TerragruntDir field is empty in the provided Options.

View Source
var ErrNilOptions = errors.New("options cannot be nil")

ErrNilOptions is returned when a nil Options pointer is passed to a function that requires a valid configuration.

Functions

func ApplyAllContext

func ApplyAllContext(t testing.TestingT, ctx context.Context, options *Options) string

ApplyAllContext runs terragrunt run --all apply with the given options and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. Note that this method does NOT call destroy and assumes the caller is responsible for cleaning up any resources created by running apply.

func ApplyAllContextE

func ApplyAllContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

ApplyAllContextE runs terragrunt run --all apply with the given options and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. Note that this method does NOT call destroy and assumes the caller is responsible for cleaning up any resources created by running apply.

func ApplyContext

func ApplyContext(t testing.TestingT, ctx context.Context, options *Options) string

ApplyContext runs terragrunt run apply for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ApplyContextE

func ApplyContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

ApplyContextE runs terragrunt run -- apply for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func BuildRunArgs

func BuildRunArgs(tgArgs []string, tfArgs []string) []string

BuildRunArgs constructs the argument list for a terragrunt run command. The -- separator disambiguates Terragrunt flags from OpenTofu/Terraform flags:

run [tgArgs...] -- [tfArgs...]

func BuildTerragruntArgs

func BuildTerragruntArgs(opts *Options, commandArgs ...string) []string

BuildTerragruntArgs constructs the final argument list for a terragrunt command. Arguments are ordered as: TerragruntArgs → --non-interactive → commandArgs → TerraformArgs.

func CleanTerragruntJSON

func CleanTerragruntJSON(input string) (string, error)

CleanTerragruntJSON cleans the JSON output from a terragrunt stack command that returns a single combined JSON object. Returns an error if the output contains multiple JSON objects (use ExtractJSONContent directly for multi-object output).

Example input (raw tg JSON output):

time=2023-07-11T10:30:45Z level=info prefix=mother tf-path=terraform msg=Initializing...
time=2023-07-11T10:30:46Z level=info prefix=mother tf-path=terraform msg=Running command...
{"mother":{"output":"./test.txt"},"father":{"output":"./test.txt"}}

Example output (cleaned and formatted):

{
  "mother": {
    "output": "./test.txt"
  },
  "father": {
    "output": "./test.txt"
  }
}

func CleanTerragruntOutput

func CleanTerragruntOutput(rawOutput string) string

CleanTerragruntOutput extracts the actual output value from terragrunt stack's verbose output.

Example input (raw tg output):

time=2023-07-11T10:30:45Z level=info prefix=foo tf-path=terraform msg=Initializing...
time=2023-07-11T10:30:46Z level=info prefix=foo tf-path=terraform msg=Running command...
"my-bucket-name"

Example output (cleaned):

my-bucket-name

For JSON values, it preserves the structure: Input:

time=2023-07-11T10:30:45Z level=info prefix=foo tf-path=terraform msg=Running...
{"vpc_id": "vpc-12345", "subnet_ids": ["subnet-1", "subnet-2"]}

Output:

{"vpc_id": "vpc-12345", "subnet_ids": ["subnet-1", "subnet-2"]}

func DestroyAllContext

func DestroyAllContext(t testing.TestingT, ctx context.Context, options *Options) string

DestroyAllContext runs terragrunt run --all destroy with the given options and returns stdout. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func DestroyAllContextE

func DestroyAllContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

DestroyAllContextE runs terragrunt run --all -- destroy with the given options and returns stdout. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func DestroyContext

func DestroyContext(t testing.TestingT, ctx context.Context, options *Options) string

DestroyContext runs terragrunt run destroy for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func DestroyContextE

func DestroyContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

DestroyContextE runs terragrunt run -- destroy for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ExtractJSONContent

func ExtractJSONContent(rawOutput string) (string, error)

ExtractJSONContent extracts only JSON objects from terragrunt output, filtering out log lines and other non-JSON content like "Group 1" or "- Unit ./foo". Uses json.Decoder to correctly handle braces inside JSON string values.

func FilterLogLines

func FilterLogLines(rawOutput string) string

FilterLogLines removes terragrunt log lines while preserving original indentation. Unlike RemoveLogLines (which trims whitespace for JSON extraction), this keeps leading whitespace intact so HCL output structure is preserved.

func FormatAllContext

func FormatAllContext(t testing.TestingT, ctx context.Context, options *Options) string

FormatAllContext runs terragrunt hcl format to format all terragrunt.hcl files and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func FormatAllContextE

func FormatAllContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

FormatAllContextE runs terragrunt hcl format to format all terragrunt.hcl files and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func GraphContext

func GraphContext(t testing.TestingT, ctx context.Context, options *Options) string

GraphContext runs terragrunt dag graph and returns the DOT-format dependency graph. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is useful for verifying dependency relationships between terragrunt units. Log lines are stripped from the output so the result is clean DOT format.

func GraphContextE

func GraphContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

GraphContextE runs terragrunt dag graph and returns the DOT-format dependency graph. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is useful for verifying dependency relationships between terragrunt units. Log lines are stripped from the output so the result is clean DOT format.

func HasWarning

func HasWarning(opts *Options, commandOutput string) error

HasWarning checks if the command output contains any warnings that should be treated as errors. It uses regex patterns defined in opts.WarningsAsErrors to match warning messages.

func HclValidateContext

func HclValidateContext(t testing.TestingT, ctx context.Context, options *Options) string

HclValidateContext runs terragrunt hcl validate to check terragrunt.hcl syntax. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This validates Terragrunt HCL configuration and can check for mis-aligned inputs. Use TerraformArgs to pass additional flags like "--inputs" or "--strict".

Examples:

HclValidateContext(t, ctx, options)                                        // Basic syntax check
HclValidateContext(t, ctx, &Options{TerraformArgs: []string{"--inputs"}})  // Check input alignment

func HclValidateContextE

func HclValidateContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

HclValidateContextE runs terragrunt hcl validate to check terragrunt.hcl syntax. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This validates Terragrunt HCL configuration and can check for mis-aligned inputs. Use TerraformArgs to pass additional flags like "--inputs" or "--strict".

func InitAndApplyContext

func InitAndApplyContext(t testing.TestingT, ctx context.Context, options *Options) string

InitAndApplyContext runs terragrunt init followed by apply for a single unit and returns the apply stdout/stderr. The provided context is passed through to both the init and apply command executions.

func InitAndApplyContextE

func InitAndApplyContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

InitAndApplyContextE runs terragrunt init followed by apply for a single unit and returns the apply stdout/stderr. The provided context is passed through to both the init and apply command executions.

func InitAndPlanContext

func InitAndPlanContext(t testing.TestingT, ctx context.Context, options *Options) string

InitAndPlanContext runs terragrunt init followed by plan for a single unit and returns the plan stdout/stderr. The provided context is passed through to both the init and plan command executions.

func InitAndPlanContextE

func InitAndPlanContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

InitAndPlanContextE runs terragrunt init followed by plan for a single unit and returns the plan stdout/stderr. The provided context is passed through to both the init and plan command executions.

func InitAndValidateContext

func InitAndValidateContext(t testing.TestingT, ctx context.Context, options *Options) string

InitAndValidateContext runs terragrunt init followed by validate for a single unit and returns the validate stdout/stderr. The provided context is passed through to both the init and validate command executions.

func InitAndValidateContextE

func InitAndValidateContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

InitAndValidateContextE runs terragrunt init followed by validate for a single unit and returns the validate stdout/stderr. The provided context is passed through to both the init and validate command executions.

func InitContext

func InitContext(t testing.TestingT, ctx context.Context, options *Options) string

InitContext calls terragrunt run init and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func InitContextE

func InitContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

InitContextE calls terragrunt run -- init and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func IsLogLine

func IsLogLine(line string) bool

IsLogLine checks if a line is a terragrunt log line.

func IsMetadataLine

func IsMetadataLine(line string) bool

IsMetadataLine checks if a line is terragrunt metadata (e.g., "Group 1", "- Unit ./foo").

func OutputAllJSONContext

func OutputAllJSONContext(t testing.TestingT, ctx context.Context, options *Options) string

OutputAllJSONContext runs terragrunt run --all output -json and returns the raw JSON string. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. Note: Current terragrunt versions return separate JSON objects per module, not a combined object.

func OutputAllJSONContextE

func OutputAllJSONContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

OutputAllJSONContextE runs terragrunt run --all output -json and returns the raw JSON string. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. Note: Current terragrunt versions return separate JSON objects per module, not a combined object.

func OutputJSONContext

func OutputJSONContext(t testing.TestingT, ctx context.Context, options *Options, key string) string

OutputJSONContext runs terragrunt run output -json for a single unit and returns clean JSON. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. If key is non-empty, returns the JSON value for that specific output. If key is empty, returns all outputs as JSON.

func OutputJSONContextE

func OutputJSONContextE(t testing.TestingT, ctx context.Context, options *Options, key string) (string, error)

OutputJSONContextE runs terragrunt run output -json for a single unit and returns clean JSON. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. If key is non-empty, returns the JSON value for that specific output. If key is empty, returns all outputs as JSON.

func PlanAllExitCodeContext

func PlanAllExitCodeContext(t testing.TestingT, ctx context.Context, options *Options) int

PlanAllExitCodeContext runs terragrunt run --all plan with the given options and returns the detailed exit code. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This will fail the test if there is an error in the command.

func PlanAllExitCodeContextE

func PlanAllExitCodeContextE(t testing.TestingT, ctx context.Context, options *Options) (int, error)

PlanAllExitCodeContextE runs terragrunt run --all -- plan with the given options and returns the detailed exit code. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func PlanContext

func PlanContext(t testing.TestingT, ctx context.Context, options *Options) string

PlanContext runs terragrunt run plan for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func PlanContextE

func PlanContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

PlanContextE runs terragrunt run -- plan for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. Uses -lock=false since plan is a read-only operation that does not need state locking.

func PlanExitCodeContext

func PlanExitCodeContext(t testing.TestingT, ctx context.Context, options *Options) int

PlanExitCodeContext runs terragrunt run plan for a single unit and returns the detailed exit code. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This will fail the test if there is an error in the command.

func PlanExitCodeContextE

func PlanExitCodeContextE(t testing.TestingT, ctx context.Context, options *Options) (int, error)

PlanExitCodeContextE runs terragrunt run -- plan for a single unit and returns the detailed exit code. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func PrepareOptions

func PrepareOptions(opts *Options) error

PrepareOptions validates options and sets defaults.

func RemoveLogLines

func RemoveLogLines(rawOutput string) string

RemoveLogLines removes terragrunt log lines and metadata from output.

func RenderContext

func RenderContext(t testing.TestingT, ctx context.Context, options *Options) string

RenderContext runs terragrunt render to output the resolved terragrunt configuration as HCL. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is useful for verifying merged includes, resolved dependencies, and executed functions without actually applying any changes.

func RenderContextE

func RenderContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

RenderContextE runs terragrunt render to output the resolved terragrunt configuration as HCL. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is useful for verifying merged includes, resolved dependencies, and executed functions without actually applying any changes. Log lines are stripped from the output.

func RenderJSONContext

func RenderJSONContext(t testing.TestingT, ctx context.Context, options *Options) string

RenderJSONContext runs terragrunt render --format json and returns the cleaned JSON output. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is useful for programmatic assertions on the resolved terragrunt configuration.

func RenderJSONContextE

func RenderJSONContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

RenderJSONContextE runs terragrunt render --format json and returns the cleaned JSON output. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is useful for programmatic assertions on the resolved terragrunt configuration.

func RunContext

func RunContext(t testing.TestingT, ctx context.Context, options *Options, tgArgs []string, tfArgs []string) string

RunContext runs terragrunt run [tgArgs...] -- [tfArgs...] with the given options and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is a generic wrapper that allows running any OpenTofu/Terraform command through terragrunt run. The -- separator disambiguates Terragrunt flags from OpenTofu/Terraform flags. The OpenTofu/Terraform command (e.g. "apply") should be the first element of tfArgs.

func RunContextE

func RunContextE(t testing.TestingT, ctx context.Context, options *Options, tgArgs []string, tfArgs []string) (string, error)

RunContextE runs terragrunt run [tgArgs...] -- [tfArgs...] with the given options and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This is a generic wrapper that allows running any OpenTofu/Terraform command through terragrunt run. The -- separator disambiguates Terragrunt flags from OpenTofu/Terraform flags. The OpenTofu/Terraform command (e.g. "apply") should be the first element of tfArgs.

func StackCleanContext

func StackCleanContext(t testing.TestingT, ctx context.Context, options *Options) string

StackCleanContext calls terragrunt stack clean to remove the .terragrunt-stack directory. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This command cleans up the generated stack files created by stack generate or stack run.

func StackCleanContextE

func StackCleanContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

StackCleanContextE calls terragrunt stack clean to remove the .terragrunt-stack directory. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. This command cleans up the generated stack files created by stack generate or stack run.

func StackGenerateContext

func StackGenerateContext(t testing.TestingT, ctx context.Context, options *Options) string

StackGenerateContext calls terragrunt stack generate and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackGenerateContextE

func StackGenerateContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

StackGenerateContextE calls terragrunt stack generate and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackOutputAllContext

func StackOutputAllContext(t testing.TestingT, ctx context.Context, options *Options) map[string]any

StackOutputAllContext gets all stack outputs and returns them as a map[string]any. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackOutputAllContextE

func StackOutputAllContextE(t testing.TestingT, ctx context.Context, options *Options) (map[string]any, error)

StackOutputAllContextE gets all stack outputs and returns them as a map[string]any. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackOutputContext

func StackOutputContext(t testing.TestingT, ctx context.Context, options *Options, key string) string

StackOutputContext calls terragrunt stack output for the given variable and returns its value as a string. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackOutputContextE

func StackOutputContextE(t testing.TestingT, ctx context.Context, options *Options, key string) (string, error)

StackOutputContextE calls terragrunt stack output for the given variable and returns its value as a string. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackOutputJSONContext

func StackOutputJSONContext(t testing.TestingT, ctx context.Context, options *Options, key string) string

StackOutputJSONContext calls terragrunt stack output for the given variable and returns the result as a JSON string. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. If key is an empty string, it will return all the output variables.

func StackOutputJSONContextE

func StackOutputJSONContextE(t testing.TestingT, ctx context.Context, options *Options, key string) (string, error)

StackOutputJSONContextE calls terragrunt stack output for the given variable and returns the result as a JSON string. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control. If key is an empty string, it will return all the output variables.

func StackOutputListAllContext

func StackOutputListAllContext(t testing.TestingT, ctx context.Context, options *Options) []string

StackOutputListAllContext gets all stack output variable names and returns them as a slice. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackOutputListAllContextE

func StackOutputListAllContextE(t testing.TestingT, ctx context.Context, options *Options) ([]string, error)

StackOutputListAllContextE gets all stack output variable names and returns them as a slice. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackRunContext

func StackRunContext(t testing.TestingT, ctx context.Context, options *Options) string

StackRunContext calls terragrunt stack run and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func StackRunContextE

func StackRunContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

StackRunContextE calls terragrunt stack run and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ValidateAllContext

func ValidateAllContext(t testing.TestingT, ctx context.Context, options *Options) string

ValidateAllContext runs terragrunt run --all validate with the given options and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ValidateAllContextE

func ValidateAllContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

ValidateAllContextE runs terragrunt run --all -- validate with the given options and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ValidateContext

func ValidateContext(t testing.TestingT, ctx context.Context, options *Options) string

ValidateContext runs terragrunt run validate for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ValidateContextE

func ValidateContextE(t testing.TestingT, ctx context.Context, options *Options) (string, error)

ValidateContextE runs terragrunt run -- validate for a single unit and returns stdout/stderr. The provided context is passed through to the underlying command execution, allowing for timeout and cancellation control.

func ValidateOptions

func ValidateOptions(opts *Options) error

ValidateOptions validates that required options are provided.

Types

type Options

type Options struct {
	// Optional stdin to pass to OpenTofu/Terraform commands
	Stdin io.Reader

	// Test framework retry and error handling (NOT passed to tg command line)
	RetryableTerraformErrors map[string]string // Retryable error patterns
	EnvVars                  map[string]string // Environment variables for command execution
	WarningsAsErrors         map[string]string // Warnings to treat as errors

	// Test framework configuration (NOT passed to tg command line)
	Logger *logger.Logger // Logger for command output

	// Complex configuration that requires special formatting (NOT raw command-line args)
	BackendConfig map[string]any // Backend configuration (formatted specially)

	// Test framework configuration (NOT passed to tg command line)
	TerragruntBinary string // The tg binary to use (should be "terragrunt")
	PluginDir        string // Plugin directory (formatted specially)
	TerragruntDir    string // The directory containing the tg configuration

	// Global terragrunt command-line flags (placed BEFORE the command)
	// Example: []string{"--log-level", "info", "--no-color"}
	TerragruntArgs []string

	// Command-specific OpenTofu/Terraform flags (placed AFTER the command)
	// Example: []string{"-upgrade=true"} for init, or []string{"plan"} for stack run
	TerraformArgs []string

	MaxRetries         int           // Maximum number of retries
	TimeBetweenRetries time.Duration // Time between retries
}

Options represent the configuration options for tg test execution.

This struct is divided into two clear categories:

1. TEST FRAMEWORK CONFIGURATION:

  • Controls HOW the test framework executes tg
  • Includes: binary paths, directories, retry logic, logging, environment
  • These are NOT passed as command-line arguments to tg

2. TG COMMAND ARGUMENTS:

  • TerragruntArgs: Global terragrunt flags (placed BEFORE the command)
  • TerraformArgs: Command-specific flags (placed AFTER the command)
  • These ARE passed directly to tg in the appropriate positions

This separation eliminates confusion about which settings control the test framework vs which become tg command-line arguments.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL