options

package
v0.0.0-...-53190cb Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2024 License: MIT Imports: 13 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"

	DefaultTFDataDir = ".terraform"

	DefaultIAMAssumeRoleDuration = 3600
)
View Source
const ContextKey ctxKey = iota
View Source
const DefaultRetryMaxAttempts = 3
View Source
const DefaultRetrySleepInterval = 5 * time.Second

Variables

View Source
var (
	DefaultWrappedPath = identifyDefaultWrappedExecutable()

	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.*",
}

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.

View Source
var ErrRunTerragruntCommandNotSet = goErrors.New("the RunTerragrunt option has not been set on this TerragruntOptions object")

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 {
	Source  string
	Version string
	Type    string
	Meta    map[string]interface{}
}

EngineOptions Options for the Terragrunt engine

type IAMRoleOptions

type IAMRoleOptions struct {
	// The ARN of an IAM Role to assume. Used when accessing AWS, both internally and through terraform.
	RoleARN string

	// The Web identity token. Used when RoleArn is also set to use AssumeRoleWithWebIdentity instead of AssumeRole.
	WebIdentityToken string

	// Duration of the STS Session when assuming the role.
	AssumeRoleDuration int64

	// STS Session name when assuming the role.
	AssumeRoleSessionName string
}

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

func MergeIAMRoleOptions

func MergeIAMRoleOptions(target IAMRoleOptions, source IAMRoleOptions) IAMRoleOptions

type TerraformImplementationType

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

type TerragruntOptions

