tfeval

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package tfeval evaluates local Terraform modules: bind inputs, resolve locals, recurse into nested modules, emit resources with concrete cty values where possible. Anything still unresolvable (e.g. data sources) stays cty.UnknownVal, not sentinels.

Index

Constants

View Source
const UnknownAttributePlaceholder = "__DD_TFEVAL_UNKNOWN__"

UnknownAttributePlaceholder is stored for cty unknown values when converting to the document shape rules consume, so keys stay present and MissingAttribute checks do not treat unresolved expressions 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: a value evaluation could not resolve falls back to its reference text, or to UnknownAttributePlaceholder when it has none, so presence-based rules do not fire false positives on unresolved expressions.

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

func StripGetterPrefix

func StripGetterPrefix(source string) string

StripGetterPrefix removes go-getter scheme prefixes so the source can be treated as a path. Compound prefixes like "git::file://./path" are fully stripped in two passes.

Types

type CallSite

type CallSite struct {
	ModuleName      string
	Source          string
	Version         string
	CalledFrom      string
	CalledLine      int
	CalledEndLine   int
	CalledColumn    int
	CalledEndColumn int
}

CallSite records one hop in a module call chain.

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) 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) 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) 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) LoadRootVars added in v1.15.0

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

LoadRootVars reads terraform.tfvars and *.auto.tfvars from dir and returns a variable map for use as root-module inputs, reading through the evaluator's filesystem. Terraform loads terraform.tfvars first, then *.auto.tfvars in lexicographic order; later files override earlier ones. Files that fail to read or parse are silently skipped.

Candidates are Stat-probed before reading: MemFS records ReadFile misses as escalation signals but not Stat misses, so the always-probed terraform.tfvars must not surface as a missing file for a workspace that has none.

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. Every entry holds the resolved resources of its whole subtree, so retaining entries for a whole repository scales peak memory with the number of roots. Entries are reusable across roots now that the key is the inputs alone, but in practice each root passes its own values to the shared modules it calls, so the hit rate across roots is low and not worth that peak. The parse cache is keyed by directory alone, genuinely is shared by every root, and is kept.

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)

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

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

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