hcl

package
v0.0.0-...-a2d4d4d Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2024 License: Apache-2.0 Imports: 59 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// AWSVersionConstraintVolumeTags is the version constraint for the Terraform aws
	// provider that supports propagating default tags to volume tags. See
	// https://github.com/hashicorp/terraform-provider-aws/issues/19890 for more
	// information.
	AWSVersionConstraintVolumeTags = version.Must(version.NewVersion("5.39.0"))
)
View Source
var TypeData = Type{
	// contains filtered or unexported fields
}
View Source
var TypeLocal = Type{
	// contains filtered or unexported fields
}
View Source
var TypeModule = Type{
	// contains filtered or unexported fields
}
View Source
var TypeOutput = Type{
	// contains filtered or unexported fields
}
View Source
var TypeProvider = Type{
	// contains filtered or unexported fields
}
View Source
var TypeResource = Type{
	// contains filtered or unexported fields
}
View Source
var TypeTerraform = Type{
	// contains filtered or unexported fields
}
View Source
var TypeVariable = Type{
	// contains filtered or unexported fields
}

Functions

func ConstraintsAllowVersionOrAbove

func ConstraintsAllowVersionOrAbove(constraints version.Constraints, requiredVersion *version.Version) bool

ConstraintsAllowVersionOrAbove checks if the given constraints enforce at least the given minVersion.

func ExpFunctions

func ExpFunctions(baseDir string, logger zerolog.Logger) map[string]function.Function

ExpFunctions returns the set of functions that should be used to when evaluating expressions in the receiving scope.

func IsAutoVarFile

func IsAutoVarFile(file string) bool

IsAutoVarFile checks if the var file is an auto.tfvars or terraform.tfvars. These are special Terraform var files that are applied to every project automatically.

func ParseVariable

func ParseVariable(val interface{}) (cty.Value, error)

func SetUUIDAttributes

func SetUUIDAttributes(b *Block)

SetUUIDAttributes adds commonly used identifiers to the block so that it can be referenced by other blocks in context evaluation. The identifiers are only set if they don't already exist as attributes on the block.

Types

type Attribute

type Attribute struct {
	// HCLAttr is the underlying hcl.Attribute that the Attribute references.
	HCLAttr *hcl.Attribute
	// Ctx is the context that the Attribute should be evaluated against. This propagates
	// any references from variables into the attribute.
	Ctx *Context
	// Verbose defines if the attribute should log verbose diagnostics messages to debug.
	Verbose bool
	Logger  zerolog.Logger
	// contains filtered or unexported fields
}

Attribute provides a wrapper struct around hcl.Attribute it provides helper methods and functionality for common interactions with hcl.Attribute.

Attributes are key/value pairs that are part of a Block. For example take the following Block:

		resource "aws_instance" "t3_standard" {
		  	ami           = "fake_ami"
 		instance_type = "t3.medium"

 		credit_specification {
   			cpu_credits = "standard"
 		}
		}

"ami" & "instance_type" are the Attributes of this Block, "credit_specification" is a child Block see Block.Children for more info.

func (*Attribute) AllReferences

func (attr *Attribute) AllReferences() []*Reference

AllReferences returns a list of References for the given Attribute. This can include the main Value Reference (see Reference method) and also a list of references used in conditional evaluation and templating.

func (*Attribute) AsInt

func (attr *Attribute) AsInt() int64

AsInt returns the Attribute value as a int64. If the cty.Value is not a type that can be converted to integer, this method returns 0.

func (*Attribute) AsString

func (attr *Attribute) AsString() string

AsString returns the Attribute value as a string. If the cty.Value is not a type that can be converted to string, this method returns an empty string.

func (*Attribute) DecodeProviders

func (attr *Attribute) DecodeProviders() map[string]string

DecodeProviders decodes the providers block into a map of provider names to provider aliases. This is used by the graph evaluator to make sure the correct edges are created when providers are inherited from parent modules.

func (*Attribute) Equals

func (attr *Attribute) Equals(val interface{}) bool

Equals checks that val matches the underlying Attribute cty.Type.

func (*Attribute) HasChanged

func (attr *Attribute) HasChanged() (change bool)

HasChanged returns if the Attribute Value has changed since Value was last called.

func (*Attribute) IsIterable

func (attr *Attribute) IsIterable() bool

IsIterable returns if the attribute can be ranged over.

func (*Attribute) Name

func (attr *Attribute) Name() string

Name is a helper method to return the underlying hcl.Attribute Name

func (*Attribute) ProvidersValue

func (attr *Attribute) ProvidersValue() cty.Value

ProvidersValue retrieves the value of the attribute with special handling need for module.providers blocks: Keys in the providers block are converted to literal values, then the attr.Value() is returned.

func (*Attribute) Reference

func (attr *Attribute) Reference() (*Reference, error)

Reference returns the pointer to a Reference struct that holds information about the Attributes referenced block. Reference achieves this by traversing the Attribute Expression in order to find the parent block. E.g. with the following HCL

resource "aws_launch_template" "foo2" {
	name = "foo2"
}

resource "some_resource" "example_with_launch_template_3" {
	...
	name    = aws_launch_template.foo2.name
}

The Attribute some_resource.name would have a reference of

Reference {
	blockType: Type{
		name:                  "resource",
		removeTypeInReference: true,
	}
	typeLabel: "aws_launch_template"
	nameLabel: "foo2"
}

Reference is used to build up a Terraform JSON configuration file that holds information about the expressions and their parents. Diginfra uses these references in resource evaluation to lookup connecting resource information.

func (*Attribute) ReferencesCausingUnknownKeys

func (attr *Attribute) ReferencesCausingUnknownKeys() []string

ReferencesCausingUnknownKeys returns a list of missing references if the attribute is an object without fully known keys. For example, this will return []string{"var.default_tags"} if a value is set to the result of `merge({"x": "y"}, var.default_tags)` where the value of `var.default_tags` is not known at evaluation time.

