Back to godoc.org

Package configs

v0.13.3
Latest Go to latest

The latest major version is .

Published: Sep 16, 2020 | License: MPL-2.0 | Module: github.com/hashicorp/terraform

Overview

Package configs contains types that represent Terraform configurations and the different elements thereof.

The functionality in this package can be used for some static analyses of Terraform configurations, but this package generally exposes representations of the configuration source code rather than the result of evaluating these objects. The sibling package "lang" deals with evaluation of structures and expressions in the configuration.

Due to its close relationship with HCL, this package makes frequent use of types from the HCL API, including raw HCL diagnostic messages. Such diagnostics can be converted into Terraform-flavored diagnostics, if needed, using functions in the sibling package tfdiags.

The Parser type is the main entry-point into this package. The LoadConfigDir method can be used to load a single module directory, and then a full configuration (including any descendent modules) can be produced using the top-level BuildConfig method.

Index

func IsEmptyDir

func IsEmptyDir(path string) (bool, error)

IsEmptyDir returns true if the given filesystem path contains no Terraform configuration files.

Unlike the methods of the Parser type, this function always consults the real filesystem, and thus it isn't appropriate to use when working with configuration loaded from a plan file.

func IsIgnoredFile

func IsIgnoredFile(name string) bool

IsIgnoredFile returns true if the given filename (which must not have a directory path ahead of it) should be ignored as e.g. an editor swap file.

func MergeBodies

func MergeBodies(base, override hcl.Body) hcl.Body

MergeBodies creates a new HCL body that contains a combination of the given base and override bodies. Attributes and blocks defined in the override body take precedence over those of the same name defined in the base body.

If any block of a particular type appears in "override" then it will replace _all_ of the blocks of the same type in "base" in the new body.

func ParseProviderConfigCompact

func ParseProviderConfigCompact(traversal hcl.Traversal) (addrs.LocalProviderConfig, tfdiags.Diagnostics)

ParseProviderConfigCompact parses the given absolute traversal as a relative provider address in compact form. The following are examples of traversals that can be successfully parsed as compact relative provider configuration addresses:

aws
aws.foo

This function will panic if given a relative traversal.

If the returned diagnostics contains errors then the result value is invalid and must not be used.

func ParseProviderConfigCompactStr

func ParseProviderConfigCompactStr(str string) (addrs.LocalProviderConfig, tfdiags.Diagnostics)

ParseProviderConfigCompactStr is a helper wrapper around ParseProviderConfigCompact that takes a string and parses it with the HCL native syntax traversal parser before interpreting it.

This should be used only in specialized situations since it will cause the created references to not have any meaningful source location information. If a reference string is coming from a source that should be identified in error messages then the caller should instead parse it directly using a suitable function from the HCL API and pass the traversal itself to ParseProviderConfigCompact.

Error diagnostics are returned if either the parsing fails or the analysis of the traversal fails. There is no way for the caller to distinguish the two kinds of diagnostics programmatically. If error diagnostics are returned then the returned address is invalid.

func SynthBody

func SynthBody(filename string, values map[string]cty.Value) hcl.Body

SynthBody produces a synthetic hcl.Body that behaves as if it had attributes corresponding to the elements given in the values map.

This is useful in situations where, for example, values provided on the command line can override values given in configuration, using MergeBodies.

The given filename is used in case any diagnostics are returned. Since the created body is synthetic, it is likely that this will not be a "real" filename. For example, if from a command line argument it could be a representation of that argument's name, such as "-var=...".

type Backend

type Backend struct {
	Type   string
	Config hcl.Body

	TypeRange hcl.Range
	DeclRange hcl.Range
}

Backend represents a "backend" block inside a "terraform" block in a module or file.

func (*Backend) Hash

func (b *Backend) Hash(schema *configschema.Block) int

Hash produces a hash value for the reciever that covers the type and the portions of the config that conform to the given schema.

If the config does not conform to the schema then the result is not meaningful for comparison since it will be based on an incomplete result.

