engine

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: MPL-2.0 Imports: 54 Imported by: 0

Documentation

Overview

Package engine provides the core functionality of Terramate.

Index

Constants

View Source
const (
	// ErrRunFailed represents the error when the execution fails, whatever the reason.
	ErrRunFailed errors.Kind = "execution failed"

	// ErrRunCanceled represents the error when the execution was canceled.
	ErrRunCanceled errors.Kind = "execution canceled"

	// ErrRunCommandNotExecuted represents the error when the command was not executed for whatever reason.
	ErrRunCommandNotExecuted errors.Kind = "command not found"
)
View Source
const (
	// ErrCurrentHeadIsOutOfDate indicates the local HEAD revision is outdated.
	ErrCurrentHeadIsOutOfDate errors.Kind = "current HEAD is out-of-date with the remote base branch"
)

Variables

This section is empty.

Functions

func IsDeploymentTask

func IsDeploymentTask(t StackRunTask) bool

IsDeploymentTask returns true if the task is a deployment task.

func IsDriftTask

func IsDriftTask(t StackRunTask) bool

IsDriftTask returns true if the task is a drift task.

func IsPreviewTask

func IsPreviewTask(t StackRunTask) bool

IsPreviewTask returns true if the task is a preview task.

func LoadProjectBundles added in v0.16.0

func LoadProjectBundles(root *config.Root, resolveAPI resolve.API, evalctx *eval.Context, allowFetch bool) ([]*config.Bundle, error)

LoadProjectBundles recursively collects all the bundles in the given dir and evaluates them.

func ParseFilterTags

func ParseFilterTags(tags, notags []string) (filter.TagClause, error)

ParseFilterTags parses the tags and notags arguments.

Types

type CloudOrgState

type CloudOrgState struct {
	Name string
	UUID resources.UUID
}

CloudOrgState represents the state of a cloud organization.

type CloudState

type CloudState struct {
	Org CloudOrgState
	// contains filtered or unexported fields
}

CloudState represents the state of the cloud.

type DependencyFilters added in v0.15.0

type DependencyFilters struct {
	// Deprecated: Use IncludeDependencies instead
	IncludeOutputDependencies bool
	// Deprecated: Use OnlyDependencies instead
	OnlyOutputDependencies bool

	// Dependency filters (what selected stacks depend on)
	IncludeAllDependencies    bool
	IncludeDirectDependencies bool
	OnlyAllDependencies       bool
	OnlyDirectDependencies    bool
	ExcludeAllDependencies    bool

	// Dependent filters (what depends on selected stacks)
	IncludeAllDependents    bool
	IncludeDirectDependents bool
	OnlyDirectDependents    bool
	OnlyAllDependents       bool
	ExcludeAllDependents    bool
}

DependencyFilters holds the configuration for filtering stacks based on their dependencies and dependents.

func (*DependencyFilters) HasDependencyFilters added in v0.15.0

func (df *DependencyFilters) HasDependencyFilters() bool

HasDependencyFilters returns if there are any dependency filters set.

type DependencyGraph added in v0.15.0

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

DependencyGraph represents the dependency relationships between stacks.

func (*DependencyGraph) DetectCycles added in v0.15.0

func (g *DependencyGraph) DetectCycles() [][]string

DetectCycles detects circular dependencies in the graph Returns the paths involved in cycles, if any

func (*DependencyGraph) GetAllDependencies added in v0.15.0

func (g *DependencyGraph) GetAllDependencies(stackPath string) []string

GetAllDependencies returns all transitive dependencies of a stack (what it depends on, recursively)

func (*DependencyGraph) GetAllDependenciesForStacks added in v0.15.0

func (g *DependencyGraph) GetAllDependenciesForStacks(stackPaths []string) []string

GetAllDependenciesForStacks returns all transitive dependencies for a set of stacks

func (*DependencyGraph) GetAllDependents added in v0.15.0

func (g *DependencyGraph) GetAllDependents(stackPath string) []string

GetAllDependents returns all transitive dependents of a stack (what depends on it, recursively)