func (*Attribute) Value

func (attr *Attribute) Value() cty.Value

Value returns the Attribute with the underlying hcl.Expression of the hcl.Attribute evaluated with the Attribute Context. This returns a cty.Value with the values filled from any variables or references that the Context carries.

func (*Attribute) VerticesReferenced

func (attr *Attribute) VerticesReferenced(b *Block) []VertexReference

VerticesReferenced traverses all the Expressions used by the attribute to build a list of all the Blocks referenced by the Attribute.

type AttributeWithUnknownKeys

type AttributeWithUnknownKeys struct {
	Attribute        string   `json:"attribute"`
	MissingVariables []string `json:"missingVariables"`
}

type Block

type Block struct {
	// HCLBlock is the underlying hcl.Block that has been parsed from a hcl.File
	HCLBlock *hcl.Block
	// UniqueAttrs specifies diginfra specific unique attributes that will be appended to the block values.
	UniqueAttrs map[string]*hcl.Attribute

	Filename  string
	StartLine int
	EndLine   int
	// contains filtered or unexported fields
}

Block wraps a hcl.Block type with additional methods and context. A Block is a core piece of HCL schema and represents a set of data. Most importantly a Block directly corresponds to a schema.Resource.

Blocks can represent a number of different types - see terraformSchemaV012 for a list of potential HCL blocks available.

e.g. a type resource block could look like this in HCL:

		resource "aws_lb" "lb1" {
  		load_balancer_type = "application"
		}

A Block can also have a set number of child Blocks, these child Blocks in turn can also have children. Blocks are recursive. The following example is represents a resource Block with child Blocks:

		resource "aws_instance" "t3_standard_cpuCredits" {
		  	ami           = "fake_ami"
 		instance_type = "t3.medium"

			# child Block starts here
 		credit_specification {
   			cpu_credits = "standard"
 		}
		}

See Attribute for more info about how the values of Blocks are evaluated with their Context and returned.

func (*Block) AttributesAsMap

func (b *Block) AttributesAsMap() map[string]*Attribute

AttributesAsMap returns the Attributes of this block as a map with the attribute name as the key and the value as the Attribute.

func (*Block) AttributesWithUnknownKeys

func (b *Block) AttributesWithUnknownKeys() []AttributeWithUnknownKeys

func (*Block) CallDetails

func (b *Block) CallDetails() []ModuleMetadata

CallDetails returns the tree of module calls that were used to create this resource. Each step of the tree contains a full file path and block name that were used to create the resource.

CallDetails returns a list of ModuleMetadata that are ordered by appearance in the Terraform config tree.

func (*Block) Children

func (b *Block) Children() Blocks

Children returns all the child Blocks associated with this Block.

func (*Block) Context

func (b *Block) Context() *Context

func (*Block) FullName

func (b *Block) FullName() string

FullName returns the fully qualified Reference name as it relates to the Blocks position in the entire Terraform config tree. This includes module name. e.g.

The following resource residing in a module named "web_app":

		resource "aws_instance" "t3_standard" {
		  	ami           = "fake_ami"
 		instance_type = var.instance_type
		}

Would have its FullName as module.web_app.aws_instance.t3_standard FullName is what Terraform uses in its JSON output file.

func (*Block) GetAttribute

func (b *Block) GetAttribute(name string) *Attribute

GetAttribute returns the given attribute with the provided name. It will return nil if the attribute is not found. If we take the following Block example:

		resource "aws_instance" "t3_standard_cpuCredits" {
		  	ami           = "fake_ami"
 		instance_type = "t3.medium"

 		credit_specification {
   			cpu_credits = "standard"
 		}
		}

ami & instance_type are both valid Attribute names that can be used to lookup Block Attributes.

func (*Block) GetAttributes

func (b *Block) GetAttributes() []*Attribute

GetAttributes returns a list of Attribute for this Block. Attributes are key value specification on a given Block. For example take the following hcl:

		resource "aws_instance" "t3_standard_cpuCredits" {
		  	ami           = "fake_ami"
 		instance_type = "t3.medium"

 		credit_specification {
   			cpu_credits = "standard"
 		}
		}

ami & instance_type are the Attributes of this Block and credit_specification is a child Block.

func (*Block) GetChildBlock

func (b *Block) GetChildBlock(name string) *Block

GetChildBlock is a helper method around GetChildBlocks. It returns the first non nil child block matching name.

func (*Block) GetChildBlocks

func (b *Block) GetChildBlocks(name string) []*Block

GetChildBlocks returns all the child Block that match the name provided. e.g: If the current Block looks like such:

		resource "aws_instance" "t3_standard_cpuCredits" {
		  	ami           = "fake_ami"
 		instance_type = "t3.medium"

 		credit_specification {
   			cpu_credits = "standard"
 		}

			ebs_block_device {
				device_name = "xvdj"
			}
		}

Then "credit_specification" & "ebs_block_device" would be valid names that could be used to retrieve child Blocks.

func (*Block) HasChild

func (b *Block) HasChild(childElement string) bool

func (*Block) HasDynamicBlock

func (b *Block) HasDynamicBlock() bool

HasDynamicBlock searches all the nested children of the given block to see if any are type "dynamic". This is used before embarking on dynamic expansion logic.

func (*Block) HasModuleBlock

func (b *Block) HasModuleBlock() bool

HasModuleBlock returns is the Block as a module associated with it. If it doesn't this means that this Block is part of the root Module.

func (*Block) Index

func (b *Block) Index() *int64

Index returns the count index of the block using the name label. Index returns nil if the block has no count.

func (*Block) IsCountExpanded

func (b *Block) IsCountExpanded() bool

IsCountExpanded returns if the Block has been expanded as part of a for_each or count evaluation.

func (*Block) IsForEachReferencedExpanded

