options

package
v0.99.4 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package options provides a set of options that configure the behavior of the Terragrunt program.

Index

Constants

View Source
const (
	DefaultMaxFoldersToCheck = 100

	// no limits on parallelism by default (limited by GOPROCS)
	DefaultParallelism = math.MaxInt32

	// TofuDefaultPath command to run tofu
	TofuDefaultPath = "tofu"

	// TerraformDefaultPath just takes terraform from the path
	TerraformDefaultPath = "terraform"

	// Default to naming it `terragrunt_rendered.json` in the terragrunt config directory.
	DefaultJSONOutName = "terragrunt_rendered.json"

	DefaultSignalsFile = "error-signals.json"

	DefaultTFDataDir = ".terraform"

	DefaultIAMAssumeRoleDuration = 3600

	DefaultLogLevel = log.InfoLevel
)
View Source
const ContextKey ctxKey = iota
View Source
const DefaultRetryMaxAttempts = 3
View Source
const DefaultRetrySleepInterval = 5 * time.Second

Variables

View Source
var (
	DefaultWrappedPath = identifyDefaultWrappedExecutable(context.Background())

	TerraformCommandsWithSubcommand = []string{
		"debug",
		"force-unlock",
		"state",
	}
)
View Source
var DefaultRetryableErrors = []string{
	"(?s).*Failed to load state.*tcp.*timeout.*",
	"(?s).*Failed to load backend.*TLS handshake timeout.*",
	"(?s).*Creating metric alarm failed.*request to update this alarm is in progress.*",
	"(?s).*Error installing provider.*TLS handshake timeout.*",
	"(?s).*Error configuring the backend.*TLS handshake timeout.*",
	"(?s).*Error installing provider.*tcp.*timeout.*",
	"(?s).*Error installing provider.*tcp.*connection reset by peer.*",
	"NoSuchBucket: The specified bucket does not exist",
	"(?s).*Error creating SSM parameter: TooManyUpdates:.*",
	"(?s).*app.terraform.io.*: 429 Too Many Requests.*",
	"(?s).*ssh_exchange_identification.*Connection closed by remote host.*",
	"(?s).*Client\\.Timeout exceeded while awaiting headers.*",
	"(?s).*Could not download module.*The requested URL returned error: 429.*",
	"(?s).*net/http: TLS.*handshake timeout.*",
	"(?s).*could not query provider registry.*context deadline exceeded.*",
}

DefaultRetryableErrors is a list of errors that are considered transient and should be retried.

It's a list of recurring transient errors encountered when calling terraform If any of these match, we'll retry the command.

Functions

func DefaultWorkingAndDownloadDirs

func DefaultWorkingAndDownloadDirs(terragruntConfigPath string) (string, string, error)

DefaultWorkingAndDownloadDirs gets the default working and download directories for the given Terragrunt config path.

func GetDefaultIAMAssumeRoleSessionName

func GetDefaultIAMAssumeRoleSessionName() string

GetDefaultIAMAssumeRoleSessionName gets the default IAM assume role session name.

Types

type EngineOptions

type EngineOptions struct {
	Meta    map[string]any
	Source  string
	Version string
	Type    string
}

EngineOptions Options for the Terragrunt engine.

type ErrorAction

type ErrorAction struct {
	IgnoreSignals   map[string]any
	IgnoreBlockName string
	RetryBlockName  string
	IgnoreMessage   string
	RetryAttempts   int
	RetrySleepSecs  int
	ShouldIgnore    bool
	ShouldRetry     bool
}

ErrorAction represents the action to take when an error occurs

type ErrorsConfig

type ErrorsConfig struct {
	Retry  map[string]*RetryConfig
	Ignore map[string]*IgnoreConfig
}

ErrorsConfig extracted errors handling configuration.

func (*ErrorsConfig) AttemptErrorRecovery added in v0.99.0

