terraform

package
v0.50.1 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2024 License: MPL-2.0, MPL-2.0 Imports: 24 Imported by: 1

README

Forked Terraform packages

This directory contains a subset of code from Terraform's internal packages. However, the implementation is not exactly the same, it is just a fork, and simplifications and changes have been made according to our project.

Previously, TFLint uses Terraform as a library, but due to the package internalization, it is no longer possible to import from external packages such as TFLint. This is why TFLint has its own fork.

This package provides functionality for static analysis of Terraform Language.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func VariableValues added in v0.41.0

func VariableValues(config *Config, values ...InputValues) (map[string]map[string]cty.Value, hcl.Diagnostics)

VariableValues returns a value map based on configuration, environment variables, and external input values. External input values take precedence over configuration defaults, environment variables, and the last one passed takes precedence.

func Workspace added in v0.41.0

func Workspace() string

Types

type CallModuleType added in v0.50.0

type CallModuleType int32

CallModuleType is a type of module to call. This is primarily used to control module walker behavior.

const (
	// CallAllModule calls all (local/remote) modules.
	CallAllModule CallModuleType = iota

	// CallLocalModule calls only local modules.
	CallLocalModule

	// CallNoModule does not call any modules.
	CallNoModule
)

func AsCallModuleType added in v0.50.0

func AsCallModuleType(s string) (CallModuleType, error)

func (CallModuleType) String added in v0.50.0

func (c CallModuleType) String() string

type CallStack added in v0.42.1

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

func NewCallStack added in v0.42.1

func NewCallStack() *CallStack

func (*CallStack) Clear added in v0.42.1

func (g *CallStack) Clear()

func (*CallStack) Empty added in v0.42.1

func (g *CallStack) Empty() bool

func (*CallStack) Pop added in v0.42.1

func (g *CallStack) Pop()

func (*CallStack) Push added in v0.42.1

func (g *CallStack) Push(addr addrs.Reference) hcl.Diagnostics

func (*CallStack) String added in v0.42.1

func (g *CallStack) String() string

type Config

type Config struct {
	// RootModule points to the Config for the root module within the same
	// module tree as this module. If this module _is_ the root module then
	// this is self-referential.
	Root *Config

	// Path is a sequence of module logical names that traverse from the root
	// module to this config. Path is empty for the root module.
	Path addrs.Module

	// ChildModules points to the Config for each of the direct child modules
	// called from this module. The keys in this map match the keys in
	// Module.ModuleCalls.
	Children map[string]*Config

	// Module points to the object describing the configuration for the
	// various elements (variables, resources, etc) defined by this module.
	Module *Module
}

A Config is a node in the tree of modules within a configuration.

The module tree is constructed by following ModuleCall instances recursively through the root module transitively into descendent modules.

func BuildConfig

func BuildConfig(root *Module, walker ModuleWalker) (*Config, hcl.Diagnostics)

BuildConfig constructs a Config from a root module by loading all of its descendent modules via the given ModuleWalker.

The result is a module tree that has so far only had basic module- and file-level invariants validated. If the returned diagnostics contains errors, the returned module tree may be incomplete but can still be used carefully for static analysis.

func NewEmptyConfig

func NewEmptyConfig() *Config

NewEmptyConfig constructs a single-node configuration tree with an empty root module. This is generally a pretty useless thing to do, so most callers should instead use BuildConfig.

func (*Config) DescendentForInstance

func (c *Config) DescendentForInstance(path addrs.ModuleInstance) *Config

DescendentForInstance returns the descendent config that has the given instance path beneath the receiver, or nil if there is no such module.

type ContextMeta

type ContextMeta struct {
	Env                string
	OriginalWorkingDir string
}

type Evaluator

type Evaluator struct {
	Meta           *ContextMeta
	ModulePath     addrs.ModuleInstance
	Config         *Config
	VariableValues map[string]map[string]cty.Value
	CallStack      *CallStack
}

func (*Evaluator) EvaluateExpr

func (e *Evaluator) EvaluateExpr(expr hcl.Expression, wantType cty.Type) (cty.Value, hcl.Diagnostics)

EvaluateExpr takes the given HCL expression and evaluates it to produce a value.

func (*Evaluator) ExpandBlock added in v0.43.0