func (b *Block) IsForEachReferencedExpanded(moduleBlocks Blocks) bool

IsForEachReferencedExpanded checks if the block referenced under the for_each has already been expanded. This is used to check is we can safely expand this block, expanding block prematurely can lead to output inconsistencies. It is advised to always check if that the block has any references that are yet to be expanded before expanding itself.

func (*Block) Key

func (b *Block) Key() *string

Key returns the foreach key of the block using the name label. Key returns nil if the block has no each key.

func (*Block) Label

func (b *Block) Label() string

func (*Block) Labels

func (b *Block) Labels() []string

func (*Block) LocalName

func (b *Block) LocalName() string

LocalName is the name relative to the current module

func (*Block) ModuleAddress

func (b *Block) ModuleAddress() string

ModuleAddress returns the address of the module associated with this Block or "" if it is part of the root Module

func (*Block) ModuleName

func (b *Block) ModuleName() string

ModuleName returns the name of the module associated with this Block or "" if it is part of the root Module

func (*Block) ModuleSource

func (b *Block) ModuleSource() string

ModuleSource returns the "source" attribute from the associated Module or "" if it is part of the root Module

func (*Block) NameLabel

func (b *Block) NameLabel() string

func (*Block) Provider

func (b *Block) Provider() string

Provider returns the provider by first checking if it is explicitly set as an attribute, if it is not the first word in the snake_case name of the type is returned. E.g. the type 'aws_instance' would return provider 'aws'

func (*Block) ProviderConfigKey

func (b *Block) ProviderConfigKey() string

ProviderConfigKey looks up the key used to reference the provider in the "configuration.providers" section of the terraform plan json. This should be used to set the "provider_config_key " of the resource in the "configuration.resources" section of plan json.

func (*Block) Reference

func (b *Block) Reference() *Reference

Reference returns a Reference to the given Block this can be used to when printing out full names of Blocks to stdout or a file.

func (*Block) SetContext

func (b *Block) SetContext(ctx *Context)

SetContext sets the Block.context to the provided ctx. This ctx is also set on the child Blocks as a child Context. Meaning that it can be used in traversal evaluation when looking up Context variables.

func (*Block) SetLabels

func (b *Block) SetLabels(labels []string)

func (*Block) SetType

func (b *Block) SetType(t string)

func (*Block) ShouldExpand

func (b *Block) ShouldExpand() bool

func (*Block) Type

func (b *Block) Type() string

func (*Block) TypeLabel

func (b *Block) TypeLabel() string

func (*Block) Values

func (b *Block) Values() cty.Value

Values returns the Block as a cty.Value with all the Attributes evaluated with the Block Context. This means that any variables or references will be replaced by their actual value. For example:

		variable "instance_type" {
			default = "t3.medium"
		}

		resource "aws_instance" "t3_standard_cpucredits" {
		  	ami           = "fake_ami"
 		instance_type = var.instance_type
		}

Would evaluate to a cty.Value of type Object with the instance_type Attribute holding the value "t3.medium".

func (*Block) VerticesReferenced

func (b *Block) VerticesReferenced() []VertexReference

VerticesReferenced traverses the block attributes and child blocks to build a complete list of all the vertices referenced by the Block. We build a special VertexReference if the block uses a provider but doesn't have one referenced. This is because blocks will depend on the default provider to get the correct region data, even if not explicitly referenced as a reference.

type BlockBuilder

type BlockBuilder struct {
	MockFunc      func(a *Attribute) cty.Value
	SetAttributes []SetAttributesFunc
	Logger        zerolog.Logger
	HCLParser     *modules.SharedHCLParser
	// contains filtered or unexported fields
}

BlockBuilder handles generating new Blocks as part of the parsing and evaluation process.

func (BlockBuilder) BuildModuleBlocks

func (b BlockBuilder) BuildModuleBlocks(block *Block, modulePath string, rootPath string) (Blocks, error)

BuildModuleBlocks loads all the Blocks for the module at the given path

func (BlockBuilder) CloneBlock

func (b BlockBuilder) CloneBlock(block *Block, index cty.Value) *Block

CloneBlock creates a duplicate of the block and sets the returned Block's Context to include the index provided. This is primarily used when Blocks are expanded as part of a count evaluation.

func (BlockBuilder) NewBlock

func (b BlockBuilder) NewBlock(filename string, rootPath string, hclBlock *hcl.Block, ctx *Context, parent *Block, moduleBlock *Block) *Block

NewBlock returns a Block with Context and child Blocks initialised.

type BlockMatcher

type BlockMatcher struct {
	Type       string
	Label      string
	StripCount bool
}

BlockMatcher defines a struct that can be used to filter a list of blocks to a single Block.

type BlockValueFunc

type BlockValueFunc = func(b *Block) cty.Value

BlockValueFunc defines a type that returns a set of fake/mocked values for a given block type.

type Blocks

type Blocks []*Block

Blocks is a helper type around a slice of blocks to provide easy access finding blocks of type.

func (Blocks) FindLocalName

func (blocks Blocks) FindLocalName(name string) *Block

func (Blocks) Matching

func (blocks Blocks) Matching(pattern BlockMatcher) *Block

Matching returns a single block filtered from the given pattern. If more than one Block is filtered by the pattern, Matching returns the first Block found.

func (Blocks) ModuleBlocks

func (blocks Blocks) ModuleBlocks() Blocks

ModuleBlocks is a wrapper around SortedByCaller that selects just Modules to be sorted.

func (Blocks) OfType

func (blocks Blocks) OfType(t string) Blocks

OfType returns Blocks of the given type t. See terraformSchemaV012 for a list of possible types to lookup.

func (Blocks) Outputs

func (blocks Blocks) Outputs(suppressNil bool) cty.Value

Outputs returns a map of all the evaluated outputs from the list of Blocks.

func (Blocks) SortedByCaller

func (blocks Blocks) SortedByCaller() Blocks