func (c *ErrorsConfig) AttemptErrorRecovery(l log.Logger, err error, currentAttempt int) (*ErrorAction, error)

AttemptErrorRecovery attempts to recover from an error by checking the ignore and retry rules.

type ErrorsPattern

type ErrorsPattern struct {
	Pattern  *regexp.Regexp `clone:"shadowcopy"`
	Negative bool
}

type IAMRoleOptions

type IAMRoleOptions struct {
	RoleARN               string
	WebIdentityToken      string
	AssumeRoleSessionName string
	AssumeRoleDuration    int64
}

IAMRoleOptions represents options that are used by Terragrunt to assume an IAM role.

func MergeIAMRoleOptions

func MergeIAMRoleOptions(target IAMRoleOptions, source IAMRoleOptions) IAMRoleOptions

type IgnoreConfig

type IgnoreConfig struct {
	Signals         map[string]any
	Name            string
	Message         string
	IgnorableErrors []*ErrorsPattern
}

IgnoreConfig represents the configuration for ignoring specific errors.

type MaxAttemptsReachedError added in v0.99.0

type MaxAttemptsReachedError struct {
	Err        error
	MaxRetries int
}

func (*MaxAttemptsReachedError) Error added in v0.99.0

func (e *MaxAttemptsReachedError) Error() string

type RetryConfig

type RetryConfig struct {
	Name             string
	RetryableErrors  []*ErrorsPattern
	MaxAttempts      int
	SleepIntervalSec int
}

RetryConfig represents the configuration for retrying specific errors.

type TerraformImplementationType

type TerraformImplementationType string
const (
	TerraformImpl TerraformImplementationType = "terraform"
	OpenTofuImpl  TerraformImplementationType = "tofu"
	UnknownImpl   TerraformImplementationType = "unknown"
)

type TerragruntOptions