func (*DependencyGraph) GetAllDependentsForStacks added in v0.15.0

func (g *DependencyGraph) GetAllDependentsForStacks(stackPaths []string) []string

GetAllDependentsForStacks returns all transitive dependents for a set of stacks

func (*DependencyGraph) GetDirectDependencies added in v0.15.0

func (g *DependencyGraph) GetDirectDependencies(stackPath string) []string

GetDirectDependencies returns the immediate dependencies of a stack (what it depends on)

func (*DependencyGraph) GetDirectDependenciesForStacks added in v0.15.0

func (g *DependencyGraph) GetDirectDependenciesForStacks(stackPaths []string) []string

GetDirectDependenciesForStacks returns all direct dependencies for a set of stacks

func (*DependencyGraph) GetDirectDependents added in v0.15.0

func (g *DependencyGraph) GetDirectDependents(stackPath string) []string

GetDirectDependents returns the immediate dependents of a stack (what depends on it)

func (*DependencyGraph) GetDirectDependentsForStacks added in v0.15.0

func (g *DependencyGraph) GetDirectDependentsForStacks(stackPaths []string) []string

GetDirectDependentsForStacks returns all direct dependents for a set of stacks

type Engine

type Engine struct {
	HTTPClient http.Client
	// contains filtered or unexported fields
}

Engine holds the Terramate runtime state and does the heavy lifting of the CLI. The engine exposes an API for the core machinery of Terramate (stack management, change detection, stack ordering, etc) and is used by the CLI commands. Note(i4k): It's stateful and shared between commands, so beware of the side-effects of calling its methods. This is not the ideal design but the result of refactoring the cli package into per-package commands.

func Load

func Load(ctx context.Context, wd string, loadTerragruntModules bool, clicfg cliconfig.Config, uimode UIMode, printers printer.Printers, verbosity int, hclOpts ...hcl.Option) (e *Engine, found bool, err error)

Load loads the engine with the given working directory and CLI configuration. If the project is not found, it returns false.

func (*Engine) AddOutputDependencies added in v0.14.7

func (e *Engine) AddOutputDependencies(dependencyFilters DependencyFilters, stacks config.List[*config.SortableStack], target string) (config.List[*config.SortableStack], error)

AddOutputDependencies takes a list of stacks and adds potential output dependencies. Deprecated: This method now supports all dependency filtering via DependencyFilters.

func (*Engine) ApplyDependencyFilters added in v0.15.0

func (e *Engine) ApplyDependencyFilters(opts DependencyFilters, stacks config.List[*config.SortableStack], target string) (config.List[*config.SortableStack], error)

ApplyDependencyFilters applies dependency and dependent filters to the given stacks. It supports both legacy output-sharing filters and new comprehensive dependency filters for both Terragrunt and Terramate native stacks.

func (*Engine) BaseRef

func (e *Engine) BaseRef() string

BaseRef returns the git baseref of the project.

func (*Engine) CLIConfig

func (e *Engine) CLIConfig() cliconfig.Config

CLIConfig returns the CLI configuration.

func (*Engine) CheckTargetsConfiguration

func (e *Engine) CheckTargetsConfiguration(targetArg, fromTargetArg string, cloudCheckFn func(bool) error) error

CheckTargetsConfiguration checks the target configuration of the project.

func (*Engine) CloudClient

func (e *Engine) CloudClient() *cloud.Client

CloudClient returns the cloud client.

func (*Engine) CloudOrgName

func (e *Engine) CloudOrgName() string

CloudOrgName returns the name of the cloud organization.

func (*Engine) CloudRegion added in v0.14.2

func (e *Engine) CloudRegion() cloud.Region

CloudRegion returns the cloud region from configuration, defaulting to EU.

func (*Engine) CloudState

func (e *Engine) CloudState() CloudState

CloudState returns the cloud state.

func (*Engine) ComputeSelectedStacks

func (e *Engine) ComputeSelectedStacks(gitfilter GitFilter, tags filter.TagClause, dependencyFilters DependencyFilters, target string, stackFilters resources.StatusFilters) (config.List[*config.SortableStack], error)