func (e *Evaluator) ExpandBlock(body hcl.Body, schema *hclext.BodySchema) (hcl.Body, hcl.Diagnostics)

ExpandBlock expands "dynamic" blocks and resources/modules with count/for_each.

In the expanded body, the content can be retrieved with the HCL API without being aware of the differences in the dynamic block schema. Also, the number of blocks and attribute values will be the same as the expanded result.

type InputValue

type InputValue struct {
	Value cty.Value
}

type InputValues

type InputValues map[string]*InputValue

func DefaultVariableValues added in v0.41.0

func DefaultVariableValues(configs map[string]*Variable) InputValues

DefaultVariableValues returns InputValues using the default values of variables declared in the configuration.

func EnvironmentVariableValues added in v0.41.0

func EnvironmentVariableValues(declVars map[string]*Variable) (InputValues, hcl.Diagnostics)

EnvironmentVariableValues looks up `TF_VAR_*` env variables and returns InputValues. Declared variables are required because the parsing mode of the variable value is type-dependent. However, in the case of environment variables, no error is returned even if the variable is not declared.

func ParseVariableValues added in v0.41.0

func ParseVariableValues(vars []string, declVars map[string]*Variable) (InputValues, hcl.Diagnostics)

ParseVariableValues parses the variable values passed as CLI flags and returns InputValues. Declared variables are required because the parsing mode of the variable value is type-dependent. Return an error if the variable is not declared.

func (InputValues) Override

func (vv InputValues) Override(others ...InputValues) InputValues

type Loader added in v0.44.0

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

Loader is a fork of configload.Loader. The instance is the main entry-point for loading configurations via this package.

It extends the general config-loading functionality in the Parser to support loading full configurations using modules and gathering input values from values files.

func NewLoader added in v0.44.0

func NewLoader(fs afero.Afero, originalWd string) (*Loader, error)

NewLoader creates and returns a loader that reads configuration from the given filesystem.

The loader has some internal state about the modules that are currently installed, which is read from disk as part of this function. Note that this will always read against the current directory unless TF_DATA_DIR is set.

If an original working dir is passed, the paths of the loaded files will be relative to that directory.

func (*Loader) Files added in v0.44.0

func (l *Loader) Files() map[string]*hcl.File

func (*Loader) IsConfigDir added in v0.44.0

func (l *Loader) IsConfigDir(path string) bool

func (*Loader) LoadConfig added in v0.44.0

func (l *Loader) LoadConfig(dir string, callModuleType CallModuleType) (*Config, hcl.Diagnostics)

LoadConfig reads the Terraform module in the given directory and uses it as the root module to build the static module tree that represents a configuration.

func (*Loader) LoadConfigDirFiles added in v0.44.0

func (l *Loader) LoadConfigDirFiles(dir string) (map[string]*hcl.File, hcl.Diagnostics)

func (*Loader) LoadValuesFiles added in v0.44.0

func (l *Loader) LoadValuesFiles(dir string, files ...string) ([]InputValues, hcl.Diagnostics)

LoadValuesFiles reads Terraform's autoloaded values files in the given directory and returns terraform.InputValues in order of priority.

The second and subsequent arguments are given the paths of value files to be read manually. Argument order matches precedence.

func (*Loader) Sources added in v0.44.0

func (l *Loader) Sources() map[string][]byte

type Local added in v0.42.0

type Local struct {
	Name string
	Expr hcl.Expression

	DeclRange hcl.Range
}

type Module

type Module struct {
	Resources   map[string]map[string]*Resource
	Variables   map[string]*Variable
	Locals      map[string]*Local
	ModuleCalls map[string]*ModuleCall

	SourceDir string

	Sources map[string][]byte
	Files   map[string]*hcl.File
	// contains filtered or unexported fields
}

func NewEmptyModule

func NewEmptyModule() *Module

func (*Module) PartialContent

func (m *Module) PartialContent(schema *hclext.BodySchema, ctx *Evaluator) (*hclext.BodyContent, hcl.Diagnostics)

