Help us shape the future of Go! Take the 2026 Go Developer Survey

tfeval

package
v1.20.3 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package tfeval evaluates local Terraform modules: bind inputs, resolve locals, recurse into nested modules, emit resource and data instances with concrete cty values where possible. Anything still unresolvable (e.g. computed attributes or data source results localdata does not compute) stays cty.UnknownVal.

Index

Constants

View Source
const UnknownAttributePlaceholder = partial.UnknownPlaceholder

UnknownAttributePlaceholder is stored for an unresolved value that has no source text to render, so keys stay present and MissingAttribute checks do not treat it as absent (which would false-positive).

Variables

View Source
var ErrModuleNotEvaluated = errors.New("tfeval: module not evaluated")

ErrModuleNotEvaluated reports that a module was skipped rather than evaluated, so callers must leave it to be scanned as written instead of treating it as a module that resolved to nothing.

Functions

func AttributesToDocument

func AttributesToDocument(r *ResolvedResource) map[string]interface{}

AttributesToDocument converts a resolved resource's attributes into the map[string]interface{} shape the rule pipeline consumes. Every attribute is always included: the parts of a value evaluation could not resolve are rendered as their "${expr}" text, as the plain parser does, so presence-based rules do not fire false positives on unresolved expressions and a string interpolating an unresolved value still carries the rest of its content.

func CalledLocalDirs

func CalledLocalDirs(dir string, fsys vfs.FS) []string

CalledLocalDirs returns the resolved directories of every local module called from dir. Remote/registry sources are ignored.

func CalledModuleDirs added in v1.8.0

func CalledModuleDirs(dir string, resolver RemoteResolver, fsys vfs.FS) []string

func MaxCountExpansion added in v1.20.0

func MaxCountExpansion() int

MaxCountExpansion reports the per-block count/for_each instance cap.

func MaxDynamicExpansion added in v1.20.0

func MaxDynamicExpansion() int

MaxDynamicExpansion is the cap on the blocks one dynamic block generates.

func MaxInstantiated added in v1.12.1

func MaxInstantiated() int

MaxInstantiated reports the per-scan instantiation budget.

func ResourceBaseName

func ResourceBaseName(name string) string

ResourceBaseName strips any count/for_each instance suffix from a resource Name (e.g. "k[0]" → "k", `k["dev"]` → "k"). Used by callers that need the bare label for rule matching or source-line lookups.

Types

type CallSite

type CallSite struct {
	ModuleName      string
	Source          string
	Version         string
	CalledFrom      string
	CalledLine      int
	CalledEndLine   int
	CalledColumn    int
	CalledEndColumn int
	// Body is the module block's body, used to trace a resource attribute back
	// to the call argument that sets it. Read-only after evaluation.
	Body *hclsyntax.Body
	// Caller is the module declaring the call as it was evaluated.
	Caller *ModuleScope
}

CallSite records one hop in a module call chain.

type DynamicCounts added in v1.20.0

type DynamicCounts map[*hclsyntax.Block]int

DynamicCounts maps a dynamic block to how many blocks it generated, or to unknownDynamicCount when its evaluations disagreed (a nested dynamic block generates a different number under each element of its parent).

type Evaluator

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

Evaluator evaluates local Terraform modules.

func New

func New() *Evaluator

func NewWithFS added in v1.15.0

func NewWithFS(fsys vfs.FS) *Evaluator

NewWithFS builds an Evaluator that reads module and tfvars files through fsys. A nil fsys falls back to the real disk.

func (*Evaluator) AddExpansionStats added in v1.20.0

func (e *Evaluator) AddExpansionStats(hits, maxRequested int)

AddExpansionStats folds truncation counters from a forked evaluator into e.

func (*Evaluator) AddNotEvaluatedDirs added in v1.19.0

func (e *Evaluator) AddNotEvaluatedDirs(dirs []string)

AddNotEvaluatedDirs records directories another evaluator skipped.

func (*Evaluator) BudgetDemand added in v1.19.0

func (e *Evaluator) BudgetDemand() int

BudgetDemand reports the most instantiated resources, counted from the evaluator's count at ResetBudgetDemand, any budget check has needed room for.

func (*Evaluator) BudgetExceeded added in v1.12.0

func (e *Evaluator) BudgetExceeded() bool

BudgetExceeded reports whether evaluation stopped early for budget, so callers can leave the modules it did not reach to be scanned as written.

func (*Evaluator) CalledModuleDirs added in v1.8.0

func (e *Evaluator) CalledModuleDirs(dir string) []string

func (*Evaluator) CalledModuleDirsWithContext added in v1.20.2

func (e *Evaluator) CalledModuleDirsWithContext(ctx context.Context, dir string) []string

CalledModuleDirsWithContext retains the scan's root and confinement cache during discovery, which shares parsed directories with module evaluation.