As an exception, required attributes in the schema are treated as optional for the purpose of hashing, so that an incomplete configuration can still be hashed. Other errors, such as extraneous attributes, have no such special case.

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

	// ParentModule points to the Config for the module that directly calls
	// this module. If this is the root module then this field is nil.
	Parent *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.
	//
	// This should only be used to display paths to the end-user in rare cases
	// where we are talking about the static module tree, before module calls
	// have been resolved. In most cases, an addrs.ModuleInstance describing
	// a node in the dynamic module tree is better, since it will then include
	// any keys resulting from evaluating "count" and "for_each" arguments.
	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

	// CallRange is the source range for the header of the module block that
	// requested this module.
	//
	// This field is meaningless for the root module, where its contents are undefined.
	CallRange hcl.Range

	// SourceAddr is the source address that the referenced module was requested
	// from, as specified in configuration.
	//
	// This field is meaningless for the root module, where its contents are undefined.
	SourceAddr string

	// SourceAddrRange is the location in the configuration source where the
	// SourceAddr value was set, for use in diagnostic messages.
	//
	// This field is meaningless for the root module, where its contents are undefined.
	SourceAddrRange hcl.Range

	// Version is the specific version that was selected for this module,
	// based on version constraints given in configuration.
	//
	// This field is nil if the module was loaded from a non-registry source,
	// since versions are not supported for other sources.
	//
	// This field is meaningless for the root module, where it will always
	// be nil.
	Version *version.Version
}

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.

A module tree described in *this* package represents the static tree represented by configuration. During evaluation a static ModuleNode may expand into zero or more module instances depending on the use of count and for_each configuration attributes within each call.

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) AllModules

func (c *Config) AllModules() []*Config

AllModules returns a slice of all the receiver and all of its descendent nodes in the module tree, in the same order they would be visited by DeepEach.

func (*Config) DeepEach

func (c *Config) DeepEach(cb func(c *Config))

DeepEach calls the given function once for each module in the tree, starting with the receiver.

A parent is always called before its children and children of a particular node are visited in lexicographic order by their names.

func (*Config) Depth

func (c *Config) Depth() int

Depth returns the number of "hops" the receiver is from the root of its module tree, with the root module having a depth of zero.

func (*Config) Descendent

func (c *Config) Descendent(path addrs.Module) *Config

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

The path traverses the static module tree, prior to any expansion to handle count and for_each arguments.

An empty path will just return the receiver, and is therefore pointless.

func (*Config) DescendentForInstance

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

DescendentForInstance is like Descendent except that it accepts a path to a particular module instance in the dynamic module graph, returning the node from the static module graph that corresponds to it.

All instances created by a particular module call share the same configuration, so the keys within the given path are disregarded.

func (*Config) ProviderForConfigAddr

func (c *Config) ProviderForConfigAddr(addr addrs.LocalProviderConfig) addrs.Provider

ProviderForConfigAddr returns the FQN for a given addrs.ProviderConfig, first by checking for the provider in module.ProviderRequirements and falling back to addrs.NewDefaultProvider if it is not found.

func (*Config) ProviderRequirements

func (c *Config) ProviderRequirements() (getproviders.Requirements, hcl.Diagnostics)

ProviderRequirements searches the full tree of modules under the receiver for both explicit and implicit dependencies on providers.

The result is a full manifest of all of the providers that must be available in order to work with the receiving configuration.

If the returned diagnostics includes errors then the resulting Requirements may be incomplete.

func (*Config) ProviderRequirementsByModule

func (c *Config) ProviderRequirementsByModule() (*ModuleRequirements, hcl.Diagnostics)

ProviderRequirementsByModule searches the full tree of modules under the receiver for both explicit and implicit dependencies on providers, constructing a tree where the requirements are broken out by module.

If the returned diagnostics includes errors then the resulting Requirements may be incomplete.

func (*Config) ProviderTypes

func (c *Config) ProviderTypes() []addrs.Provider

ProviderTypes returns the FQNs of each distinct provider type referenced in the receiving configuration.

This is a helper for easily determining which provider types are required to fully interpret the configuration, though it does not include version information and so callers are expected to have already dealt with provider version selection in an earlier step and have identified suitable versions for each provider.

func (*Config) ResolveAbsProviderAddr

func (c *Config) ResolveAbsProviderAddr(addr addrs.ProviderConfig, inModule addrs.Module) addrs.AbsProviderConfig

ResolveAbsProviderAddr returns the AbsProviderConfig represented by the given ProviderConfig address, which must not be nil or this method will panic.

If the given address is already an AbsProviderConfig then this method returns it verbatim, and will always succeed. If it's a LocalProviderConfig then it will consult the local-to-FQN mapping table for the given module to find the absolute address corresponding to the given local one.