ComputeSelectedStacks computes stacks based on filters, working directory, tags, filesystem ordering, git changes, etc.

func (*Engine) Config

func (e *Engine) Config() *config.Root

Config returns the root configuration of the project.

func (*Engine) Credential

func (e *Engine) Credential() cliauth.Credential

Credential returns the cloud credential.

func (*Engine) DetectEvalContext

func (e *Engine) DetectEvalContext(wd string, overrideGlobals map[string]string) (*eval.Context, error)

DetectEvalContext detects the evaluation context for a stack.

func (*Engine) DisableCloudFeatures

func (e *Engine) DisableCloudFeatures(err error)

DisableCloudFeatures disables cloud features and prints an error message.

func (*Engine) EnsureAllStackHaveIDs

func (e *Engine) EnsureAllStackHaveIDs(stacks config.List[*config.SortableStack]) error

EnsureAllStackHaveIDs ensures all stacks have IDs.

func (*Engine) FilterStacks

func (e *Engine) FilterStacks(stacks []stack.Entry, opts ...FilterStacksOption) ([]stack.Entry, error)

FilterStacks filters stacks based on tags and working directory.

func (*Engine) FriendlyFmtDir

func (e *Engine) FriendlyFmtDir(dir string) (string, bool)

FriendlyFmtDir formats the directory path in a friendly way.

func (*Engine) GetAffectedStacks

func (e *Engine) GetAffectedStacks(gitfilter GitFilter) ([]stack.Entry, error)

GetAffectedStacks returns the list of stacks affected by the current command. c.affectedStacks is expected to be already set, if not it will be computed and cached.

func (*Engine) HCLOptions

func (e *Engine) HCLOptions() []hcl.Option

HCLOptions returns the HCL options used to load the configuration.

func (*Engine) HandleCloudCriticalError

func (e *Engine) HandleCloudCriticalError(err error) error

HandleCloudCriticalError handles the error depending on the UI mode set. The error is logged as a warning and ignored if the UI mode is AutomationMode.

func (*Engine) IsCloudDisabled

func (e *Engine) IsCloudDisabled() bool

IsCloudDisabled returns true if cloud features are disabled.

func (*Engine) IsCloudEnabled

func (e *Engine) IsCloudEnabled() bool

IsCloudEnabled returns true if cloud features are enabled.

func (*Engine) ListStacks

func (e *Engine) ListStacks(gitfilter GitFilter, target string, stackFilters resources.StatusFilters, checkRepo bool) (*stack.Report, error)

ListStacks returns the list of stacks based on filters.

func (*Engine) LoadCredential

func (e *Engine) LoadCredential(preferences ...string) error

LoadCredential loads the cloud credential from the environment or configuration.

func (*Engine) NewDependencyGraph added in v0.15.0

func (e *Engine) NewDependencyGraph(stacks config.List[*config.SortableStack], target string) (*DependencyGraph, error)

NewDependencyGraph creates a new dependency graph from the given stacks. It extracts ONLY data dependencies from: - input.from_stack_id (Terramate native output sharing) - Terragrunt dependency blocks (read directly from mod.DependencyBlocks)

NOTE: stack.After and stack.Before are NOT included because they contain ordering-only dependencies (e.g., Terragrunt dependencies.paths) which should NOT widen scope.

func (*Engine) Project

func (e *Engine) Project() *Project

Project returns the project.

func (*Engine) ReloadConfig

func (e *Engine) ReloadConfig(ctx context.Context) error

ReloadConfig reloads the root configuration of the project.

func (*Engine) RepoChecks

func (e *Engine) RepoChecks() stack.RepoChecks

RepoChecks returns the cached repository checks.

func (*Engine) RootNode

func (e *Engine) RootNode() hcl.Config

RootNode returns the root node of the project.

func (*Engine) RunAll

func (e *Engine) RunAll(
	runs []StackRun,
	opts RunAllOptions,
) error

