configs

package
v0.11.12-beta1 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2019 License: MPL-2.0 Imports: 14 Imported by: 0

Documentation

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

Constants

This section is empty.

Variables

This section is empty.

Functions

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.

Types

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.

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 not be used to display a path to the end-user, since
	// our UI conventions call for us to return a module address string in that
	// case, and a module address string ought to be built from the dynamic
	// module tree (resulting from evaluating "count" and "for_each" arguments
	// on our calls to produce potentially multiple child instances per call)
	// rather than from our static module tree.
	Path []string

	// 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 (*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.

type Connection

type Connection struct {
	Type   string
	Config hcl.Body

	DeclRange hcl.Range
	TypeRange *hcl.Range // nil if type is not set
}

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

type DataResource

type DataResource struct {
	Name    string
	Type    string
	Config  hcl.Body
	Count   hcl.Expression
	ForEach hcl.Expression

	ProviderConfigRef *ProviderConfigRef

	DependsOn []hcl.Traversal

	DeclRange hcl.Range
	TypeRange hcl.Range
}

DataResource represents a "data" block in a module or file.

type File

type File struct {
	CoreVersionConstraints []VersionConstraint

	Backends             []*Backend
	ProviderConfigs      []*Provider
	ProviderRequirements []*ProviderRequirement

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

	ModuleCalls []*ModuleCall

	ManagedResources []*ManagedResource
	DataResources    []*DataResource
}

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

type ManagedResource

type ManagedResource struct {
	Name    string
	Type    string
	Config  hcl.Body
	Count   hcl.Expression
	ForEach hcl.Expression

	ProviderConfigRef *ProviderConfigRef

	DependsOn []hcl.Traversal

	Connection   *Connection
	Provisioners []*Provisioner

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

	CreateBeforeDestroySet bool
	PreventDestroySet      bool

	DeclRange hcl.Range
	TypeRange hcl.Range
}

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

type Module

type Module struct {
	CoreVersionConstraints []VersionConstraint

	Backend              *Backend
	ProviderConfigs      map[string]*Provider
	ProviderRequirements map[string][]VersionConstraint

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

	ModuleCalls map[string]*ModuleCall

	ManagedResources map[string]*ManagedResource
	DataResources    map[string]*DataResource
}

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.

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

	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 []string

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

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

type ProviderConfigRef

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

type ProviderRequirement

type ProviderRequirement struct {
	Name        string
	Requirement VersionConstraint
}

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

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 Variable

type Variable struct {
	Name        string
	Description string
	Default     cty.Value
	Type        cty.Type
	ParsingMode VariableParsingMode

	DescriptionSet bool

	DeclRange hcl.Range
}

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

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

Directories

Path Synopsis
Package configload knows how to install modules into the .terraform/modules directory and to load modules from those installed locations.
Package configload knows how to install modules into the .terraform/modules directory and to load modules from those installed locations.

Jump to

Keyboard shortcuts

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