SortedByCaller returns all the Blocks of type module. The returned Blocks are sorted in order of reference. Blocks that are referenced by others are the first in this list.

So if we start with a list of [A,B,C] and A references B the returned list will be [B,A,C].

This makes the list returned safe for context evaluation, as we evaluate modules that have outputs that other modules rely on first.

type Context

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

func NewContext

func NewContext(ctx *hcl.EvalContext, parent *Context, logger zerolog.Logger) *Context

func (*Context) Get

func (c *Context) Get(parts ...string) (val cty.Value)

func (*Context) Inner

func (c *Context) Inner() *hcl.EvalContext

func (*Context) NewChild

func (c *Context) NewChild() *Context

func (*Context) Parent

func (c *Context) Parent() *Context

func (*Context) Root

func (c *Context) Root() *Context

func (*Context) Set

func (c *Context) Set(val cty.Value, parts ...string)

func (*Context) SetByDot

func (c *Context) SetByDot(val cty.Value, path string)

type DetectedProject

type DetectedProject interface {
	ProjectName() string
	EnvName() string
	RelativePath() string
	VarFiles() []string
	YAML() string
	DependencyPaths() []string
}

type EnvFileMatcher

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

EnvFileMatcher is used to match environment specific var files.

func CreateEnvFileMatcher

func CreateEnvFileMatcher(names []string, extensions []string) *EnvFileMatcher

func (*EnvFileMatcher) EnvName

func (e *EnvFileMatcher) EnvName(file string) string

EnvName returns the environment name for the given var file.

func (*EnvFileMatcher) IsEnvName

func (e *EnvFileMatcher) IsEnvName(file string) bool

IsEnvName checks if the var file is an environment specific var file.

func (*EnvFileMatcher) IsGlobalVarFile

func (e *EnvFileMatcher) IsGlobalVarFile(file string) bool

IsGlobalVarFile checks if the var file is a global var file.

func (*EnvFileMatcher) PathEnv

func (e *EnvFileMatcher) PathEnv(file string) string

PathEnv returns the env name detected in file path when it matches defined envs. Otherwise returns an empty string.

type Evaluator

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

Evaluator provides a set of given Blocks with contextual information. Evaluator is an important step in retrieving Block values that can be used in the schema.Resource cost retrieval. Without Evaluator the Blocks provided only have shallow information within attributes and won't contain any evaluated variables or references.

func NewEvaluator

func NewEvaluator(
	module Module,
	workingDir string,
	inputVars map[string]cty.Value,
	moduleMetadata *modules.Manifest,
	visitedModules map[string]map[string]cty.Value,
	workspace string,
	blockBuilder BlockBuilder,
	logger zerolog.Logger,
	isGraph bool,
) *Evaluator

NewEvaluator returns an Evaluator with Context initialised with top level variables. This Context is then passed to all Blocks as child Context so that variables built in Evaluation are propagated to the Block Attributes.

func (*Evaluator) AddFilteredBlocks

func (e *Evaluator) AddFilteredBlocks(blocks ...*Block)

func (*Evaluator) MissingVars

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

MissingVars returns a list of names of the variable blocks with missing input values.

func (*Evaluator) Run

func (e *Evaluator) Run() (*Module, error)

Run builds the Evaluator Context using all the provided Blocks. It will build up the Context to hold variable and reference information so that this can be used by Attribute evaluation. Run will also parse and build up and child modules that are referenced in the Blocks and runs child Evaluator on this Module.

type Graph

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

func NewGraphWithRoot

func NewGraphWithRoot(logger zerolog.Logger, vertexMutex *sync.Mutex) (*Graph, error)

func (*Graph) AsJSON

func (g *Graph) AsJSON() ([]byte, error)

func (*Graph) Populate

func (g *Graph) Populate(evaluator *Evaluator) error

func (*Graph) ReduceTransitively

func (g *Graph) ReduceTransitively()

func (*Graph) Run

func (g *Graph) Run(evaluator *Evaluator) (*Module, error)

func (*Graph) Walk

func (g *Graph) Walk()

type GraphVisitor

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

func NewGraphVisitor

func NewGraphVisitor(logger zerolog.Logger, vertexMutex *sync.Mutex) *GraphVisitor

func (*GraphVisitor) Visit

func (v *GraphVisitor) Visit(id string, vertex interface{})

type LiteralBoolValueExpression

type LiteralBoolValueExpression struct {
	// we embed the hclsyntax.LiteralValueExpr as the hcl.Expression interface
	// has an unexported method that we need to implement.
	*hclsyntax.LiteralValueExpr

	Expression hcl.Expression
}

LiteralBoolValueExpression is a wrapper around any hcl.Expression that returns a literal bool value. This is use to evaluate mocked expressions that are used in conditional expressions. It turns any non bool literal value into a bool false value.

func (*LiteralBoolValueExpression) Value

func (e *LiteralBoolValueExpression) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics)

Value returns the value of the expression. If the expression is not a literal bool value, this returns false.

type LiteralValueCollectionExpression

type LiteralValueCollectionExpression struct {
	// we embed the hclsyntax.LiteralValueExpr as the hcl.Expression interface
	// has an unexported method that we need to implement.
	*hclsyntax.LiteralValueExpr
	Expression  hcl.Expression
	MockedValue cty.Value
}

func (*LiteralValueCollectionExpression) Value

func (e *LiteralValueCollectionExpression) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics)

type LiteralValueIndexExpression

type LiteralValueIndexExpression struct {
	// we embed the hclsyntax.LiteralValueExpr as the hcl.Expression interface
	// has an unexported method that we need to implement.
	*hclsyntax.LiteralValueExpr
	Expression  *hclsyntax.IndexExpr
	MockedValue cty.Value
}

func (*LiteralValueIndexExpression) Value

func (e *LiteralValueIndexExpression) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics)