The module address to resolve local addresses in must be given in the second argument, and must refer to a module that exists under the receiver or else this method will panic.

type Connection

type Connection struct {
	Config hcl.Body

	DeclRange hcl.Range
}

Connection represents a "connection" block when used within either a "resource" or "provisioner" block in a module or file.

type CountValueType

type CountValueType byte

CountValueType is the type of the count variable that is referenced.

const (
	CountValueInvalid CountValueType = iota
	CountValueIndex
)

type CountVariable

type CountVariable struct {
	Type CountValueType
	// contains filtered or unexported fields
}

CountVariable is a variable for referencing information about the count.

func NewCountVariable

func NewCountVariable(key string) (*CountVariable, error)

func (*CountVariable) FullKey

func (c *CountVariable) FullKey() string

func (CountVariable) SourceRange

func (r CountVariable) SourceRange() tfdiags.SourceRange

type File

type File struct {
	CoreVersionConstraints []VersionConstraint

	ActiveExperiments experiments.Set

	Backends          []*Backend
	ProviderConfigs   []*Provider
	ProviderMetas     []*ProviderMeta
	RequiredProviders []*RequiredProviders

	Variables []*Variable
	Locals    []*Local
	Outputs   []*Output

	ModuleCalls []*ModuleCall

	ManagedResources []*Resource
	DataResources    []*Resource
}

File describes the contents of a single configuration file.

Individual files are not usually used alone, but rather combined together with other files (conventionally, those in the same directory) to produce a *Module, using NewModule.

At the level of an individual file we represent directly the structural elements present in the file, without any attempt to detect conflicting declarations. A File object can therefore be used for some basic static analysis of individual elements, but must be built into a Module to detect duplicate declarations.

type InterpolatedVariable

type InterpolatedVariable interface {
	FullKey() string
	SourceRange() tfdiags.SourceRange
}

An InterpolatedVariable is a variable reference within an interpolation.

Implementations of this interface represents various sources where variables can come from: user variables, resources, etc.

func DetectVariables

func DetectVariables(root ast.Node) ([]InterpolatedVariable, error)

DetectVariables takes an AST root and returns all the interpolated variables that are detected in the AST tree.

func NewInterpolatedVariable

func NewInterpolatedVariable(v string) (InterpolatedVariable, error)

type Local

type Local struct {
	Name string
	Expr hcl.Expression

	DeclRange hcl.Range
}

Local represents a single entry from a "locals" block in a module or file. The "locals" block itself is not represented, because it serves only to provide context for us to interpret its contents.

func (*Local) Addr

func (l *Local) Addr() addrs.LocalValue

Addr returns the address of the local value declared by the receiver, relative to its containing module.

type LocalVariable

type LocalVariable struct {
	Name string
	// contains filtered or unexported fields
}

A LocalVariable is a variable that references a local value defined within the current module, via a "locals" block. This looks like "${local.foo}".

func NewLocalVariable

func NewLocalVariable(key string) (*LocalVariable, error)

func (*LocalVariable) FullKey

func (v *LocalVariable) FullKey() string

func (*LocalVariable) GoString

func (v *LocalVariable) GoString() string

func (LocalVariable) SourceRange

func (r LocalVariable) SourceRange() tfdiags.SourceRange

type ManagedResource

type ManagedResource struct {
	Connection   *Connection
	Provisioners []*Provisioner

	CreateBeforeDestroy bool
	PreventDestroy      bool
	IgnoreChanges       []hcl.Traversal
	IgnoreAllChanges    bool

	CreateBeforeDestroySet bool
	PreventDestroySet      bool
}

ManagedResource represents a "resource" block in a module or file.

type Module

type Module struct {

	// Any other caller that constructs a module directly with NewModule may
	// assign a suitable value to this attribute before using it for other
	// purposes. It should be treated as immutable by all consumers of Module
	// values.
	SourceDir string

	CoreVersionConstraints []VersionConstraint

	ActiveExperiments experiments.Set

	Backend              *Backend
	ProviderConfigs      map[string]*Provider
	ProviderRequirements *RequiredProviders
	ProviderLocalNames   map[addrs.Provider]string
	ProviderMetas        map[addrs.Provider]*ProviderMeta

	Variables map[string]*Variable
	Locals    map[string]*Local
	Outputs   map[string]*Output

	ModuleCalls map[string]*ModuleCall

	ManagedResources map[string]*Resource
	DataResources    map[string]*Resource
}