type TerragruntOptions struct {
	// Location of the Terragrunt config file
	TerragruntConfigPath string

	// Location of the original Terragrunt config file. This is primarily useful when one Terragrunt config is being
	// read from another: e.g., if /terraform-code/terragrunt.hcl calls read_terragrunt_config("/foo/bar.hcl"),
	// and within bar.hcl, you call get_original_terragrunt_dir(), you'll get back /terraform-code.
	OriginalTerragruntConfigPath string

	// Version of terragrunt
	TerragruntVersion *version.Version

	// Location of the terraform binary
	TerraformPath string

	// Current Terraform command being executed by Terragrunt
	TerraformCommand string

	// Original Terraform command being executed by Terragrunt. Used to track command evolution as terragrunt chains
	// different commands together. For example, when retrieving dependencies, terragrunt will change the
	// TerraformCommand to `output` to run `terraform output`, which loses the context of the original command that was
	// run to fetch the dependency. This is a problem when mock_outputs is configured and we only allow mocks to be
	// returned on specific commands.
	// NOTE: For `xxx-all` commands, this will be set to the Terraform command, which would be `xxx`. For example,
	// if you run `apply-all` (which is a terragrunt command), this variable will be set to `apply`.
	OriginalTerraformCommand string

	// Terraform implementation tool (e.g. terraform, tofu) that terragrunt is wrapping
	TerraformImplementation TerraformImplementationType

	// Version of terraform (obtained by running 'terraform version')
	TerraformVersion *version.Version

	// Whether we should prompt the user for confirmation or always assume "yes"
	NonInteractive bool

	// Whether we should automatically run terraform init if necessary when executing other commands
	AutoInit bool

	// Whether we should automatically run terraform with -auto-apply in run-all mode.
	RunAllAutoApprove bool

	// CLI args that are intended for Terraform (i.e. all the CLI args except the --terragrunt ones)
	TerraformCliArgs []string

	// The working directory in which to run Terraform
	WorkingDir string

	// Unlike `WorkingDir`, this path is the same for all dependencies and points to the root working directory specified in the CLI.
	RootWorkingDir string

	// Basic log entry
	Logger log.Logger

	// Disable Terragrunt colors
	DisableLogColors bool

	// Output Terragrunt logs in JSON format
	JSONLogFormat bool

	// Disable replacing full paths in logs with short relative paths
	LogShowAbsPaths bool

	// Log level
	LogLevel log.Level

	// Log formatter
	LogFormatter *format.Formatter

	// If true, logs will be displayed in format key/value, by default logs are formatted in human-readable format.
	DisableLogFormatting bool

	// Wrap Terraform logs in JSON format
	TerraformLogsToJSON bool

	// ValidateStrict mode for the validate-inputs command
	ValidateStrict bool

	// Environment variables at runtime
	Env map[string]string

	// Download Terraform configurations from the specified source location into a temporary folder and run
	// Terraform in that temporary folder
	Source string

	// Map to replace terraform source locations. This will replace occurrences of the given source with the target
	// value.
	SourceMap map[string]string

	// If set to true, delete the contents of the temporary folder before downloading Terraform source code into it
	SourceUpdate bool

	// Download Terraform configurations specified in the Source parameter into this folder
	DownloadDir string

	// IAM Role options set from command line. This is used to differentiate between the options set from the config and
	// CLI.
	OriginalIAMRoleOptions IAMRoleOptions

	// IAM Role options that should be used when authenticating to AWS.
	IAMRoleOptions IAMRoleOptions

	// If set to true, continue running *-all commands even if a dependency has errors. This is mostly useful for 'output-all <some_variable>'. See https://github.com/nholuongut/terragrunt/issues/193
	IgnoreDependencyErrors bool

	// If set to true, ignore the dependency order when running *-all command.
	IgnoreDependencyOrder bool

	// If set to true, skip any external dependencies when running *-all commands
	IgnoreExternalDependencies bool

	// If set to true, apply all external dependencies when running *-all commands
	IncludeExternalDependencies bool

	// 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

	// When searching the directory tree, this is the max folders to check before exiting with an error. This is
	// exposed here primarily so we can set it to a low value at test time.
	MaxFoldersToCheck int

	// Whether we should automatically retry errored Terraform commands
	AutoRetry bool

	// Maximum number of times to retry errors matching RetryableErrors
	RetryMaxAttempts int

	// The duration in seconds to wait before retrying
	RetrySleepInterval time.Duration

	// RetryableErrors is an array of regular expressions with RE2 syntax (https://github.com/google/re2/wiki/Syntax) that qualify for retrying
	RetryableErrors []string

	// Path to a file with a list of directories that need  to be excluded when running *-all commands.
	ExcludesFile string

	// Unix-style glob of directories to exclude when running *-all commands
	ExcludeDirs []string

	// Unix-style glob of directories to include when running *-all commands
	IncludeDirs []string

	// If set to true, exclude all directories by default when running *-all commands
	// Is set automatically if IncludeDirs is set
	ExcludeByDefault bool

	// If set to true, do not include dependencies when processing IncludeDirs (unless they are in the included dirs)
	StrictInclude bool

	// Parallelism limits the number of commands to run concurrently during *-all commands
	Parallelism int

	// Enable check mode, by default it's disabled.
	Check bool

	// Show diff, by default it's disabled.
	Diff bool

	// The file which hclfmt should be specifically run on
	HclFile string

	// The file path that terragrunt should use when rendering the terragrunt.hcl config as json.
	JSONOut string

	// When used with `run-all`, restrict the modules in the stack to only those that include at least one of the files
	// in this list.
	ModulesThatInclude []string

	// A command that can be used to run Terragrunt with the given options. This is useful for running Terragrunt
	// multiple times (e.g. when spinning up a stack of Terraform modules). The actual command is normally defined
	// in the cli package, which depends on almost all other packages, so we declare it here so that other
	// packages can use the command without a direct reference back to the cli package (which would create a
	// circular dependency).
	RunTerragrunt func(ctx context.Context, opts *TerragruntOptions) error

	// True if terragrunt should run in debug mode, writing terragrunt-debug.tfvars to working folder to help
	// root-cause issues.
	Debug bool

	// Attributes to override in AWS provider nested within modules as part of the aws-provider-patch command. See that
	// command for more info.
	AwsProviderPatchOverrides map[string]string

	// True if is required to show dependent modules and confirm action
	CheckDependentModules bool

	// This is an experimental feature, used to speed up dependency processing by getting the output from the state
	FetchDependencyOutputFromState bool

	// Enables caching of includes during partial parsing operations.
	UsePartialParseConfigCache bool

	// Include fields metadata in render-json
	RenderJSONithMetadata bool

	// Disable TF output formatting
	ForwardTFStdout bool

	// Fail execution if is required to create S3 bucket
	FailIfBucketCreationRequired bool

	// Controls if s3 bucket should be updated or skipped
	DisableBucketUpdate bool

	// Disables validation terraform command
	DisableCommandValidation bool

	// Variables for usage in scaffolding.
	ScaffoldVars []string

	// Files with variables to be used in modules scaffolding.
	ScaffoldVarFiles []string

	// Root directory for graph command.
	GraphRoot string

	// Disable listing of dependent modules in render json output
	JSONDisableDependentModules bool

	// Enables Terragrunt's provider caching.
	ProviderCache bool

	// The path to store unpacked providers. The file structure is the same as terraform plugin cache dir.
	ProviderCacheDir string

	// The Token for authentication to the Terragrunt Provider Cache server.
	ProviderCacheToken string

	// The hostname of the Terragrunt Provider Cache server.
	ProviderCacheHostname string

	// The port of the Terragrunt Provider Cache server.
	ProviderCachePort int

	// The list of remote registries to cached by Terragrunt Provider Cache server.
	ProviderCacheRegistryNames []string

	// Folder to store output files.
	OutputFolder string

	// Folder to store JSON representation of output files.
	JSONOutputFolder string

	// The command and arguments that can be used to fetch authentication configurations.
	// Terragrunt invokes this command before running tofu/terraform operations for each working directory.
	AuthProviderCmd string

	// Allows to skip the output of all dependencies. Intended for use with `hclvalidate` command.
	SkipOutput bool

	// Options to use engine for running IaC operations.
	Engine *EngineOptions
}

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(terragruntConfigPath string) (*TerragruntOptions, error)

Clone 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.

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) 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