type Module

type Module struct {
	Name   string
	Source string

	Blocks Blocks
	// RawBlocks are the Blocks that were built when the module was loaded from the filesystem.
	// These are safe to pass to the child module calls as they are yet to be expanded.
	RawBlocks  Blocks
	RootPath   string
	ModulePath string

	Modules  []*Module
	Parent   *Module
	Warnings []*schema.ProjectDiag

	HasChanges         bool
	TerraformVarsPaths []string

	// ModuleSuffix is a unique name that can be optionally appended to the Module's
	// project name. This is only applicable to root modules.
	ModuleSuffix string

	// SourceURL is the discovered remote url for the module. This will only be
	// filled if the module is a remote module.
	SourceURL string

	// ProviderReferences is a map of provider names (relative to the module) to
	// the provider block that defines that provider. We keep track of this so we
	// can re-evaluate the provider blocks when we need to.
	ProviderReferences  map[string]*Block
	TerraformVersion    string
	ProviderConstraints *ProviderConstraints
}

Module encapsulates all the Blocks that are part of a Module in a Terraform project.

func (*Module) Index

func (m *Module) Index() *int64

Index returns the count index of the Module using the name. Index returns nil if the Module has no count.

func (*Module) Key

func (m *Module) Key() *string

Key returns the foreach key of the Module using the name. Key returns nil if the Module has no each key.

type ModuleCall

type ModuleCall struct {
	// Name the name of the module as specified a the point of definition.
	Name string
	// Path is the path to the local directory containing the HCL for the Module.
	Path string
	// Definition is the actual Block where the ModuleCall happens in a hcl.File
	Definition *Block
	// Module contains the parsed root module that represents this ModuleCall.
	Module *Module
}

ModuleCall represents a call to a defined Module by a parent Module.

type ModuleConfig

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

type ModuleConfigs

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

func NewModuleConfigs

func NewModuleConfigs() *ModuleConfigs

func (*ModuleConfigs) Add

func (m *ModuleConfigs) Add(moduleAddress string, moduleConfig ModuleConfig)

func (*ModuleConfigs) Get

func (m *ModuleConfigs) Get(moduleAddress string) []ModuleConfig

type ModuleMetadata

type ModuleMetadata struct {
	Filename  string `json:"filename"`
	BlockName string `json:"blockName"`
	StartLine int    `json:"startLine,omitempty"`
	EndLine   int    `json:"endLine,omitempty"`
}

type Option

type Option func(p *Parser)

func OptionGraphEvaluator

func OptionGraphEvaluator() Option

OptionGraphEvaluator sets the Parser to use the experimental graph evaluator.

func OptionWithBlockBuilder

func OptionWithBlockBuilder(blockBuilder BlockBuilder) Option

func OptionWithInputVars

func OptionWithInputVars(vars map[string]interface{}) Option

OptionWithInputVars takes cmd line var input values and converts them to cty.Value It sets these as the Parser starting inputVars which are used at the root module evaluation.

func OptionWithModuleSuffix

func OptionWithModuleSuffix(rootPath, suffix string) Option

OptionWithModuleSuffix sets an optional module suffix which will be added to the Module after it has finished parsing this can be used to augment auto-detected project path names and metadata. If the suffix is already part of the project name - ignore it.

func OptionWithPlanFlagVars

func OptionWithPlanFlagVars(vs []string) Option

OptionWithPlanFlagVars takes TF var inputs specified in a command line string and converts them to cty.Value It sets these as the Parser starting inputVars which are used at the root module evaluation.

func OptionWithProjectName

func OptionWithProjectName(name string) Option

OptionWithProjectName sets the project name for the parser. This is used if the project name has been explicitly set by the user or the autodetection

func OptionWithRawCtyInput

func OptionWithRawCtyInput(input cty.Value) (op Option)

OptionWithRawCtyInput sets the input variables for the parser using a cty.Value. OptionWithRawCtyInput expects that this input is a ObjectValue that can be transformed to a map.

func OptionWithSpaceliftRemoteVarLoader

func OptionWithSpaceliftRemoteVarLoader(ctx *config.ProjectContext) Option

OptionWithSpaceliftRemoteVarLoader attempts to build a SpaceLift remote variable loader and set this on the parser. If the required environment variables are not set, the loader is skipped.

func OptionWithTFCRemoteVarLoader

func OptionWithTFCRemoteVarLoader(host, token, localWorkspace string, loaderOpts ...TFCRemoteVariablesLoaderOption) Option

OptionWithTFCRemoteVarLoader accepts Terraform Cloud/Enterprise host and token values to load remote execution variables.

func OptionWithTFEnvVars

func OptionWithTFEnvVars(projectEnv map[string]string) Option

OptionWithTFEnvVars takes any TF_ENV_xxx=yyy from the environment and converts them to cty.Value It then sets these as the Parser starting tfEnvVars which are used at the root module evaluation.

func OptionWithTFVarsPaths

func OptionWithTFVarsPaths(paths []string, autoDetected bool) Option

OptionWithTFVarsPaths takes a slice of paths adds them to the parser tfvar files relative to the Parser detectedProjectPath. It sorts tfvar paths for precedence before adding them to the parser. Paths that don't exist will be ignored.

func OptionWithTerraformWorkspace

func OptionWithTerraformWorkspace(name string) Option

OptionWithTerraformWorkspace informs the Parser to use the provided name as the workspace for context evaluation. The Parser exposes this workspace in the evaluation context under the variable named `terraform.workspace`. This is commonly used by users to specify different capacity/configuration in their Terraform, e.g:

terraform.workspace == "prod" ? "m5.8xlarge" : "m5.4xlarge"

type Parser

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

Parser is a tool for parsing terraform templates at a given file system location.

func NewParser

func NewParser(projectRoot RootPath, envMatcher *EnvFileMatcher, moduleLoader *modules.ModuleLoader, logger zerolog.Logger, options ...Option) *Parser