func (*Evaluator) DataBlockEvaluations added in v1.20.0

func (e *Evaluator) DataBlockEvaluations() int

DataBlockEvaluations reports how many data block expansions ran, counting only evaluations the eval cache could not avoid.

func (*Evaluator) EvalCacheSize added in v1.20.2

func (e *Evaluator) EvalCacheSize() int

EvalCacheSize reports memoized module evaluations.

func (*Evaluator) EvaluateModule

func (e *Evaluator) EvaluateModule(
	ctx context.Context,
	dir string,
	inputs map[string]cty.Value,
) (resources []ResolvedResource, outputs map[string]cty.Value, visitedChildDirs map[string]bool, err error)

EvaluateModule evaluates the module rooted at dir with the given inputs and returns all resources materialized by this module and its nested modules. visitedChildDirs contains every child directory that was successfully evaluated as a module (i.e. dirs that should be suppressed from standalone scanning).

func (*Evaluator) ExpansionMaxRequested added in v1.20.0

func (e *Evaluator) ExpansionMaxRequested() int

ExpansionMaxRequested reports the largest requested instance count seen when truncating.

func (*Evaluator) ExpansionTruncations added in v1.20.0

func (e *Evaluator) ExpansionTruncations() int

ExpansionTruncations reports how many count/for_each/dynamic expansions hit a cap.

func (*Evaluator) FS added in v1.20.0

func (e *Evaluator) FS() vfs.FS

FS returns the filesystem the evaluator reads module and tfvars files through.

func (*Evaluator) ForgetRootParse added in v1.19.0

func (e *Evaluator) ForgetRootParse(dir string)

ForgetRootParse drops the parsed files of dir once it has been evaluated as a root module. The parse cache pays off for modules many roots call; a root is evaluated once, so keeping its files only holds memory until the scan ends. Anything that reaches dir again parses it again.

func (*Evaluator) Fork added in v1.19.0

func (e *Evaluator) Fork() *Evaluator

Fork returns an evaluator that can evaluate other roots concurrently with e. It shares e's settings and its parse and path caches; its evaluation cache, budget counters and skipped directories are its own.

func (*Evaluator) InstantiatedCount added in v1.12.1

func (e *Evaluator) InstantiatedCount() int

InstantiatedCount reports how many module resources have been charged against the scan-wide retained-document budget.

func (*Evaluator) InstantiationBudget added in v1.19.0

func (e *Evaluator) InstantiationBudget() int

InstantiationBudget reports the evaluator's instantiation budget; zero or less means none.

func (*Evaluator) KeyMemoSize added in v1.20.2

func (e *Evaluator) KeyMemoSize() int

KeyMemoSize reports collections retained so their digests stay valid.

func (*Evaluator) LoadRootVars added in v1.15.0

func (e *Evaluator) LoadRootVars(dir string) map[string]cty.Value

LoadRootVars reads the variable definitions files Terraform loads on its own from dir (see tfpath.AutoloadedVarFiles) and returns a variable map for use as root-module inputs, reading through the evaluator's filesystem. Later files override earlier ones. Files that fail to read or parse are silently skipped. Only files listed in dir are read: MemFS records ReadFile misses as escalation signals, so absent files must not be probed.

func (*Evaluator) LoadRootVarsWithContext added in v1.20.2

func (e *Evaluator) LoadRootVarsWithContext(ctx context.Context, dir string) map[string]cty.Value

LoadRootVarsWithContext preserves the scan boundary for linked variable files.

func (*Evaluator) LocalMemoSize added in v1.20.2

func (e *Evaluator) LocalMemoSize() int

LocalMemoSize, KeyMemoSize and EvalCacheSize report what a root left retained.

func (*Evaluator) NotEvaluatedDirs added in v1.12.0

func (e *Evaluator) NotEvaluatedDirs() []string

NotEvaluatedDirs returns the module directories that were skipped rather than evaluated. Callers must keep the content of these directories in the scan: a directory can have both resolved and skipped call sites, and the skipped ones have no synthetic document standing in for them.

func (*Evaluator) ReleaseCaches added in v1.10.0

func (e *Evaluator) ReleaseCaches()

func (*Evaluator) ReleaseEvalCache added in v1.12.0

func (e *Evaluator) ReleaseEvalCache()

ReleaseEvalCache drops memoized module evaluations while keeping parsed HCL bodies. The key includes rootDir, so a later root does not reuse them, and each entry holds its subtree. The parse cache is keyed by directory alone and is kept.

func (*Evaluator) ReleaseLocalMemo added in v1.20.2

func (e *Evaluator) ReleaseLocalMemo()

ReleaseLocalMemo drops local values shared across module instances.

func (*Evaluator) ResetBudgetDemand added in v1.19.0

func (e *Evaluator) ResetBudgetDemand()

ResetBudgetDemand starts a new BudgetDemand measurement.