Module is a container for a set of configuration constructs that are evaluated within a common namespace.

func NewModule

func NewModule(primaryFiles, overrideFiles []*File) (*Module, hcl.Diagnostics)

NewModule takes a list of primary files and a list of override files and produces a *Module by combining the files together.

If there are any conflicting declarations in the given files -- for example, if the same variable name is defined twice -- then the resulting module will be incomplete and error diagnostics will be returned. Careful static analysis of the returned Module is still possible in this case, but the module will probably not be semantically valid.

func (*Module) ImpliedProviderForUnqualifiedType

func (m *Module) ImpliedProviderForUnqualifiedType(pType string) addrs.Provider

ImpliedProviderForUnqualifiedType returns the provider FQN for a given type, first by looking up the type in the provider requirements map, and falling back to an implied default provider.

The intended behaviour is that configuring a provider with local name "foo" in a required_providers block will result in resources with type "foo" using that provider.

func (*Module) LocalNameForProvider

func (m *Module) LocalNameForProvider(p addrs.Provider) string

LocalNameForProvider returns the module-specific user-supplied local name for a given provider FQN, or the default local name if none was supplied.

func (*Module) ProviderForLocalConfig

func (m *Module) ProviderForLocalConfig(pc addrs.LocalProviderConfig) addrs.Provider

ProviderForLocalConfig returns the provider FQN for a given LocalProviderConfig, based on its local name.

func (*Module) ResourceByAddr

func (m *Module) ResourceByAddr(addr addrs.Resource) *Resource

ResourceByAddr returns the configuration for the resource with the given address, or nil if there is no such resource.

type ModuleCall

type ModuleCall struct {
	Name string

	SourceAddr      string
	SourceAddrRange hcl.Range
	SourceSet       bool

	Config hcl.Body

	Version VersionConstraint

	Count   hcl.Expression
	ForEach hcl.Expression

	Providers []PassedProviderConfig

	DependsOn []hcl.Traversal

	DeclRange hcl.Range
}

ModuleCall represents a "module" block in a module or file.

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. It is guaranteed to have already been validated as an
	// HCL identifier and UTF-8 encoded.
	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 string

	// SourceAddrRange is the source range for the SourceAddr value as it
	// was provided in configuration. This can and should be used to generate
	// diagnostics about the source address having invalid syntax, referring
	// to a non-existent object, etc.
	SourceAddrRange hcl.Range

	// VersionConstraint is the version constraint applied to the module in
	// configuration. This data structure includes the source range for
	// the constraint, which can and should be used to generate diagnostics
	// about constraint-related issues, such as constraints that eliminate all
	// available versions of a module whose source is otherwise valid.
	VersionConstraint VersionConstraint

	// 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 so that full module paths can
	// be constructed for uniqueness.
	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,
	// rather than to either its source address or its version number.
	CallRange hcl.Range
}

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

type ModuleRequirements

type ModuleRequirements struct {
	Name         string
	SourceAddr   string
	SourceDir    string
	Requirements getproviders.Requirements
	Children     map[string]*ModuleRequirements
}

ModuleRequirements represents the provider requirements for an individual module, along with references to any child modules. This is used to determine which modules require which providers.

type ModuleVariable

type ModuleVariable struct {
	Name  string
	Field string
	// contains filtered or unexported fields
}

A ModuleVariable is a variable that is referencing the output of a module, such as "${module.foo.bar}"

func NewModuleVariable

func NewModuleVariable(key string) (*ModuleVariable, error)

func (*ModuleVariable) FullKey

func (v *ModuleVariable) FullKey() string

func (*ModuleVariable) GoString

func (v *ModuleVariable) GoString() string

func (ModuleVariable) SourceRange

func (r ModuleVariable) SourceRange() tfdiags.SourceRange

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.

var DisabledModuleWalker ModuleWalker

DisabledModuleWalker is a ModuleWalker that doesn't support child modules at all, and so will return an error if asked to load one.

This is provided primarily for testing. There is no good reason to use this in the main application.

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 Output

type Output struct {
	Name        string
	Description string
	Expr        hcl.Expression
	DependsOn   []hcl.Traversal
	Sensitive   bool

	DescriptionSet bool
	SensitiveSet   bool

	DeclRange hcl.Range
}