type TerragruntOptions struct {
	// If you want stdout to go somewhere other than os.stdout
	Writer io.Writer
	// If you want stderr to go somewhere other than os.stderr
	ErrWriter io.Writer
	// Version of terragrunt
	TerragruntVersion *version.Version `clone:"shadowcopy"`
	// FeatureFlags is a map of feature flags to enable.
	FeatureFlags *xsync.MapOf[string, string] `clone:"shadowcopy"`
	// Options to use engine for running IaC operations.
	Engine *EngineOptions
	// Telemetry are telemetry options.
	Telemetry *telemetry.Options
	// Attributes to override in AWS provider nested within modules as part of the aws-provider-patch command.
	AwsProviderPatchOverrides map[string]string
	// Version of terraform (obtained by running 'terraform version')
	TerraformVersion *version.Version `clone:"shadowcopy"`
	// Errors is a configuration for error handling.
	Errors *ErrorsConfig
	// Map to replace terraform source locations.
	SourceMap map[string]string
	// Environment variables at runtime
	Env map[string]string
	// StackAction is the action that should be performed on the stack.
	StackAction string
	// IAM Role options that should be used when authenticating to AWS.
	IAMRoleOptions IAMRoleOptions
	// IAM Role options set from command line.
	OriginalIAMRoleOptions IAMRoleOptions
	// The Token for authentication to the Terragrunt Provider Cache server.
	ProviderCacheToken string
	// Current Terraform command being executed by Terragrunt
	TerraformCommand string
	// StackOutputFormat format how the stack output is rendered.
	StackOutputFormat         string
	TerragruntStackConfigPath string
	// Location of the original Terragrunt config file.
	OriginalTerragruntConfigPath string
	// Unlike `WorkingDir`, this path is the same for all dependencies and points to the root working directory specified in the CLI.
	RootWorkingDir string
	// Download Terraform configurations from the specified source location into a temporary folder
	Source string
	// The working directory in which to run Terraform
	WorkingDir string
	// Location (or name) of the OpenTofu/Terraform binary
	TFPath string
	// Download Terraform configurations specified in the Source parameter into this folder
	DownloadDir string
	// Original Terraform command being executed by Terragrunt.
	OriginalTerraformCommand string
	// Terraform implementation tool (e.g. terraform, tofu) that terragrunt is wrapping
	TofuImplementation TerraformImplementationType
	// The file path that terragrunt should use when rendering the terragrunt.hcl config as json.
	JSONOut string
	// The path to store unpacked providers.
	ProviderCacheDir string
	// Custom log level for engine
	EngineLogLevel string
	// Path to cache directory for engine files
	EngineCachePath string
	// The command and arguments that can be used to fetch authentication configurations.
	AuthProviderCmd string
	// Folder to store JSON representation of output files.
	JSONOutputFolder string
	// Folder to store output files.
	OutputFolder string
	// The file which hclfmt should be specifically run on
	HclFile string
	// The hostname of the Terragrunt Provider Cache server.
	ProviderCacheHostname string
	// Location of the Terragrunt config file
	TerragruntConfigPath string
	// Name of the root Terragrunt configuration file, if used.
	ScaffoldRootFileName string
	// Path to a file with a list of directories that need to be excluded when running *-all commands.
	ExcludesFile string
	// Path to folder of scaffold output
	ScaffoldOutputFolder string
	// Root directory for graph command.
	GraphRoot string
	// Path to the report file.
	ReportFile string
	// Path to a file containing filter queries, one per line. Default is .terragrunt-filters.
	FiltersFile string
	// Report format.
	ReportFormat report.Format
	// Path to the report schema file.
	ReportSchemaFile string
	// CLI args that are intended for Terraform (i.e. all the CLI args except the --terragrunt ones)
	TerraformCliArgs clihelper.Args
	// Files with variables to be used in modules scaffolding.
	ScaffoldVarFiles []string
	// The list of remote registries to cached by Terragrunt Provider Cache server.
	ProviderCacheRegistryNames []string
	// If set hclfmt will skip files in given directories.
	HclExclude []string
	// Variables for usage in scaffolding.
	ScaffoldVars []string
	// StrictControls is a slice of strict controls.
	StrictControls strict.Controls `clone:"shadowcopy"`
	// FilterQueries contains filter query strings for component selection
	FilterQueries []string
	// When set, it will be used to compute the cache key for `-version` checks.
	VersionManagerFileName []string
	// Experiments is a map of experiments, and their status.
	Experiments experiment.Experiments `clone:"shadowcopy"`
	// Parallelism limits the number of commands to run concurrently during *-all commands
	Parallelism int
	// When searching the directory tree, this is the max folders to check before exiting with an error.
	MaxFoldersToCheck int
	// The port of the Terragrunt Provider Cache server.
	ProviderCachePort int
	// Output Terragrunt logs in JSON format
	JSONLogFormat bool
	// True if terragrunt should run in debug mode
	Debug bool
	// Disable TF output formatting
	ForwardTFStdout bool
	// Fail execution if is required to create S3 bucket
	FailIfBucketCreationRequired bool
	// FilterAllowDestroy allows destroy runs when using Git-based filters
	FilterAllowDestroy bool
	// Controls if s3 bucket should be updated or skipped
	DisableBucketUpdate bool
	// Disables validation terraform command
	DisableCommandValidation bool
	// If True then HCL from StdIn must should be formatted.
	HclFromStdin bool
	// Show diff, by default it's disabled.
	Diff bool
	// Do not include root unit in scaffolding.
	ScaffoldNoIncludeRoot bool
	// Enable check mode, by default it's disabled.
	Check bool
	// Enables caching of includes during partial parsing operations.
	UsePartialParseConfigCache bool
	// Disable listing of dependent modules in render json output
	JSONDisableDependentModules bool
	// Enables Terragrunt's provider caching.
	ProviderCache bool
	// True if is required to show dependent units and confirm action
	CheckDependentUnits bool
	// True if is required to check for dependent modules during destroy operations
	DestroyDependenciesCheck bool
	// Include fields metadata in render-json
	RenderJSONWithMetadata bool
	// Whether we should automatically retry errored Terraform commands
	AutoRetry bool
	// Whether we should automatically run terraform init if necessary when executing other commands
	AutoInit bool
	// Allows to skip the output of all dependencies.
	SkipOutput bool
	// Whether we should prompt the user for confirmation or always assume "yes"
	NonInteractive bool
	// Skip checksum check for engine package.
	EngineSkipChecksumCheck bool
	// If set to true, ignore the dependency order when running *-all command.
	IgnoreDependencyOrder bool
	// If set to true, continue running *-all commands even if a dependency has errors.
	IgnoreDependencyErrors bool
	// Whether we should automatically run terraform with -auto-apply in run --all mode.
	RunAllAutoApprove bool
	// If set to true, delete the contents of the temporary folder before downloading Terraform source code into it
	SourceUpdate bool
	// HCLValidateStrict is a strict mode for HCL validation files. When it's set to false the command will only return an error if required inputs are missing from all input sources (env vars, var files, etc). When it's set to true, an error will be returned if required inputs are missing or if unused variables are passed to Terragrunt.",
	HCLValidateStrict bool
	// HCLValidateInputs checks if the terragrunt configured inputs align with the terraform defined variables.
	HCLValidateInputs bool
	// HCLValidateShowConfigPath shows the paths of the hcl invalid configs.
	HCLValidateShowConfigPath bool
	// HCLValidateJSONOutput outputs the hcl validate result as a JSON string.
	HCLValidateJSONOutput bool
	// If true, logs will be displayed in formatter key/value, by default logs are formatted in human-readable formatter.
	DisableLogFormatting bool
	// Headless is set when Terragrunt is running in headless mode.
	Headless bool
	// LogDisableErrorSummary is a flag to skip the error summary
	LogDisableErrorSummary bool
	// Disable replacing full paths in logs with short relative paths
	LogShowAbsPaths bool
	// NoStackGenerate disable stack generation.
	NoStackGenerate bool
	// NoStackValidate disable generated stack validation.
	NoStackValidate bool
	// RunAll runs the provided OpenTofu/Terraform command against a stack.
	RunAll bool
	// Graph runs the provided OpenTofu/Terraform against the graph of dependencies for the unit in the current working directory.
	Graph bool
	// BackendBootstrap automatically bootstraps backend infrastructure before attempting to use it.
	BackendBootstrap bool
	// DeleteBucket determines whether to delete entire bucket.
	DeleteBucket bool
	// ForceBackendDelete forces the backend to be deleted, even if the bucket is not versioned.
	ForceBackendDelete bool
	// ForceBackendMigrate forces the backend to be migrated, even if the bucket is not versioned.
	ForceBackendMigrate bool
	// SummaryDisable disables the summary output at the end of a run.
	SummaryDisable bool
	// SummaryPerUnit enables showing duration information for each unit in the summary.
	SummaryPerUnit bool
	// NoAutoProviderCacheDir disables the auto-provider-cache-dir feature even when the experiment is enabled.
	NoAutoProviderCacheDir bool
	// NoEngine disables IaC engines even when the iac-engine experiment is enabled.
	NoEngine bool
	// NoDependencyFetchOutputFromState disables the dependency-fetch-output-from-state feature even when the experiment is enabled.
	NoDependencyFetchOutputFromState bool
	// TFPathExplicitlySet is set to true if the user has explicitly set the TFPath via the --tf-path flag.
	TFPathExplicitlySet bool
	// FailFast is a flag to stop execution on the first error in apply of units.
	FailFast bool
	// NoDependencyPrompt disables prompt requiring confirmation for base and leaf file dependencies when using scaffolding.
	NoDependencyPrompt bool
	// NoShell disables shell commands when using boilerplate templates in catalog and scaffold commands.
	NoShell bool
	// NoHooks disables hooks when using boilerplate templates in catalog and scaffold commands.
	NoHooks bool
	// If set, disable automatic reading of .terragrunt-filters file.
	NoFiltersFile bool
}

TerragruntOptions represents options that configure the behavior of the Terragrunt program

func NewTerragruntOptions

func NewTerragruntOptions() *TerragruntOptions

NewTerragruntOptions creates a new TerragruntOptions object with reasonable defaults for real usage

func NewTerragruntOptionsForTest

func NewTerragruntOptionsForTest(terragruntConfigPath string, options ...TerragruntOptionsFunc) (*TerragruntOptions, error)

NewTerragruntOptionsForTest creates a new TerragruntOptions object with reasonable defaults for test usage.

func NewTerragruntOptionsWithConfigPath

func NewTerragruntOptionsWithConfigPath(terragruntConfigPath string) (*TerragruntOptions, error)

func NewTerragruntOptionsWithWriters

func NewTerragruntOptionsWithWriters(stdout, stderr io.Writer) *TerragruntOptions

func (*TerragruntOptions) AppendTerraformCliArgs

func (opts *TerragruntOptions) AppendTerraformCliArgs(argsToAppend ...string)

AppendTerraformCliArgs appends the given argsToAppend after the current TerraformCliArgs.

func (*TerragruntOptions) Clone

func (opts *TerragruntOptions) Clone() *TerragruntOptions

Clone performs a deep copy of `opts` with shadow copies of: interfaces, and funcs. Fields with "clone" tags can override this behavior.