PartialContent extracts body content from Terraform configurations based on the passed schema. Basically, this function is a wrapper for hclext.PartialContent, but in some ways it reproduces Terraform language semantics.

  1. Supports overriding files https://developer.hashicorp.com/terraform/language/files/override
  2. Expands "dynamic" blocks https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks
  3. Expands resource/module depends on the meta-arguments https://developer.hashicorp.com/terraform/language/meta-arguments/count https://developer.hashicorp.com/terraform/language/meta-arguments/for_each

But 2 and 3 won't run if you didn't pass the evaluation context.

func (*Module) Rebuild added in v0.47.0

func (m *Module) Rebuild(sources map[string][]byte) hcl.Diagnostics

Rebuild rebuilds the module from the passed sources. The main purpose of this is to apply autofixes in the module.

type ModuleCall

type ModuleCall struct {
	Name          string
	SourceAddr    addrs.ModuleSource
	SourceAddrRaw string

	DeclRange hcl.Range
}

type ModuleRequest

type ModuleRequest struct {
	// Name is the "logical name" of the module call within configuration.
	// This is provided in case the name is used as part of a storage key
	// for the module, but implementations must otherwise treat it as an
	// opaque string.
	Name string

	// Path is a list of logical names that traverse from the root module to
	// this module. This can be used, for example, to form a lookup key for
	// each distinct module call in a configuration, allowing for multiple
	// calls with the same name at different points in the tree.
	Path addrs.Module

	// SourceAddr is the source address string provided by the user in
	// configuration.
	SourceAddr addrs.ModuleSource

	// Parent is the partially-constructed module tree node that the loaded
	// module will be added to. Callers may refer to any field of this
	// structure except Children, which is still under construction when
	// ModuleRequest objects are created and thus has undefined content.
	// The main reason this is provided is to build the full path for the module.
	Parent *Config

	// CallRange is the source range for the header of the "module" block
	// in configuration that prompted this request. This can be used as the
	// subject of an error diagnostic that relates to the module call itself.
	CallRange hcl.Range
}

ModuleRequest is used with the ModuleWalker interface to describe a child module that must be loaded.

type ModuleWalker

type ModuleWalker interface {
	// LoadModule finds and loads a requested child module.
	//
	// If errors are detected during loading, implementations should return them
	// in the diagnostics object. If the diagnostics object contains any errors
	// then the caller will tolerate the returned module being nil or incomplete.
	// If no errors are returned, it should be non-nil and complete.
	//
	// Full validation need not have been performed but an implementation should
	// ensure that the basic file- and module-validations performed by the
	// LoadConfigDir function (valid syntax, no namespace collisions, etc) have
	// been performed before returning a module.
	LoadModule(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics)
}

A ModuleWalker knows how to find and load a child module given details about the module to be loaded and a reference to its partially-loaded parent Config.

type ModuleWalkerFunc

type ModuleWalkerFunc func(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics)

ModuleWalkerFunc is an implementation of ModuleWalker that directly wraps a callback function, for more convenient use of that interface.

func (ModuleWalkerFunc) LoadModule

func (f ModuleWalkerFunc) LoadModule(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics)

LoadModule implements ModuleWalker.

type Parser

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

Parser is a fork of configs.Parser. This is the main interface to read configuration files and other related files from disk.

It retains a cache of all files that are loaded so that they can be used to create source code snippets in diagnostics, etc.

func NewParser

func NewParser(fs afero.Fs) *Parser

NewParser creates and returns a new Parser that reads files from the given filesystem. If a nil filesystem is passed then the system's "real" filesystem will be used, via afero.OsFs.

func (*Parser) Exists added in v0.50.0

func (p *Parser) Exists(path string) bool

Exists returns true if the given path exists in fs.

func (*Parser) Files added in v0.39.2

func (p *Parser) Files() map[string]*hcl.File

Files returns a map of the cached HCL file objects for all files that have been loaded through this parser, with source filenames (as requested when each file was opened) as the keys.

func (*Parser) IsConfigDir

func (p *Parser) IsConfigDir(baseDir, path string) bool

IsConfigDir determines whether the given path refers to a directory that exists and contains at least one Terraform config file (with a .tf or .tf.json extension.)

func (*Parser) LoadConfigDir

func (p *Parser) LoadConfigDir(baseDir, dir string) (*Module, hcl.Diagnostics)

LoadConfigDir reads the .tf and .tf.json files in the given directory and then combines these files into a single Module.