Output represents an "output" block in a module or file.

type Parser

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

Parser 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) ConfigDirFiles

func (p Parser) ConfigDirFiles(dir string) (primary, override []string, diags hcl.Diagnostics)

ConfigDirFiles returns lists of the primary and override files configuration files in the given directory.

If the given directory does not exist or cannot be read, error diagnostics are returned. If errors are returned, the resulting lists may be incomplete.

func (*Parser) ForceFileSource

func (p *Parser) ForceFileSource(filename string, src []byte)

ForceFileSource artificially adds source code to the cache of file sources, as if it had been loaded from the given filename.

This should be used only in special situations where configuration is loaded some other way. Most callers should load configuration via methods of Parser, which will update the sources cache automatically.

func (*Parser) IsConfigDir

func (p *Parser) IsConfigDir(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(path string) (*Module, hcl.Diagnostics)

LoadConfigDir reads the .tf and .tf.json files in the given directory as config files (using LoadConfigFile) 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. Callers should first call Parser.IsConfigDir if they wish to recognize that situation.

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

func (*Parser) LoadConfigFile

func (p *Parser) LoadConfigFile(path string) (*File, hcl.Diagnostics)

LoadConfigFile reads the file at the given path and parses it as a config file.

If the file cannot be read -- for example, if it does not exist -- then a nil *File 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.

This method wraps LoadHCLFile, and so it inherits the syntax selection behaviors documented for that method.

func (*Parser) LoadConfigFileOverride

func (p *Parser) LoadConfigFileOverride(path string) (*File, hcl.Diagnostics)

LoadConfigFileOverride is the same as LoadConfigFile except that it relaxes certain required attribute constraints in order to interpret the given file as an overrides file.

func (*Parser) LoadHCLFile

func (p *Parser) LoadHCLFile(path string) (hcl.Body, hcl.Diagnostics)

LoadHCLFile is a low-level method that reads the file at the given path, parses it, and returns the hcl.Body representing its root. In many cases it is better to use one of the other Load*File methods on this type, which additionally decode the root body in some way and return a higher-level construct.

If the file cannot be read at all -- e.g. because it does not exist -- then this method will return a nil body and error diagnostics. In this case callers may wish to ignore the provided error diagnostics and produce a more context-sensitive error instead.

The file will be parsed using the HCL native syntax unless the filename ends with ".json", in which case the HCL JSON syntax will be used.

func (*Parser) LoadValuesFile

func (p *Parser) LoadValuesFile(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.

This method wraps LoadHCLFile, and so it inherits the syntax selection behaviors documented for that method.

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 PassedProviderConfig

type PassedProviderConfig struct {
	InChild  *ProviderConfigRef
	InParent *ProviderConfigRef
}

PassedProviderConfig represents a provider config explicitly passed down to a child module, possibly giving it a new local address in the process.

type PathValueType

type PathValueType byte
const (
	PathValueInvalid PathValueType = iota
	PathValueCwd
	PathValueModule
	PathValueRoot
)

type PathVariable

type PathVariable struct {
	Type PathValueType
	// contains filtered or unexported fields
}

A PathVariable is a variable that references path information about the module.

func NewPathVariable

func NewPathVariable(key string) (*PathVariable, error)

func (*PathVariable) FullKey

func (v *PathVariable) FullKey() string

func (PathVariable) SourceRange

func (r PathVariable) SourceRange() tfdiags.SourceRange

type Provider

type Provider struct {
	Name       string
	NameRange  hcl.Range
	Alias      string
	AliasRange *hcl.Range // nil if no alias set

	Version VersionConstraint

	Config hcl.Body

	DeclRange hcl.Range
}

Provider represents a "provider" block in a module or file. A provider block is a provider configuration, and there can be zero or more configurations for each actual provider.

func (*Provider) Addr

func (p *Provider) Addr() addrs.LocalProviderConfig

Addr returns the address of the receiving provider configuration, relative to its containing module.

type ProviderConfigRef

type ProviderConfigRef struct {
	Name       string
	NameRange  hcl.Range
	Alias      string
	AliasRange *hcl.Range // nil if alias not set
}

func (*ProviderConfigRef) Addr

func (r *ProviderConfigRef) Addr() addrs.LocalProviderConfig

Addr returns the provider config address corresponding to the receiving config reference.

This is a trivial conversion, essentially just discarding the source location information and keeping just the addressing information.

func (*ProviderConfigRef) String

func (r *ProviderConfigRef) String() string

type ProviderMeta

type ProviderMeta struct {
	Provider string
	Config   hcl.Body

	ProviderRange hcl.Range
	DeclRange     hcl.Range
}

ProviderMeta represents a "provider_meta" block inside a "terraform" block in a module or file.

type Provisioner

type Provisioner struct {
	Type       string
	Config     hcl.Body
	Connection *Connection
	When       ProvisionerWhen
	OnFailure  ProvisionerOnFailure

	DeclRange hcl.Range
	TypeRange hcl.Range
}

Provisioner represents a "provisioner" block when used within a "resource" block in a module or file.

type ProvisionerOnFailure

type ProvisionerOnFailure int

ProvisionerOnFailure is an enum for valid values for on_failure options for provisioners.

const (
	ProvisionerOnFailureInvalid ProvisionerOnFailure = iota
	ProvisionerOnFailureContinue
	ProvisionerOnFailureFail
)

func (ProvisionerOnFailure) String

func (i ProvisionerOnFailure) String() string

type ProvisionerWhen

type ProvisionerWhen int

ProvisionerWhen is an enum for valid values for when to run provisioners.

const (
	ProvisionerWhenInvalid ProvisionerWhen = iota
	ProvisionerWhenCreate
	ProvisionerWhenDestroy
)

func (ProvisionerWhen) String

func (i ProvisionerWhen) String() string

type RawConfig

type RawConfig struct {
	Key string

	Raw  map[string]interface{}
	Body hcl2.Body

	Interpolations []ast.Node
	Variables      map[string]InterpolatedVariable
	// contains filtered or unexported fields
}

RawConfig is a structure that holds a piece of configuration where the overall structure is unknown since it will be used to configure a plugin or some other similar external component.

RawConfigs can be interpolated with variables that come from other resources, user variables, etc.

RawConfig supports a query-like interface to request information from deep within the structure.

func NewRawConfig

func NewRawConfig(raw map[string]interface{}) (*RawConfig, error)

NewRawConfig creates a new RawConfig structure and populates the publicly readable struct fields.

func NewRawConfigHCL2

func NewRawConfigHCL2(body hcl2.Body) *RawConfig

NewRawConfigHCL2 creates a new RawConfig that is serving as a capsule to transport a hcl2.Body. In this mode, the publicly-readable struct fields are not populated since all operations should instead be diverted to the HCL2 body.

For a RawConfig object constructed with this function, the only valid use is to later retrieve the Body value and call its own methods. Callers may choose to set and then later handle the Key field, in a manner consistent with how it is handled by the Value method, but the Value method itself must not be used.

This is an experimental codepath to be used only by the HCL2 config loader. Non-experimental parsing should _always_ use NewRawConfig to produce a fully-functional RawConfig object.

func (*RawConfig) Config

func (r *RawConfig) Config() map[string]interface{}

Config returns the entire configuration with the variables interpolated from any call to Interpolate.

If any interpolated variables are unknown (value set to UnknownVariableValue), the first non-container (map, slice, etc.) element will be removed from the config. The keys of unknown variables can be found using the UnknownKeys function.

By pruning out unknown keys from the configuration, the raw structure will always successfully decode into its ultimate structure using something like mapstructure.

func (*RawConfig) Copy

func (r *RawConfig) Copy() *RawConfig

Copy returns a copy of this RawConfig, uninterpolated.

func (*RawConfig) GobDecode

func (r *RawConfig) GobDecode(b []byte) error

See GobEncode

func (*RawConfig) GobEncode

func (r *RawConfig) GobEncode() ([]byte, error)

GobEncode is a custom Gob encoder to use so that we only include the raw configuration. Interpolated variables and such are lost and the tree of interpolated variables is recomputed on decode, since it is referentially transparent.

func (*RawConfig) Interpolate

func (r *RawConfig) Interpolate(vs map[string]ast.Variable) error

Interpolate uses the given mapping of variable values and uses those as the values to replace any variables in this raw configuration.

Any prior calls to Interpolate are replaced with this one.

If a variable key is missing, this will panic.

func (*RawConfig) Merge

func (r *RawConfig) Merge(other *RawConfig) *RawConfig

Merge merges another RawConfig into this one (overriding any conflicting values in this config) and returns a new config. The original config is not modified.

func (*RawConfig) RawMap

func (r *RawConfig) RawMap() map[string]interface{}

RawMap returns a copy of the RawConfig.Raw map.

func (*RawConfig) UnknownKeys

func (r *RawConfig) UnknownKeys() []string

UnknownKeys returns the keys of the configuration that are unknown because they had interpolated variables that must be computed.

func (*RawConfig) Value

func (r *RawConfig) Value() interface{}

Value returns the value of the configuration if this configuration has a Key set. If this does not have a Key set, nil will be returned.

type RequiredProvider

type RequiredProvider struct {
	Name        string
	Source      string
	Type        addrs.Provider
	Requirement VersionConstraint
	DeclRange   hcl.Range
}

RequiredProvider represents a declaration of a dependency on a particular provider version or source without actually configuring that provider. This is used in child modules that expect a provider to be passed in from their parent.

type RequiredProviders

type RequiredProviders struct {
	RequiredProviders map[string]*RequiredProvider
	DeclRange         hcl.Range
}

type Resource

type Resource struct {
	Mode    addrs.ResourceMode
	Name    string
	Type    string
	Config  hcl.Body
	Count   hcl.Expression
	ForEach hcl.Expression

	ProviderConfigRef *ProviderConfigRef
	Provider          addrs.Provider

	DependsOn []hcl.Traversal

	// Managed is populated only for Mode = addrs.ManagedResourceMode,
	// containing the additional fields that apply to managed resources.
	// For all other resource modes, this field is nil.
	Managed *ManagedResource

	DeclRange hcl.Range
	TypeRange hcl.Range
}

Resource represents a "resource" or "data" block in a module or file.

func (*Resource) Addr

func (r *Resource) Addr() addrs.Resource

Addr returns a resource address for the receiver that is relative to the resource's containing module.

func (*Resource) ProviderConfigAddr

func (r *Resource) ProviderConfigAddr() addrs.LocalProviderConfig

ProviderConfigAddr returns the address for the provider configuration that should be used for this resource. This function returns a default provider config addr if an explicit "provider" argument was not provided.

type ResourceVariable

type ResourceVariable struct {
	Mode  addrs.ResourceMode
	Type  string // Resource type, i.e. "aws_instance"
	Name  string // Resource name
	Field string // Resource field

	Multi bool // True if multi-variable: aws_instance.foo.*.id
	Index int  // Index for multi-variable: aws_instance.foo.1.id == 1
	// contains filtered or unexported fields
}

A ResourceVariable is a variable that is referencing the field of a resource, such as "${aws_instance.foo.ami}"

func NewResourceVariable

func NewResourceVariable(key string) (*ResourceVariable, error)

func (*ResourceVariable) FullKey

func (v *ResourceVariable) FullKey() string

func (*ResourceVariable) ResourceId

func (v *ResourceVariable) ResourceId() string

func (ResourceVariable) SourceRange

func (r ResourceVariable) SourceRange() tfdiags.SourceRange

type SelfVariable

type SelfVariable struct {
	Field string
	// contains filtered or unexported fields
}

SelfVariable is a variable that is referencing the same resource it is running on: "${self.address}"

func NewSelfVariable

func NewSelfVariable(key string) (*SelfVariable, error)

func (*SelfVariable) FullKey

func (v *SelfVariable) FullKey() string

func (*SelfVariable) GoString

func (v *SelfVariable) GoString() string

func (SelfVariable) SourceRange

func (r SelfVariable) SourceRange() tfdiags.SourceRange

type SimpleVariable

type SimpleVariable struct {
	Key string
	// contains filtered or unexported fields
}

SimpleVariable is an unprefixed variable, which can show up when users have strings they are passing down to resources that use interpolation internally. The template_file resource is an example of this.

func NewSimpleVariable

func NewSimpleVariable(key string) (*SimpleVariable, error)

func (*SimpleVariable) FullKey

func (v *SimpleVariable) FullKey() string

func (*SimpleVariable) GoString

func (v *SimpleVariable) GoString() string

func (SimpleVariable) SourceRange

func (r SimpleVariable) SourceRange() tfdiags.SourceRange

type TerraformVariable

type TerraformVariable struct {
	Field string
	// contains filtered or unexported fields
}

TerraformVariable is a "terraform."-prefixed variable used to access metadata about the Terraform run.

func NewTerraformVariable

func NewTerraformVariable(key string) (*TerraformVariable, error)

func (*TerraformVariable) FullKey

func (v *TerraformVariable) FullKey() string

func (*TerraformVariable) GoString

func (v *TerraformVariable) GoString() string

func (TerraformVariable) SourceRange

func (r TerraformVariable) SourceRange() tfdiags.SourceRange

type UserVariable

type UserVariable struct {
	Name string
	Elem string
	// contains filtered or unexported fields
}

A UserVariable is a variable that is referencing a user variable that is inputted from outside the configuration. This looks like "${var.foo}"

func NewUserVariable

func NewUserVariable(key string) (*UserVariable, error)

func (*UserVariable) FullKey

func (v *UserVariable) FullKey() string

func (*UserVariable) GoString

func (v *UserVariable) GoString() string

func (UserVariable) SourceRange

func (r UserVariable) SourceRange() tfdiags.SourceRange

type Variable

type Variable struct {
	Name        string
	Description string
	Default     cty.Value
	Type        cty.Type
	ParsingMode VariableParsingMode
	Validations []*VariableValidation

	DescriptionSet bool

	DeclRange hcl.Range
}

Variable represents a "variable" block in a module or file.

func (*Variable) Required

func (v *Variable) Required() bool

Required returns true if this variable is required to be set by the caller, or false if there is a default value that will be used when it isn't set.

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.

type VariableTypeHint

type VariableTypeHint rune

VariableTypeHint is an enumeration used for the Variable.TypeHint field, which is an incompletely-specified type for the variable which is used as a hint for whether a value provided in an ambiguous context (on the command line or in an environment variable) should be taken literally as a string or parsed as an HCL expression to produce a data structure.

The type hint is applied to runtime values as well, but since it does not accurately describe a precise type it is not fully-sufficient to infer the dynamic type of a value passed through a variable.

These hints use inaccurate terminology for historical reasons. Full details are in the documentation for each constant in this enumeration, but in summary:

TypeHintString requires a primitive type
TypeHintList requires a type that could be converted to a tuple
TypeHintMap requires a type that could be converted to an object
const TypeHintList VariableTypeHint = 'L'

TypeHintList indicates that a value provided in an ambiguous context should be treated as an HCL expression, and additionally requires that the runtime value for the variable is of an tuple, list, or set type.

const TypeHintMap VariableTypeHint = 'M'

TypeHintMap indicates that a value provided in an ambiguous context should be treated as an HCL expression, and additionally requires that the runtime value for the variable is of an object or map type.

const TypeHintNone VariableTypeHint = 0

TypeHintNone indicates the absence of a type hint. Values specified in ambiguous contexts will be treated as literal strings, as if TypeHintString were selected, but no runtime value checks will be applied. This is reasonable type hint for a module that is never intended to be used at the top-level of a configuration, since descendent modules never receive values from ambiguous contexts.

const TypeHintString VariableTypeHint = 'S'

TypeHintString spec indicates that a value provided in an ambiguous context should be treated as a literal string, and additionally requires that the runtime value for the variable is of a primitive type (string, number, bool).

func (VariableTypeHint) String

func (i VariableTypeHint) String() string

type VariableValidation

type VariableValidation struct {
	// Condition is an expression that refers to the variable being tested
	// and contains no other references. The expression must return true
	// to indicate that the value is valid or false to indicate that it is
	// invalid. If the expression produces an error, that's considered a bug
	// in the module defining the validation rule, not an error in the caller.
	Condition hcl.Expression

	// ErrorMessage is one or more full sentences, which would need to be in
	// English for consistency with the rest of the error message output but
	// can in practice be in any language as long as it ends with a period.
	// The message should describe what is required for the condition to return
	// true in a way that would make sense to a caller of the module.
	ErrorMessage string

	DeclRange hcl.Range
}

VariableValidation represents a configuration-defined validation rule for a particular input variable, given as a "validation" block inside a "variable" block.

type VersionConstraint

type VersionConstraint struct {
	Required  version.Constraints
	DeclRange hcl.Range
}

VersionConstraint represents a version constraint on some resource (e.g. Terraform Core, a provider, a module, ...) that carries with it a source range so that a helpful diagnostic can be printed in the event that a particular constraint does not match.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier