hcl

package
v0.10.35 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: Apache-2.0 Imports: 45 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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 ExpFunctions added in v0.10.24

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 added in v0.10.32

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 IsParentTerragruntConfig added in v0.10.33

func IsParentTerragruntConfig(parent string, configFiles []string) bool

IsParentTerragruntConfig checks if a terragrunt config entry is a parent file that is referenced by another config with a find_in_parent_folders call. The find_in_parent_folders function searches up the directory tree from the file and returns the absolute path to the first terragrunt.hcl. This means if it is found we can treat this file as a child terragrunt.hcl.

func SetUUIDAttributes added in v0.9.22

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 added in v0.10.8

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 added in v0.10.8

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 added in v0.10.34

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 added in v0.10.17

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 added in v0.10.34

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. Infracost uses these references in resource evaluation to lookup connecting resource information.

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 added in v0.10.31

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 Block

type Block struct {
	// HCLBlock is the underlying hcl.Block that has been parsed from a hcl.File
	HCLBlock *hcl.Block
	// UniqueAttrs specifies infracost 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) CallDetails added in v0.10.0

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 added in v0.10.18

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 added in v0.10.31

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 added in v0.9.22

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 added in v0.10.13

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 added in v0.10.4

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 added in v0.10.32

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 added in v0.10.31

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

func (*Block) SetType added in v0.10.31

func (b *Block) SetType(t string)

func (*Block) ShouldExpand added in v0.10.4

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 added in v0.10.31

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 added in v0.9.22

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 added in v0.9.22

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 added in v0.9.22

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 added in v0.9.22

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 added in v0.10.4

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 added in v0.10.23

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 added in v0.10.31

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

func (Blocks) Matching added in v0.10.4

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 added in v0.9.23

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 added in v0.10.0

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 added in v0.10.17

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 added in v0.10.33

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

type EnvFileMatcher added in v0.10.33

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

EnvFileMatcher is used to match environment specific var files.

func CreateEnvFileMatcher added in v0.10.33

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

func (*EnvFileMatcher) EnvName added in v0.10.33

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

EnvName returns the environment name for the given var file.

func (*EnvFileMatcher) IsEnvName added in v0.10.33

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

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

func (*EnvFileMatcher) IsGlobalVarFile added in v0.10.33

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

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

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,
	spinFunc ui.SpinnerFunc,
	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 added in v0.10.31

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

func (*Evaluator) MissingVars added in v0.9.22

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 added in v0.10.31

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

func NewGraphWithRoot added in v0.10.31

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

func (*Graph) AsJSON added in v0.10.31

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

func (*Graph) Populate added in v0.10.31

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

func (*Graph) ReduceTransitively added in v0.10.31

func (g *Graph) ReduceTransitively()

func (*Graph) Run added in v0.10.31

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

func (*Graph) Walk added in v0.10.31

func (g *Graph) Walk()

type GraphVisitor added in v0.10.31

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

func NewGraphVisitor added in v0.10.31

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

func (*GraphVisitor) Visit added in v0.10.31

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

type LiteralBoolValueExpression added in v0.10.32

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 added in v0.10.32

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 added in v0.10.32

type LiteralValueCollectionExpression struct {
	*hclsyntax.LiteralValueExpr
	Expression  hcl.Expression
	MockedValue cty.Value
}

func (*LiteralValueCollectionExpression) Value added in v0.10.32

func (e *LiteralValueCollectionExpression) 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
}

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

func (*Module) Index added in v0.10.17

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 added in v0.10.17

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 added in v0.10.31

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

type ModuleConfigs added in v0.10.31

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

func NewModuleConfigs added in v0.10.31

func NewModuleConfigs() *ModuleConfigs

func (*ModuleConfigs) Add added in v0.10.31

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

func (*ModuleConfigs) Get added in v0.10.31

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

type ModuleMetadata added in v0.10.0

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 added in v0.10.34

func OptionGraphEvaluator() Option

OptionGraphEvaluator sets the Parser to use the experimental graph evaluator.

func OptionWithBlockBuilder added in v0.9.22

func OptionWithBlockBuilder(blockBuilder BlockBuilder) Option

func OptionWithInputVars

func OptionWithInputVars(vars map[string]string) 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 added in v0.10.25

func OptionWithModuleSuffix(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.

func OptionWithPlanFlagVars added in v0.9.23

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 OptionWithRawCtyInput added in v0.10.4

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 OptionWithRemoteVarLoader added in v0.9.23

func OptionWithRemoteVarLoader(host, token, localWorkspace string, loaderOpts ...RemoteVariablesLoaderOption) Option

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

func OptionWithSpinner added in v0.9.22

func OptionWithSpinner(f ui.SpinnerFunc) Option

OptionWithSpinner sets a SpinnerFunc onto the Parser. With this option enabled the Parser will send progress to the Spinner. This is disabled by default as we run the Parser concurrently underneath DirProvider and don't want to mess with its output.

func OptionWithTFEnvVars added in v0.9.23

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 initialPath. It sorts tfvar paths for precedence before adding them to the parser. Paths that don't exist will be ignored.

func OptionWithTerraformWorkspace added in v0.10.10

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 added in v0.10.33

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) EnvName added in v0.10.35

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 initialPath 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 added in v0.10.0

func (p *Parser) Path() string

Path returns the full path that the parser runs within.

func (*Parser) ProjectName added in v0.10.32

func (p *Parser) ProjectName() string

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

func (*Parser) RelativePath added in v0.10.32

func (p *Parser) RelativePath() string

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

func (*Parser) TerraformVarFiles added in v0.10.32

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

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

func (*Parser) YAML added in v0.10.31

func (p *Parser) YAML() string

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

type PathOverrideConfig added in v0.10.33

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

type ProjectLocator added in v0.10.14

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 added in v0.10.14

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

NewProjectLocator returns safely initialized ProjectLocator.

func (*ProjectLocator) FindRootModules added in v0.10.14

func (p *ProjectLocator) FindRootModules(fullPath 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 added in v0.10.14

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
}

ProjectLocatorConfig provides configuration options on how the locator functions.

type Reference

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

func (*Reference) JSONString added in v0.9.22

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 RemoteVariablesLoader added in v0.9.23

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

RemoteVariablesLoader handles loading remote variables from Terraform Cloud.

func NewRemoteVariablesLoader added in v0.9.23

func NewRemoteVariablesLoader(client *extclient.AuthedAPIClient, localWorkspace string, logger zerolog.Logger, opts ...RemoteVariablesLoaderOption) *RemoteVariablesLoader

NewRemoteVariablesLoader constructs a new loader for fetching remote variables.

func (*RemoteVariablesLoader) Load added in v0.9.23

func (r *RemoteVariablesLoader) Load(blocks Blocks) (map[string]cty.Value, error)

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

type RemoteVariablesLoaderOption added in v0.9.23

type RemoteVariablesLoaderOption func(r *RemoteVariablesLoader)

RemoteVariablesLoaderOption defines a function that can set properties on an RemoteVariablesLoader.

func RemoteVariablesLoaderWithRemoteConfig added in v0.10.35

func RemoteVariablesLoaderWithRemoteConfig(config TFCRemoteConfig) RemoteVariablesLoaderOption

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

func RemoteVariablesLoaderWithSpinner added in v0.9.23

func RemoteVariablesLoaderWithSpinner(f ui.SpinnerFunc) RemoteVariablesLoaderOption

RemoteVariablesLoaderWithSpinner enables the RemoteVariablesLoader to use an ui.Spinner to show the progress of loading the remote variables.

type RootPath added in v0.10.15

type RootPath struct {
	Matcher *EnvFileMatcher

	RepoPath string
	Path     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
}

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

func (*RootPath) AddVarFiles added in v0.10.32

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

func (*RootPath) AutoFiles added in v0.10.33

func (r *RootPath) AutoFiles() RootPathVarFiles

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

func (*RootPath) EnvFiles added in v0.10.33

func (r *RootPath) EnvFiles() RootPathVarFiles

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

func (*RootPath) EnvGroupings added in v0.10.33

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 added in v0.10.33

func (r *RootPath) GlobalFiles() RootPathVarFiles

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

func (*RootPath) RelPath added in v0.10.33

func (r *RootPath) RelPath() string

type RootPathVarFile added in v0.10.33

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 added in v0.10.33

func (r RootPathVarFile) IsChildVarFile() bool

type RootPathVarFiles added in v0.10.33

type RootPathVarFiles []RootPathVarFile

func (RootPathVarFiles) ToPaths added in v0.10.33

func (r RootPathVarFiles) ToPaths() []string

type SetAttributesFunc added in v0.9.22

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 TFCRemoteConfig added in v0.10.35

type TFCRemoteConfig struct {
	Organization string
	Workspace    string
	Host         string
}

type TreeNode added in v0.10.32

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 added in v0.10.32

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 added in v0.10.32

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 added in v0.10.32

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

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

func (*TreeNode) AssociateAuntVarFiles added in v0.10.32

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 added in v0.10.32

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 added in v0.10.32

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 added in v0.10.32

func (t *TreeNode) AssociateSiblingVarFiles()

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

func (*TreeNode) ChildNodes added in v0.10.32

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 added in v0.10.33

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

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

func (*TreeNode) CollectRootPaths added in v0.10.32

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

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

func (*TreeNode) FindTfvarsCommonParent added in v0.10.33

func (t *TreeNode) FindTfvarsCommonParent() *TreeNode

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

func (*TreeNode) ParentNode added in v0.10.32

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) PostOrder added in v0.10.32

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 added in v0.10.32

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 added in v0.10.32

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 added in v0.10.33

type VarFileGrouping struct {
	Name              string
	TerraformVarFiles RootPathVarFiles
}

VarFileGrouping defines a grouping of var files by environment.

type VarFiles added in v0.10.32

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 added in v0.10.31

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

type VertexData added in v0.10.31

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

func (*VertexData) ID added in v0.10.31

func (v *VertexData) ID() string

func (*VertexData) ModuleAddress added in v0.10.31

func (v *VertexData) ModuleAddress() string

func (*VertexData) References added in v0.10.31

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

func (*VertexData) Visit added in v0.10.31

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

type VertexLocal added in v0.10.31

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

func (*VertexLocal) ID added in v0.10.31

func (v *VertexLocal) ID() string

func (*VertexLocal) ModuleAddress added in v0.10.31

func (v *VertexLocal) ModuleAddress() string

func (*VertexLocal) References added in v0.10.31

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

func (*VertexLocal) Visit added in v0.10.31

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

type VertexModuleCall added in v0.10.31

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

func (*VertexModuleCall) ID added in v0.10.31

func (v *VertexModuleCall) ID() string

func (*VertexModuleCall) ModuleAddress added in v0.10.31

func (v *VertexModuleCall) ModuleAddress() string

func (*VertexModuleCall) References added in v0.10.31

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

func (*VertexModuleCall) Visit added in v0.10.31

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

type VertexModuleExit added in v0.10.31

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

func (*VertexModuleExit) ID added in v0.10.31

func (v *VertexModuleExit) ID() string

func (*VertexModuleExit) ModuleAddress added in v0.10.31

func (v *VertexModuleExit) ModuleAddress() string

func (*VertexModuleExit) References added in v0.10.31

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

func (*VertexModuleExit) Visit added in v0.10.31

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

type VertexOutput added in v0.10.31

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

func (*VertexOutput) ID added in v0.10.31

func (v *VertexOutput) ID() string

func (*VertexOutput) ModuleAddress added in v0.10.31

func (v *VertexOutput) ModuleAddress() string

func (*VertexOutput) References added in v0.10.31

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

func (*VertexOutput) Visit added in v0.10.31

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

type VertexProvider added in v0.10.31

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

func (*VertexProvider) ID added in v0.10.31

func (v *VertexProvider) ID() string

func (*VertexProvider) ModuleAddress added in v0.10.31

func (v *VertexProvider) ModuleAddress() string

func (*VertexProvider) References added in v0.10.31

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

func (*VertexProvider) Visit added in v0.10.31

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

type VertexReference added in v0.10.31

type VertexReference struct {
	ModuleAddress string
	AttributeName string
	Key           string
}

type VertexResource added in v0.10.31

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

func (*VertexResource) ID added in v0.10.31

func (v *VertexResource) ID() string

func (*VertexResource) ModuleAddress added in v0.10.31

func (v *VertexResource) ModuleAddress() string

func (*VertexResource) References added in v0.10.31

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

func (*VertexResource) Visit added in v0.10.31

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

type VertexRoot added in v0.10.31

type VertexRoot struct{}

func (*VertexRoot) ID added in v0.10.31

func (v *VertexRoot) ID() string

func (*VertexRoot) ModuleAddress added in v0.10.31

func (v *VertexRoot) ModuleAddress() string

func (*VertexRoot) References added in v0.10.31

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

func (*VertexRoot) Visit added in v0.10.31

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

type VertexVariable added in v0.10.31

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

func (*VertexVariable) ID added in v0.10.31

func (v *VertexVariable) ID() string

func (*VertexVariable) ModuleAddress added in v0.10.31

func (v *VertexVariable) ModuleAddress() string

func (*VertexVariable) References added in v0.10.31

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

func (*VertexVariable) Visit added in v0.10.31

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