common

package
v0.93.13 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package common provide base components for implementing runners.

Package common provides primitives to build and filter Terragrunt Terraform units and their dependencies. UnitResolver converts discovery results into executable units, resolves/wires dependencies, applies include/exclude rules and custom filters, and records telemetry.

Usage

  1. Create the resolver ctx := context.Background() resolver, err := NewUnitResolver(ctx, stack) if err != nil { /* handle error */ }

  2. Optionally add filters (applied after dependency wiring) resolver = resolver.WithFilters( /* examples: FilterByGraph(...), FilterByPaths(...), custom UnitFilter funcs */ )

  3. Resolve from discovery output units, err := resolver.ResolveFromDiscovery(ctx, logger, discoveredComponents) if err != nil { /* handle error */ }

  4. Iterate results for _, u := range units { if u.FlagExcluded { continue } // use u.Config, u.Dependencies, u.TerragruntOptions, etc. }

Notes

  • Include/Exclude: CLI include/exclude patterns are honored when the "double-star" strict control is enabled. Globs are compiled relative to WorkingDir and matched against unit paths.
  • Telemetry: resolver stages are wrapped with telemetry to aid performance diagnostics.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureAbsolutePath added in v0.93.4

func EnsureAbsolutePath(path string) (string, error)

EnsureAbsolutePath ensures a path is absolute, converting it if necessary. Returns the absolute path and any error encountered during conversion.

Types

type CompositeFilter added in v0.89.0

type CompositeFilter struct {
	Filters []UnitFilter
}

CompositeFilter combines multiple filters into a single filter. Filters are applied in the order they are provided.

func (*CompositeFilter) Filter added in v0.89.0

func (f *CompositeFilter) Filter(ctx context.Context, units Units, opts *options.TerragruntOptions) error

Filter implements UnitFilter by applying all filters in sequence.

type DependencyCycleError

type DependencyCycleError []string

func (DependencyCycleError) Error

func (err DependencyCycleError) Error() string

type DependencyNotFoundWhileCrossLinkingError

type DependencyNotFoundWhileCrossLinkingError struct {
	Unit       *Unit
	Dependency *Unit
}

func (DependencyNotFoundWhileCrossLinkingError) Error

type ForceLogLevelHook

type ForceLogLevelHook struct {
	// contains filtered or unexported fields
}

ForceLogLevelHook is a log hook which can change log level for messages which contains specific substrings

func NewForceLogLevelHook

func NewForceLogLevelHook(forcedLevel log.Level) *ForceLogLevelHook

NewForceLogLevelHook creates default log reduction hook

func (*ForceLogLevelHook) Fire

func (hook *ForceLogLevelHook) Fire(entry *logrus.Entry) error

Fire implements logrus.Hook.Fire()

func (*ForceLogLevelHook) Levels

func (hook *ForceLogLevelHook) Levels() []logrus.Level

Levels implements logrus.Hook.Levels()

type InfiniteRecursionError

type InfiniteRecursionError struct {
	Units          map[string]*Unit
	RecursionLevel int
}

func (InfiniteRecursionError) Error

func (err InfiniteRecursionError) Error() string

type LogEntriesDropperFormatter

type LogEntriesDropperFormatter struct {
	// contains filtered or unexported fields
}

LogEntriesDropperFormatter is a custom formatter which will ignore log entries which has lower level than preconfigured in logger

func (*LogEntriesDropperFormatter) Format

func (formatter *LogEntriesDropperFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format implements logrus.Formatter

type Option

type Option interface {
	Apply(stack StackRunner)
}

Option applies configuration to a StackRunner.

Options are small composable units used to configure runners without exposing their internals. They can update runtime dependencies (e.g. report collector), tweak parsing behavior via ParseOptionsSetter, or seed contextual configuration.

func WithChildTerragruntConfig

func WithChildTerragruntConfig(cfg *config.TerragruntConfig) Option

WithChildTerragruntConfig sets the child Terragrunt configuration on a StackRunner.

Useful when running a single child unit with a pre-parsed configuration.

func WithParseOptions

func WithParseOptions(parserOptions []hclparse.Option) Option

WithParseOptions provides custom HCL parser options to both discovery and stack execution.

Typical options include diagnostics writers, loggers, and file-update hooks.

func WithReport

func WithReport(r *report.Report) Option

WithReport attaches a report collector to the stack, enabling run summaries and metrics.

func WithUnitFilters added in v0.89.0

func WithUnitFilters(filters ...UnitFilter) Option

WithUnitFilters provides unit filters to customize unit exclusions after resolution. Filters are applied after units are discovered but before the queue is built. This is useful for commands like graph that need to filter units based on custom logic.

type ParseOptionsProvider added in v0.87.4

type ParseOptionsProvider interface {
	GetParseOptions() []hclparse.Option
}

ParseOptionsProvider exposes HCL parser options carried by an Option.

This is primarily used by discovery to extract parser options early, prior to constructing a stack, so discovery-time parsing uses the same configuration as execution-time parsing.

type ParseOptionsSetter added in v0.87.4

type ParseOptionsSetter interface {
	SetParseOptions(parserOptions []hclparse.Option)
}

ParseOptionsSetter is a minimal interface for components that can accept HCL parser options.

Implemented by both discovery and stack runner implementations, allowing callers to inject custom HCL parsing behavior (e.g., diagnostics writer, file update hooks) without coupling to concrete types.

type ProcessingUnitDependencyError

type ProcessingUnitDependencyError struct {
	Unit       *Unit
	Dependency *Unit
	Err        error
}

func (ProcessingUnitDependencyError) Error

func (ProcessingUnitDependencyError) ExitStatus

func (err ProcessingUnitDependencyError) ExitStatus() (int, error)

func (ProcessingUnitDependencyError) Unwrap

func (err ProcessingUnitDependencyError) Unwrap() error

type ProcessingUnitError

type ProcessingUnitError struct {
	UnderlyingError     error
	UnitPath            string
	HowThisUnitWasFound string
}

func (ProcessingUnitError) Error

func (err ProcessingUnitError) Error() string

func (ProcessingUnitError) Unwrap

func (err ProcessingUnitError) Unwrap() error

type Stack

type Stack struct {
	Report                *report.Report
	TerragruntOptions     *options.TerragruntOptions
	ChildTerragruntConfig *config.TerragruntConfig
	Units                 Units
	ParserOptions         []hclparse.Option
}

Stack represents a stack of units that you can "spin up" or "spin down"

func (*Stack) FindUnitByPath

func (stack *Stack) FindUnitByPath(path string) *Unit

FindUnitByPath finds a unit in the stack by its path

func (*Stack) String

func (stack *Stack) String() string

String renders this stack as a human-readable string

type StackRunner

type StackRunner interface {
	// Run - Execute all units in the stack according to the specified Terraform command and options.
	Run(ctx context.Context, l log.Logger, opts *options.TerragruntOptions) error
	// LogUnitDeployOrder Log the order in which units will be deployed for the given Terraform command.
	LogUnitDeployOrder(l log.Logger, terraformCommand string) error
	// JSONUnitDeployOrder Return the deployment order of units as a JSON string for the specified Terraform command.
	JSONUnitDeployOrder(terraformCommand string) (string, error)
	// ListStackDependentUnits Build and return a map of each unit to the list of units that depend on it.
	ListStackDependentUnits() map[string][]string
	// GetStack Retrieve the underlying Stack object managed by this runner.
	GetStack() *Stack
	// SetTerragruntConfig Set the child Terragrunt configuration for the stack.
	SetTerragruntConfig(config *config.TerragruntConfig)
	// SetParseOptions Set the parser options used for HCL parsing in the stack.
	SetParseOptions(parserOptions []hclparse.Option)
	// SetReport Attach a report object to the stack for collecting run data and summaries.
	SetReport(report *report.Report)
}

StackRunner is the abstraction for running stack of units.

type Unit

type Unit struct {
	TerragruntOptions    *options.TerragruntOptions
	Logger               log.Logger
	Path                 string
	Reading              []string
	Dependencies         Units
	Config               config.TerragruntConfig
	AssumeAlreadyApplied bool
	FlagExcluded         bool
	IsExternal           bool // Set to true if this unit is outside the working directory (discovered as external dependency)
}

Unit represents a single module (i.e. folder with Terraform templates), including the Terragrunt configuration for that module and the list of other modules that this module depends on

func (*Unit) AbsolutePath added in v0.93.1

func (unit *Unit) AbsolutePath(l log.Logger) string

AbsolutePath returns the absolute path of the unit. If path conversion fails, returns the original path and logs a warning.

func (*Unit) FindUnitInPath

func (unit *Unit) FindUnitInPath(targetDirs []string) bool

FindUnitInPath returns true if a unit is located under one of the target directories. Both unit.Path and targetDirs are expected to be in canonical form (absolute or relative to the same base).

func (*Unit) FlushOutput

func (unit *Unit) FlushOutput() error

FlushOutput flushes buffer data to the output writer.

func (*Unit) OutputFile

func (unit *Unit) OutputFile(l log.Logger, opts *options.TerragruntOptions) string

OutputFile - return plan file location, if output folder is set

func (*Unit) OutputJSONFile

func (unit *Unit) OutputJSONFile(l log.Logger, opts *options.TerragruntOptions) string

OutputJSONFile - return plan JSON file location, if JSON output folder is set

func (*Unit) PlanFile

func (unit *Unit) PlanFile(l log.Logger, opts *options.TerragruntOptions) string

PlanFile - return plan file location, if output folder is set

func (*Unit) String

func (unit *Unit) String() string

String renders this unit as a human-readable string

type UnitFilter added in v0.89.0

type UnitFilter interface {
	// Filter applies the filtering logic to the given units.
	// Returns an error if the filtering operation fails.
	Filter(ctx context.Context, units Units, opts *options.TerragruntOptions) error
}

UnitFilter applies filtering logic to resolved units. Filters are applied after units are resolved but before the queue is built. They can modify the FlagExcluded field to control which units are included in execution.

type UnitFilterGraph added in v0.89.0

type UnitFilterGraph struct {
	// TargetDir is the directory whose dependents should be included
	TargetDir string
}

UnitFilterGraph filters units to include only a target directory and its dependents. This filter is used by the graph command to show only relevant units in the dependency graph.

func (*UnitFilterGraph) Filter added in v0.89.0

func (f *UnitFilterGraph) Filter(ctx context.Context, units Units, opts *options.TerragruntOptions) error

Filter implements UnitFilter. It marks all units as excluded except for the target directory and units that depend on it.

type UnitFiltersSetter added in v0.89.0

type UnitFiltersSetter interface {
	SetUnitFilters(filters ...UnitFilter)
}

UnitFiltersSetter is an interface for stack runners that support unit filtering.

type UnitResolver added in v0.84.0

type UnitResolver struct {
	Stack *Stack
	// contains filtered or unexported fields
}

UnitResolver provides common functionality for resolving Terraform units from Terragrunt configuration files.

func NewUnitResolver added in v0.84.0

func NewUnitResolver(ctx context.Context, stack *Stack) (*UnitResolver, error)

NewUnitResolver creates a new UnitResolver with the given stack.

func (*UnitResolver) ResolveFromDiscovery added in v0.93.1

func (r *UnitResolver) ResolveFromDiscovery(ctx context.Context, l log.Logger, discovered []component.Component) (Units, error)

ResolveFromDiscovery builds units starting from discovery-parsed components, avoiding re-parsing for initially discovered units. It preserves the same filtering and dependency resolution pipeline. Discovery has already found and parsed all dependencies including external ones.

func (*UnitResolver) WithFilters added in v0.89.0

func (r *UnitResolver) WithFilters(filters ...UnitFilter) *UnitResolver

WithFilters adds unit filters to the resolver. Filters are applied after units are resolved but before the queue is built.

type UnitRunner

type UnitRunner struct {
	Err    error
	Unit   *Unit
	Status UnitStatus
}

UnitRunner handles the logic for running a single unit.

func NewUnitRunner

func NewUnitRunner(unit *Unit) *UnitRunner

func (*UnitRunner) Run

func (runner *UnitRunner) Run(ctx context.Context, opts *options.TerragruntOptions, r *report.Report) error

Run a unit right now by executing the runTerragrunt command of its TerragruntOptions field.

type UnitStatus

type UnitStatus int

UnitStatus represents the status of a unit that we are trying to apply or destroy as part of the run --all apply or run --all destroy command

const (
	Waiting UnitStatus = iota
	Running
	Finished
)

type UnitWriter

type UnitWriter struct {
	// contains filtered or unexported fields
}

UnitWriter represents a Writer with data buffering. We should avoid outputting data directly to the output out, since when units run in parallel, the output data may be mixed with each other, thereby spoiling each other's results.

func NewUnitWriter

func NewUnitWriter(out io.Writer) *UnitWriter

NewUnitWriter returns a new UnitWriter instance.

func (*UnitWriter) Flush

func (writer *UnitWriter) Flush() error

Flush flushes buffer data to the `out` writer.

func (*UnitWriter) Write

func (writer *UnitWriter) Write(p []byte) (int, error)

Write appends the contents of p to the buffer.

type Units

type Units []*Unit

func (Units) CheckForCycles

func (units Units) CheckForCycles() error

CheckForCycles checks for dependency cycles in the given list of units and return an error if one is found.

type UnitsMap

type UnitsMap map[string]*Unit

func (UnitsMap) ConvertDiscoveryToRunner added in v0.93.4

func (unitsMap UnitsMap) ConvertDiscoveryToRunner(canonicalTerragruntConfigPaths []string) (Units, error)

ConvertDiscoveryToRunner converts units from discovery domain to runner domain by resolving Component interface dependencies into concrete *Unit pointer dependencies. Discovery found all dependencies and stored them as Component interfaces, but runner needs concrete *Unit pointers for efficient execution. This function translates between domains.

func (UnitsMap) FindByPath

func (unitsMap UnitsMap) FindByPath(path string) *Unit

FindByPath returns the unit that matches the given path, or nil if no such unit exists in the map.

func (UnitsMap) MergeMaps

func (unitsMap UnitsMap) MergeMaps(externalDependencies UnitsMap) UnitsMap

MergeMaps the given external dependencies into the given map of units if those dependencies aren't already in the units map

func (UnitsMap) SortedKeys

func (unitsMap UnitsMap) SortedKeys() []string

SortedKeys Return the keys for the given map in sorted order. This is used to ensure we always iterate over maps of units in a consistent order (Go does not guarantee iteration order for maps, and usually makes it random)

type UnrecognizedDependencyError

type UnrecognizedDependencyError struct {
	UnitPath              string
	DependencyPath        string
	TerragruntConfigPaths []string
}

func (UnrecognizedDependencyError) Error

func (err UnrecognizedDependencyError) Error() string

Jump to

Keyboard shortcuts

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