If this method returns nil, that indicates that the given directory does not exist at all or could not be opened for some reason. Callers may wish to detect this case and ignore the returned diagnostics so that they can produce a more context-aware error message in that case.

If this method returns a non-nil module while error diagnostics are returned then the module may be incomplete but can be used carefully for static analysis.

This file does not consider a directory with no files to be an error, and will simply return an empty module in that case.

.tf files are parsed using the HCL native syntax while .tf.json files are parsed using the HCL JSON syntax.

If a baseDir is passed, the loaded files are assumed to be loaded from that directory. However, SourceDir does not contain baseDir because it affects `path.module` and `path.root` values.

func (*Parser) LoadConfigDirFiles added in v0.44.0

func (p *Parser) LoadConfigDirFiles(baseDir, dir string) (map[string]*hcl.File, hcl.Diagnostics)

LoadConfigDirFiles reads the .tf and .tf.json files in the given directory and then returns these files as a map of file path.

The difference with LoadConfigDir is that it returns hcl.File instead of a single module. This is useful when parsing HCL files in a context outside of Terraform.

If a baseDir is passed, the loaded files are assumed to be loaded from that directory.

func (*Parser) LoadValuesFile

func (p *Parser) LoadValuesFile(baseDir, path string) (map[string]cty.Value, hcl.Diagnostics)

LoadValuesFile reads the file at the given path and parses it as a "values file", which is an HCL config file whose top-level attributes are treated as arbitrary key.value pairs.

If the file cannot be read -- for example, if it does not exist -- then a nil map will be returned along with error diagnostics. Callers may wish to disregard the returned diagnostics in this case and instead generate their own error message(s) with additional context.

If the returned diagnostics has errors when a non-nil map is returned then the map may be incomplete but should be valid enough for careful static analysis.

If a baseDir is passed, the loaded file is assumed to be loaded from that directory.

func (*Parser) Sources

func (p *Parser) Sources() map[string][]byte

Sources returns a map of the cached source buffers for all files that have been loaded through this parser, with source filenames (as requested when each file was opened) as the keys.

type Resource added in v0.42.0

type Resource struct {
	Name string
	Type string

	DeclRange hcl.Range
	TypeRange hcl.Range
}

type Variable

type Variable struct {
	Name    string
	Default cty.Value

	Type           cty.Type
	ConstraintType cty.Type
	TypeDefaults   *typeexpr.Defaults

	DeclRange hcl.Range

	ParsingMode VariableParsingMode
	Sensitive   bool
	Nullable    bool
}

type VariableParsingMode

type VariableParsingMode rune

VariableParsingMode defines how values of a particular variable given by text-only mechanisms (command line arguments and environment variables) should be parsed to produce the final value.

const VariableParseHCL VariableParsingMode = 'H'

VariableParseHCL is a variable parsing mode that attempts to parse the given string as an HCL expression and returns the result.

const VariableParseLiteral VariableParsingMode = 'L'

VariableParseLiteral is a variable parsing mode that just takes the given string directly as a cty.String value.

func (VariableParsingMode) Parse

func (m VariableParsingMode) Parse(name, value string) (cty.Value, hcl.Diagnostics)

Parse uses the receiving parsing mode to process the given variable value string, returning the result along with any diagnostics.

A VariableParsingMode does not know the expected type of the corresponding variable, so it's the caller's responsibility to attempt to convert the result to the appropriate type and return to the user any diagnostics that conversion may produce.

The given name is used to create a synthetic filename in case any diagnostics must be generated about the given string value. This should be the name of the root module variable whose value will be populated from the given string.

If the returned diagnostics has errors, the returned value may not be valid.

Directories

Path Synopsis
Package ipaddr is a fork of a subset of the Go standard "net" package which retains parsing behaviors from Go 1.16 or earlier.
Package ipaddr is a fork of a subset of the Go standard "net" package which retains parsing behaviors from Go 1.16 or earlier.
types
Package types contains non-standard cty types used only within Terraform.
Package types contains non-standard cty types used only within Terraform.
Package tfhcl is a fork of hcl/ext/dynblock.
Package tfhcl is a fork of hcl/ext/dynblock.

Jump to

Keyboard shortcuts

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