NewParser creates a new parser for the given RootPath.

func (*Parser) DependencyPaths

func (p *Parser) DependencyPaths() []string

DependencyPaths returns the list of module calls that the project depends on. These are usually local module calls that have been detected in the project.

func (*Parser) EnvName

func (p *Parser) EnvName() string

EnvName returns the module suffix of the parser (normally the environment name).

func (*Parser) ParseDirectory

func (p *Parser) ParseDirectory() (m *Module, err error)

ParseDirectory parses all the terraform files in the detectedProjectPath into Blocks and then passes them to an Evaluator to fill these Blocks with additional Context information. Parser does not parse any blocks outside the root Module. It instead leaves ModuleLoader to fetch these Modules on demand. See ModuleLoader.Load for more information.

ParseDirectory returns the root Module that represents the top of the Terraform Config tree.

func (*Parser) Path

func (p *Parser) Path() string

Path returns the full path that the parser runs within.

func (*Parser) ProjectName

func (p *Parser) ProjectName() string

ProjectName generates a name for the project that can be used in the Diginfra config file.

func (*Parser) RelativePath

func (p *Parser) RelativePath() string

RelativePath returns the path of the parser relative to the repo path

func (*Parser) VarFiles

func (p *Parser) VarFiles() []string

TerraformVarFiles returns the list of terraform var files that the parser will use to load variables from.

func (*Parser) YAML

func (p *Parser) YAML() string

YAML returns a yaml representation of Parser, that can be used to "explain" the auto-detection functionality.

type PathOverrideConfig

type PathOverrideConfig struct {
	Path    string
	Exclude []string
	Only    []string
}

type ProjectLocator

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

ProjectLocator finds Terraform projects for given paths. It naively excludes folders that are imported as modules in other projects.

func NewProjectLocator

func NewProjectLocator(logger zerolog.Logger, config *ProjectLocatorConfig) *ProjectLocator

NewProjectLocator returns safely initialized ProjectLocator.

func (*ProjectLocator) FindRootModules

func (p *ProjectLocator) FindRootModules(startingPath string) []RootPath

FindRootModules returns a list of all directories that contain a full Terraform project under the given fullPath. This list excludes any Terraform modules that have been found (if they have been called by a Module source).

type ProjectLocatorConfig

type ProjectLocatorConfig struct {
	ExcludedDirs               []string
	ChangedObjects             []string
	UseAllPaths                bool
	SkipAutoDetection          bool
	IncludedDirs               []string
	EnvNames                   []string
	PathOverrides              []PathOverrideConfig
	FallbackToIncludePaths     bool
	MaxSearchDepth             int
	ForceProjectType           string
	TerraformVarFileExtensions []string
	WorkingDirectory           string
}

ProjectLocatorConfig provides configuration options on how the locator functions.

type ProviderConstraints

type ProviderConstraints struct {
	AWS    version.Constraints
	Google version.Constraints
}

ProviderConstraints represents the constraints for a providers within a module. This can be used to check if Diginfra functionality is applicable to a given run.

func NewProviderConstraints

func NewProviderConstraints(blocks Blocks) *ProviderConstraints

NewProviderConstraints parses the provider blocks for any Terraform configuration blocks if found it will attempt to return a ProviderConstraints struct from the required_providers configuration. Currently, we only support AWS provider constraints.

func (*ProviderConstraints) MarshalJSON

func (p *ProviderConstraints) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation of the ProviderConstraints. This is used to serialize the constraints for the sub providers.

func (*ProviderConstraints) UnmarshalJSON

func (p *ProviderConstraints) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the JSON representation of the ProviderConstraints and sets the constraints for the sub providers.

type Reference

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

func (*Reference) JSONString

func (r *Reference) JSONString() string

JSONString returns the reference so that it's possible to use in the plan JSON file. This strips any count keys from the reference.

func (*Reference) String

func (r *Reference) String() string

type RemoteVarLoaderOptions

type RemoteVarLoaderOptions struct {
	Blocks      Blocks
	ModulePath  string
	Environment string
}

type RemoteVariableLoader

type RemoteVariableLoader interface {
	// Load fetches remote variables from a remote service.
	Load(options RemoteVarLoaderOptions) (map[string]cty.Value, error)
}

RemoteVariableLoader is an interface for loading remote variables from a remote service.

type RootPath

type RootPath struct {
	Matcher *EnvFileMatcher

	// StartingPath is the path to the directory where the search started.
	StartingPath string
	// DetectedPath is the path to the root of the project.
	DetectedPath string
	// HasChanges contains information about whether the project has git changes associated with it.
	// This will show as true if one or more files/directories have changed in the Path, and also if
	// and local modules that are used by this project have changes.
	HasChanges bool
	// TerraformVarFiles are a list of any .tfvars or .tfvars.json files found at the root level.
	TerraformVarFiles RootPathVarFiles

	HasChildVarFiles         bool
	IsTerragrunt             bool
	IsParentTerragruntConfig bool
	ModuleCalls              []string
}

RootPath holds information about the root directory of a project, this is normally the top level Terraform containing provider blocks.

func (*RootPath) AddVarFiles

func (r *RootPath) AddVarFiles(v *VarFiles)

func (*RootPath) AutoFiles

func (r *RootPath) AutoFiles() RootPathVarFiles

AutoFiles returns a list of any auto.tfvars or terraform.tfvars files defined in the project.

func (*RootPath) EnvFiles

func (r *RootPath) EnvFiles() RootPathVarFiles

EnvFiles returns a list of any environment specific var files defined in the project.

func (*RootPath) EnvGroupings

func (r *RootPath) EnvGroupings() []VarFileGrouping

EnvGroupings returns a list of var file groupings by environment. This is used to group and dedup var files that would otherwise create new projects.

func (*RootPath) GlobalFiles