RunAll will execute the list of RunStack definitions. A RunStack defines the stack and its command to be executed. The isSuccessCode is a predicate used to decide if the command is considered a successful run or not. During the execution of this function the default behavior for signal handling will be changed so we can wait for the child process to exit before exiting Terramate. If a single SIGINT is sent to the Terramate process group then Terramate will wait for the process graceful exit and abort the execution of all subsequent stacks. If SIGINT is sent 3x then Terramate will send a SIGKILL to the currently running process and abort the execution of all subsequent stacks.

func (*Engine) SetupCloudConfig

func (e *Engine) SetupCloudConfig(requestedFeatures []string) error

SetupCloudConfig sets up the cloud configuration.

func (*Engine) SetupEvalContext

func (e *Engine) SetupEvalContext(wd string, st *config.Stack, target string, overrideGlobals map[string]string) (*eval.Context, error)

SetupEvalContext sets up the evaluation context for a stack.

func (*Engine) StackManager

func (e *Engine) StackManager() *stack.Manager

StackManager returns the stack manager.

func (*Engine) VendorDir

func (e *Engine) VendorDir() (project.Path, error)

VendorDir returns the vendor directory path.

type FilterStacksOption added in v0.14.6

type FilterStacksOption func(e *Engine, stacks []stack.Entry) ([]stack.Entry, error)

FilterStacksOption is an option for FilterStacks.

func ByBasePath added in v0.14.6

func ByBasePath(basePath project.Path) FilterStacksOption

ByBasePath filters out stacks not inside the given base path.

func ByTags added in v0.14.6

func ByTags(tags, notags []string) FilterStacksOption

ByTags is a convenience wrapper for ByTagsClause that handles the tag parsing.

func ByTagsClause added in v0.14.6

func ByTagsClause(tags filter.TagClause) FilterStacksOption

ByTagsClause filters stacks based on tags.

func ByWorkingDir added in v0.14.6

func ByWorkingDir() FilterStacksOption

ByWorkingDir filters out stacks based on the current working directory.

type GitFilter

type GitFilter struct {
	IsChanged  bool
	ChangeBase string

	EnableUntracked   *bool
	EnableUncommitted *bool
}

GitFilter holds the configuration for git change detection.

func NewGitFilter

func NewGitFilter(isChanged bool, gitChangeBase string, enable []string, disable []string) (GitFilter, error)

NewGitFilter creates a new GitFilter.

func NoGitFilter

func NoGitFilter() GitFilter

NoGitFilter returns a GitFilter for unfiltered list.

type Hooks

type Hooks struct {
	Before           RunBeforeHook
	After            RunAfterHook
	LogSyncer        LogSyncer
	LogSyncCondition LogSyncCondition
}

Hooks contains hooks that can be used to extend the behavior of the run engine.

type LogSyncCondition

type LogSyncCondition func(task StackRunTask, run StackRun) bool

LogSyncCondition is a function that is used to determine if the log syncer should be enabled for a given task.

type LogSyncer

type LogSyncer func(logger *zerolog.Logger, e *Engine, run StackRun, task StackRunTask, logs resources.CommandLogs)

LogSyncer is a function that is called when the cloud API is enabled and the log sync condition is met.

type Project

type Project struct {
	Git struct {
		Wrapper *git.Git

		RemoteConfigured bool
		BranchConfigured bool
		// contains filtered or unexported fields
	}
	// contains filtered or unexported fields
}

Project represents a Terramate project.

func NewProject

func NewProject(ctx context.Context, wd string, loadTerragruntModules bool, parserOpts ...hcl.Option) (prj *Project, found bool, err error)

NewProject creates a new project from the working directory.

func (*Project) CIPlatform

func (p *Project) CIPlatform() ci.PlatformType

CIPlatform returns the CI platform of the project.

func (*Project) DefaultBaseRef

func (p *Project) DefaultBaseRef() (string, error)

DefaultBaseRef returns the baseRef for the current git environment.

func (Project) DefaultBranchRef

func (p Project) DefaultBranchRef() string

DefaultBranchRef returns the default branch ref. Usually it's "origin/main".

func (*Project) DefaultLocalBaseRef

func (p *Project) DefaultLocalBaseRef() (string, error)