func (*TerragruntOptions) CloneWithConfigPath

func (opts *TerragruntOptions) CloneWithConfigPath(l log.Logger, configPath string) (log.Logger, *TerragruntOptions, error)

CloneWithConfigPath creates a copy of this TerragruntOptions, but with different values for the given variables. This is useful for creating a TerragruntOptions that behaves the same way, but is used for a Terraform module in a different folder.

It also adjusts the given logger, as each cloned option has to use a working directory specific logger to enrich log output correctly.

func (*TerragruntOptions) DataDir

func (opts *TerragruntOptions) DataDir() string

DataDir returns the Terraform data directory prepended with the working directory path, or just the Terraform data directory if it is an absolute path.

func (*TerragruntOptions) InsertTerraformCliArgs

func (opts *TerragruntOptions) InsertTerraformCliArgs(argsToInsert ...string)

InsertTerraformCliArgs inserts the given argsToInsert after the terraform command argument, but before the remaining args.

func (*TerragruntOptions) OptionsFromContext

func (opts *TerragruntOptions) OptionsFromContext(ctx context.Context) *TerragruntOptions

OptionsFromContext tries to retrieve options from context, otherwise, returns its own instance.

func (*TerragruntOptions) RunWithErrorHandling

func (opts *TerragruntOptions) RunWithErrorHandling(
	ctx context.Context,
	l log.Logger,
	r *report.Report,
	operation func() error,
) error

RunWithErrorHandling runs the given operation and handles any errors according to the configuration.

func (*TerragruntOptions) TerraformDataDir

func (opts *TerragruntOptions) TerraformDataDir() string

TerraformDataDir returns Terraform data directory (.terraform by default, overridden by $TF_DATA_DIR envvar)

type TerragruntOptionsFunc

type TerragruntOptionsFunc func(*TerragruntOptions)

TerragruntOptionsFunc is a functional option type used to pass options in certain integration tests

func WithIAMRoleARN

func WithIAMRoleARN(arn string) TerragruntOptionsFunc

WithIAMRoleARN adds the provided role ARN to IamRoleOptions

func WithIAMWebIdentityToken

func WithIAMWebIdentityToken(token string) TerragruntOptionsFunc

WithIAMWebIdentityToken adds the provided WebIdentity token to IamRoleOptions

Jump to

Keyboard shortcuts

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