func (r *RootPath) GlobalFiles() RootPathVarFiles

GlobalFiles returns a list of any global var files defined in the project.

func (*RootPath) RelPath

func (r *RootPath) RelPath() string

type RootPathVarFile

type RootPathVarFile struct {
	Name string
	// RelPath is the path relative to the root of the project.
	RelPath string

	IsGlobal bool
	EnvName  string
	FullPath string
}

func (RootPathVarFile) IsChildVarFile

func (r RootPathVarFile) IsChildVarFile() bool

type RootPathVarFiles

type RootPathVarFiles []RootPathVarFile

func (RootPathVarFiles) ToPaths

func (r RootPathVarFiles) ToPaths() []string

type SetAttributesFunc

type SetAttributesFunc func(b *Block)

SetAttributesFunc defines a function that sets required attributes on a hcl.Block. This is done so that identifiers that are normally propagated from a Terraform state/apply are set on the Block. This means they can be used properly in references and outputs.

type SpaceliftRemoteVariableLoader

type SpaceliftRemoteVariableLoader struct {
	Client   client.Client
	Metadata vcs.Metadata
	// contains filtered or unexported fields
}

SpaceliftRemoteVariableLoader orchestrates communicating with the Spacelift API to fetch remote variables.

func NewSpaceliftRemoteVariableLoader

func NewSpaceliftRemoteVariableLoader(metadata vcs.Metadata, apiKeyEndpoint, apiKeyId, apiKeySecret string) (*SpaceliftRemoteVariableLoader, error)

NewSpaceliftRemoteVariableLoader creates a new SpaceliftRemoteVariableLoader, this function expects that the required environment variables are set.

func (*SpaceliftRemoteVariableLoader) Load

Load fetches remote variables from Spacelift by querying the stacks for the provided environment name and remote name.

type TFCRemoteConfig

type TFCRemoteConfig struct {
	Organization string
	Workspace    string
	Host         string
}

type TFCRemoteVariablesLoader

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

TFCRemoteVariablesLoader handles loading remote variables from Terraform Cloud.

func NewTFCRemoteVariablesLoader

func NewTFCRemoteVariablesLoader(client *extclient.AuthedAPIClient, localWorkspace string, logger zerolog.Logger, opts ...TFCRemoteVariablesLoaderOption) *TFCRemoteVariablesLoader

NewTFCRemoteVariablesLoader constructs a new loader for fetching remote variables.

func (*TFCRemoteVariablesLoader) Load

Load fetches remote variables if terraform block contains organization and workspace name.

type TFCRemoteVariablesLoaderOption

type TFCRemoteVariablesLoaderOption func(r *TFCRemoteVariablesLoader)

TFCRemoteVariablesLoaderOption defines a function that can set properties on an TFCRemoteVariablesLoader.

func RemoteVariablesLoaderWithRemoteConfig

func RemoteVariablesLoaderWithRemoteConfig(config TFCRemoteConfig) TFCRemoteVariablesLoaderOption

RemoteVariablesLoaderWithRemoteConfig sets a user defined configuration for the TFCRemoteVariablesLoader. This is normally done to override the configuration detected from the HCL blocks.

type TreeNode

type TreeNode struct {
	Name              string
	Level             int
	RootPath          *RootPath
	TerraformVarFiles *VarFiles
	Children          []*TreeNode
	Parent            *TreeNode
}

TreeNode represents a node in the tree of Terraform projects. A TreeNode can either be a Terraform project, a directory containing Terraform var files, or just a filler node to represent a directory. Callers should check the RootPath and TerraformVarFiles fields to determine what type of node this is.

func CreateTreeNode

func CreateTreeNode(basePath string, paths []RootPath, varFiles map[string][]RootPathVarFile, e *EnvFileMatcher) *TreeNode

CreateTreeNode creates a tree of Terraform projects and directories that contain var files.

func (*TreeNode) AddPath

func (t *TreeNode) AddPath(path RootPath)

AddPath adds a path to the tree, this will create any missing nodes in the tree.

func (*TreeNode) AddTerraformVarFiles

func (t *TreeNode) AddTerraformVarFiles(basePath, dir string, files []RootPathVarFile)

AddTerraformVarFiles adds a directory that contains Terraform var files to the tree.

func (*TreeNode) AssociateAuntVarFiles

func (t *TreeNode) AssociateAuntVarFiles()

AssociateAuntVarFiles returns a list of any aunt directories that contain var files that have not been used by a project.

func (*TreeNode) AssociateChildVarFiles

func (t *TreeNode) AssociateChildVarFiles()

AssociateChildVarFiles make sure that any projects have directories which contain var files are associated with the project. These are only associated if they are within 2 levels of the project and not if the child directory is a valid sibling directory.

func (*TreeNode) AssociateParentVarFiles

func (t *TreeNode) AssociateParentVarFiles()

AssociateParentVarFiles returns a list of any parent directories that contain var files that have not been used by a project.

func (*TreeNode) AssociateSiblingVarFiles

func (t *TreeNode) AssociateSiblingVarFiles()

AssociateSiblingVarFiles makes sure that any sibling directories that contain var files are associated with their corresponding projects.

func (*TreeNode) ChildNodes

func (t *TreeNode) ChildNodes() []*TreeNode

ChildNodes returns the first set of child nodes that are Terraform projects or directories that contain var files.

func (*TreeNode) ChildNodesExcluding

func (t *TreeNode) ChildNodesExcluding(root *TreeNode) []*TreeNode

ChildNodesExcluding collects all the child nodes of the current node, excluding the given root node.

func (*TreeNode) ChildTerraformVarFiles

func (t *TreeNode) ChildTerraformVarFiles() []*TreeNode

ChildTerraformVarFiles returns the first set of child nodes that contain just terraform var files.

func (*TreeNode) CollectRootPaths

func (t *TreeNode) CollectRootPaths(e *EnvFileMatcher) []RootPath

CollectRootPaths returns a list of all the Terraform projects found in the tree.

func (*TreeNode) FindTfvarsCommonParent

func (t *TreeNode) FindTfvarsCommonParent() *TreeNode

FindTfvarsCommonParent returns the first parent directory that has a child directory with a root Terraform project.

func (*TreeNode) ParentNode

func (t *TreeNode) ParentNode() *TreeNode

ParentNode returns the parent node of the current node, this will skip any nodes that are not Terraform projects or directories that contain var files.

func (*TreeNode) Parents

func (t *TreeNode) Parents() []*TreeNode

Parents returns the list of parent nodes of the current node.

func (*TreeNode) PostOrder

func (t *TreeNode) PostOrder(visit func(t *TreeNode))

PostOrder traverses the tree in post order, calling the given function on each node. This will skip any nodes that are not Terraform projects or directories that contain var files.

func (*TreeNode) UnusedParentVarFiles

func (t *TreeNode) UnusedParentVarFiles() []*VarFiles

UnusedParentVarFiles returns a list of any parent directories that contain var files that have not been used by a project.

func (*TreeNode) Visit

func (t *TreeNode) Visit(f func(t *TreeNode))

Visit traverses the tree in pre order, calling the given function on each node. This will skip any nodes that are not Terraform projects or directories

type Type

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

func TypeFromRefName

func TypeFromRefName(name string) (*Type, error)

func (Type) Name

func (t Type) Name() string

func (Type) ShortName

func (t Type) ShortName() string

type VarFileGrouping

type VarFileGrouping struct {
	Name              string
	TerraformVarFiles RootPathVarFiles
}

VarFileGrouping defines a grouping of var files by environment.

type VarFiles

type VarFiles struct {
	Path  string
	Files []RootPathVarFile

	// HasSiblings is true if the directory is within a directory that contains other
	// root Terraform projects.
	HasSiblings bool
	// Used is true if the var files have been used by a project.
	Used bool
}

VarFiles represents a directory that contains Terraform var files. HasSiblings is true if the directory is within a directory that contains other directories that are root Terraform projects.

type Vertex

type Vertex interface {
	ID() string
	ModuleAddress() string
	Visit(mutex *sync.Mutex) error
	References() []VertexReference
}

type VertexData

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

func (*VertexData) ID

func (v *VertexData) ID() string

func (*VertexData) ModuleAddress

func (v *VertexData) ModuleAddress() string

func (*VertexData) References

func (v *VertexData) References() []VertexReference

func (*VertexData) Visit

func (v *VertexData) Visit(mutex *sync.Mutex) error

type VertexLocal

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

func (*VertexLocal) ID

func (v *VertexLocal) ID() string

func (*VertexLocal) ModuleAddress

func (v *VertexLocal) ModuleAddress() string

func (*VertexLocal) References

func (v *VertexLocal) References() []VertexReference

func (*VertexLocal) Visit

func (v *VertexLocal) Visit(mutex *sync.Mutex) error

type VertexModuleCall

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

func (*VertexModuleCall) ID

func (v *VertexModuleCall) ID() string

func (*VertexModuleCall) ModuleAddress

func (v *VertexModuleCall) ModuleAddress() string

func (*VertexModuleCall) References

func (v *VertexModuleCall) References() []VertexReference

func (*VertexModuleCall) Visit

func (v *VertexModuleCall) Visit(mutex *sync.Mutex) error

type VertexModuleExit

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

func (*VertexModuleExit) ID

func (v *VertexModuleExit) ID() string

func (*VertexModuleExit) ModuleAddress

func (v *VertexModuleExit) ModuleAddress() string

func (*VertexModuleExit) References

func (v *VertexModuleExit) References() []VertexReference

func (*VertexModuleExit) Visit

func (v *VertexModuleExit) Visit(mutex *sync.Mutex) error

type VertexOutput

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

func (*VertexOutput) ID

func (v *VertexOutput) ID() string

func (*VertexOutput) ModuleAddress

func (v *VertexOutput) ModuleAddress() string

func (*VertexOutput) References

func (v *VertexOutput) References() []VertexReference

func (*VertexOutput) Visit

func (v *VertexOutput) Visit(mutex *sync.Mutex) error

type VertexProvider

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

func (*VertexProvider) ID

func (v *VertexProvider) ID() string

func (*VertexProvider) ModuleAddress

func (v *VertexProvider) ModuleAddress() string

func (*VertexProvider) References

func (v *VertexProvider) References() []VertexReference

func (*VertexProvider) Visit

func (v *VertexProvider) Visit(mutex *sync.Mutex) error

type VertexReference

type VertexReference struct {
	ModuleAddress string
	AttributeName string
	Key           string
}

type VertexResource

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

func (*VertexResource) ID

func (v *VertexResource) ID() string

func (*VertexResource) ModuleAddress

func (v *VertexResource) ModuleAddress() string

func (*VertexResource) References

func (v *VertexResource) References() []VertexReference

func (*VertexResource) Visit

func (v *VertexResource) Visit(mutex *sync.Mutex) error

type VertexRoot

type VertexRoot struct{}

func (*VertexRoot) ID

func (v *VertexRoot) ID() string

func (*VertexRoot) ModuleAddress

func (v *VertexRoot) ModuleAddress() string

func (*VertexRoot) References

func (v *VertexRoot) References() []VertexReference

func (*VertexRoot) Visit

func (v *VertexRoot) Visit(mutex *sync.Mutex) error

type VertexVariable

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

func (*VertexVariable) ID

func (v *VertexVariable) ID() string

func (*VertexVariable) ModuleAddress

func (v *VertexVariable) ModuleAddress() string

func (*VertexVariable) References

func (v *VertexVariable) References() []VertexReference

func (*VertexVariable) Visit

func (v *VertexVariable) Visit(mutex *sync.Mutex) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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