DefaultLocalBaseRef returns the baseRef in case there's no remote setup.

func (*Project) GitConfig

func (p *Project) GitConfig() *hcl.GitConfig

GitConfig returns the git configuration of the project.

func (*Project) HasCommit

func (p *Project) HasCommit() bool

HasCommit returns true if the project has a commit.

func (*Project) HasCommits

func (p *Project) HasCommits() bool

HasCommits returns true if the project has commits.

func (*Project) HeadCommit

func (p *Project) HeadCommit() (string, error)

HeadCommit returns the HEAD commit of the project.

func (*Project) IsGitFeaturesEnabled

func (p *Project) IsGitFeaturesEnabled() bool

IsGitFeaturesEnabled returns true if the project has git features enabled.

func (*Project) IsRepo

func (p *Project) IsRepo() bool

IsRepo returns true if the project is a git repository.

func (*Project) LocalDefaultBranchCommit

func (p *Project) LocalDefaultBranchCommit() (string, error)

LocalDefaultBranchCommit returns the local default branch commit of the project.

func (*Project) PrettyRepo

func (p *Project) PrettyRepo() (string, error)

PrettyRepo returns the pretty repository name.

func (*Project) RemoteDefaultCommit

func (p *Project) RemoteDefaultCommit() (string, error)

RemoteDefaultCommit returns the remote default branch commit of the project. Eg.: git fetch origin main && git rev-parse origin/main

func (*Project) Repo

func (p *Project) Repo() (*git.Repository, error)

Repo returns the git repository of the project.

type RunAfterHook

type RunAfterHook func(engine *Engine, run StackCloudRun, res RunResult, err error)

RunAfterHook is a function that is called after a stack is executed by the run engine.

type RunAllOptions

type RunAllOptions struct {
	Quiet           bool
	DryRun          bool
	Reverse         bool
	ScriptRun       bool
	ContinueOnError bool
	Parallel        int

	Stdout io.Writer
	Stderr io.Writer
	Stdin  io.Reader

	Hooks *Hooks
}

RunAllOptions contains options for the RunAll method.

type RunBeforeHook

type RunBeforeHook func(engine *Engine, run StackCloudRun)

RunBeforeHook is a function that is called before a stack is executed by the run engine.

type RunResult

type RunResult struct {
	ExitCode   int
	StartedAt  *time.Time
	FinishedAt *time.Time
}

RunResult contains exit code and duration of a completed run.

type StackCloudRun

type StackCloudRun struct {
	Target string
	Stack  *config.Stack
	Task   StackRunTask
	Env    []string
}

StackCloudRun is a stackRun, but with a single task, because the cloud API only supports a single command per stack for any operation (deploy, drift, preview).

func SelectCloudStackTasks

func SelectCloudStackTasks(runs []StackRun, pred func(StackRunTask) bool) []StackCloudRun

SelectCloudStackTasks selects cloud tasks from a list of stack runs.

type StackRun

type StackRun struct {
	Stack         *config.Stack
	Tasks         []StackRunTask
	SyncTaskIndex int // index of the task with sync options
}

StackRun contains a list of tasks to be run per stack.

type StackRunTask

type StackRunTask struct {
	Cmd []string

	ScriptIdx    int
	ScriptJobIdx int
	ScriptCmdIdx int

	CloudTarget     string
	CloudFromTarget string

	CloudSyncDeployment  bool
	CloudSyncDriftStatus bool
	CloudSyncPreview     bool
	CloudSyncLayer       preview.Layer

	CloudPlanFile          string
	CloudPlanProvisioner   string
	CloudPlanRenderTimeout time.Duration

	UseTerragrunt bool
	EnableSharing bool
	MockOnFail    bool
}

StackRunTask defines the command to be run and the cloud options.

type UIMode

type UIMode int

UIMode defines different modes of operation for the cli.

const (
	// HumanMode is the default normal mode when Terramate is executed at the user's machine.
	HumanMode UIMode = iota
	// AutomationMode is the mode when Terramate executes in the CI/CD environment.
	AutomationMode
)

Jump to

Keyboard shortcuts

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