func (*Evaluator) ResetSpeculativeBudget added in v1.12.1

func (e *Evaluator) ResetSpeculativeBudget()

ResetSpeculativeBudget clears the counter for speculative sibling evaluation at a root boundary. That work is discarded once the root it belongs to is done.

The count of resources actually instantiated is deliberately not reset. Those become documents that live until the scan ends, so their bound has to span the scan; resetting it per root is what left the total unbounded when several scans ran concurrently on one pod.

func (*Evaluator) RestoreInstantiatedCount added in v1.12.1

func (e *Evaluator) RestoreInstantiatedCount(n int)

RestoreInstantiatedCount rolls back charges from a root whose evaluation failed after descendants were counted but before any documents were emitted.

func (*Evaluator) SetMaxInstantiated added in v1.12.0

func (e *Evaluator) SetMaxInstantiated(n int)

SetMaxInstantiated overrides the instantiation budget. A value of zero or less disables it.

func (*Evaluator) SetMergeAllow added in v1.15.0

func (e *Evaluator) SetMergeAllow(allow map[string]struct{})

SetMergeAllow restricts OpenTofu twin-shadowing to inventory paths.

func (*Evaluator) SetRemoteResolver added in v1.8.0

func (e *Evaluator) SetRemoteResolver(r RemoteResolver)

func (*Evaluator) SetTrackModuleInstances added in v1.20.0

func (e *Evaluator) SetTrackModuleInstances(track bool)

SetTrackModuleInstances makes evaluations record the module calls they evaluate, for TakeModuleInstances. Forks inherit the setting.

func (*Evaluator) TakeExpansionStats added in v1.20.0

func (e *Evaluator) TakeExpansionStats() (hits, maxRequested int)

TakeExpansionStats returns and clears truncation counters recorded since the last take.

func (*Evaluator) TakeModuleInstances added in v1.20.0

func (e *Evaluator) TakeModuleInstances() []ModuleInstance

TakeModuleInstances returns the module calls the last EvaluateModule evaluated, nothing when it failed, and forgets them.

func (*Evaluator) TakeNotEvaluatedDirs added in v1.19.0

func (e *Evaluator) TakeNotEvaluatedDirs() []string

TakeNotEvaluatedDirs returns the directories skipped since the last call and forgets them.

type ModuleInstance added in v1.20.0

type ModuleInstance struct {
	Dir           string
	ModuleAddress string
	CallChain     []CallSite
}

ModuleInstance is one evaluated call of a module directory, whether or not the module declares resources.

type ModuleScope added in v1.20.0

type ModuleScope struct {
	Locals map[string]hclsyntax.Expression
	// Bodies are the module's parsed files, from which the resource and data
	// blocks a value references can be read.
	Bodies []*hclsyntax.Body
	Var    cty.Value
	Local  cty.Value
	// contains filtered or unexported fields
}

ModuleScope is a module's local value expressions with the var and local values its blocks were evaluated with, so a value can be traced back to the module inputs it reads after evaluation. Read-only after evaluation.

type RemoteResolver added in v1.8.0

type RemoteResolver func(
	source, version, callerFile, moduleName string,
) (dir, packageRoot string, ok bool)

RemoteResolver maps a non-local module call to its selected directory and acquired package root.

type ResolvedResource

type ResolvedResource struct {
	Type       string
	Name       string
	Attributes map[string]cty.Value
	// Body is the resource's HCL body, used to recover the reference text of
	// attributes evaluation could not resolve. It is not consulted during
	// evaluation, so recovered references never feed back into resolved values.
	Body *hclsyntax.Body
	// Scope is the module declaring the resource as it was evaluated.
	Scope *ModuleScope
	// Iteration holds the each or count value of an expanded instance, nil
	// for a block without count or for_each.
	Iteration map[string]cty.Value

	// Source location and module address for finding attribution.
	DefinedIn     string
	DefLine       int
	DefEndLine    int
	DefColumn     int
	DefEndColumn  int
	ModuleAddress string // "" for root module resources
	CallChain     []CallSite
	// ExpansionTruncated is set when count/for_each produced more instances than
	// maxCountExpansion; the source block must stay in the scan for the rest.
	ExpansionTruncated bool
	// ExpansionTotal is the full count/for_each size when ExpansionTruncated.
	ExpansionTotal int
	// ExpansionKeys is every for_each key when truncated and within
	// maxExpansionShape, so ref injection can pad omitted keys as unknown.
	ExpansionKeys []string
	// DynamicCounts is how many blocks each dynamic block of Body generated for
	// this instance, so generated blocks can be mapped back to their sources.
	DynamicCounts DynamicCounts

	// Data marks an instance of a data block rather than a resource.
	Data bool
}

ResolvedResource is a resource block after evaluation with attributes resolved to concrete cty values where possible, unknown otherwise.

Jump to

Keyboard shortcuts

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