hcl2template

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2022 License: MPL-2.0 Imports: 49 Imported by: 0

Documentation

Overview

Package hcl2template defines code to parse hcl2 template files.

In order to configure a packer builder,provisioner, and post processor.

Checkout the files in testdata/complete/ to see what a packer config could look like.

Index

Constants

View Source
const VarEnvPrefix = "PKR_VAR_"

Prefix your environment variables with VarEnvPrefix so that Packer can see them.

Variables

View Source
var PackerConsoleHelp = strings.TrimSpace(`
Packer console HCL2 Mode.
The Packer console allows you to experiment with Packer interpolations.
You may access variables and functions in the Packer config you called the
console with.

Type in the interpolation to test and hit <enter> to see the result.

"upper(var.foo.id)" would evaluate to the ID of "foo" and uppercase is, if it
exists in your config file.

"variables" will dump all available variables and their values.

To exit the console, type "exit" and hit <enter>, or use Control-C.

/!\ It is not possible to use go templating interpolation like "{{timestamp}}"
with in HCL2 mode.
`)

Functions

func ConvertPluginConfigValueToHCLValue added in v1.7.0

func ConvertPluginConfigValueToHCLValue(v interface{}) (cty.Value, error)

func Functions added in v1.5.2

func Functions(basedir string) map[string]function.Function

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

basedir is used with file functions and allows a user to reference a file using local path. Usually basedir is the directory in which the config file is located

func GetHCL2Files added in v1.5.2

func GetHCL2Files(filename, hclSuffix, jsonSuffix string) (hclFiles, jsonFiles []string, diags hcl.Diagnostics)

GetHCL2Files returns two slices of json formatted and hcl formatted files, hclSuffix and jsonSuffix tell which file is what. Filename can be a folder or a file.

When filename is a folder all files of folder matching the suffixes will be returned. Otherwise if filename references a file and filename matches one of the suffixes it is returned in the according slice.

func PrintableCtyValue added in v1.6.0

func PrintableCtyValue(v cty.Value) string

Types

type BlockContext added in v1.7.0

type BlockContext int
const (
	InputVariableContext BlockContext = iota
	LocalContext
	BuildContext
	DatasourceContext
	NilContext
)

type BuildBlock added in v1.5.0

type BuildBlock struct {
	// Name is a string representing the named build to show in the logs
	Name string

	// A description of what this build does, it could be used in a inspect
	// call for example.
	Description string

	// HCPPackerRegistry contains the configuration for publishing the image to the HCP Packer Registry.
	HCPPackerRegistry *HCPPackerRegistryBlock

	// Sources is the list of sources that we want to start in this build block.
	Sources []SourceUseBlock

	// ProvisionerBlocks references a list of HCL provisioner block that will
	// will be ran against the sources.
	ProvisionerBlocks []*ProvisionerBlock

	// ErrorCleanupProvisionerBlock references a special provisioner block that
	// will be ran only if the provision step fails.
	ErrorCleanupProvisionerBlock *ProvisionerBlock

	// PostProcessorLists references the lists of lists of HCL post-processors
	// block that will be run against the artifacts from the provisioning
	// steps.
	PostProcessorsLists [][]*PostProcessorBlock

	HCL2Ref HCL2Ref
}

BuildBlock references an HCL 'build' block and it content, for example :

build {
	sources = [
		...
	]
	provisioner "" { ... }
	post-processor "" { ... }
}

type Builds

type Builds []*BuildBlock

type ComponentKind added in v1.7.1

type ComponentKind int

ComponentKind helps enumerate what kind of components exist in this Package.

const (
	Builder ComponentKind = iota
	Provisioner
	PostProcessor
	Datasource
)

type DatasourceBlock added in v1.7.1

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

DatasourceBlock references an HCL 'data' block.

func (*DatasourceBlock) Ref added in v1.7.1

func (data *DatasourceBlock) Ref() DatasourceRef

type DatasourceRef added in v1.7.0

type DatasourceRef struct {
	Type string
	Name string
}

type Datasources added in v1.7.0

type Datasources map[DatasourceRef]DatasourceBlock

func (*Datasources) Values added in v1.7.0

func (ds *Datasources) Values() (map[string]cty.Value, hcl.Diagnostics)

type Decodable

type Decodable interface {
	ConfigSpec() hcldec.ObjectSpec
}

Decodable structs are structs that can tell their hcl2 ObjectSpec; this config spec will be passed to hcldec.Decode and the result will be a cty.Value. This Value can then be applied on the said struct.

type HCL2Formatter added in v1.6.6

type HCL2Formatter struct {
	ShowDiff, Write, Recursive bool
	Output                     io.Writer
	// contains filtered or unexported fields
}

func NewHCL2Formatter added in v1.6.6

func NewHCL2Formatter() *HCL2Formatter

NewHCL2Formatter creates a new formatter, ready to format configuration files.

func (*HCL2Formatter) Format added in v1.6.6

func (f *HCL2Formatter) Format(path string) (int, hcl.Diagnostics)

Format all HCL2 files in path and return the total bytes formatted. If any error is encountered, zero bytes will be returned.

Path can be a directory or a file.

type HCL2PostProcessor added in v1.6.1

type HCL2PostProcessor struct {
	PostProcessor packersdk.PostProcessor
	// contains filtered or unexported fields
}

HCL2PostProcessor has a reference to the part of the HCL2 body where it is defined, allowing to completely reconfigure the PostProcessor right before calling PostProcess: with contextual variables. This permits using "${build.ID}" values for example.

func (*HCL2PostProcessor) ConfigSpec added in v1.6.1

func (p *HCL2PostProcessor) ConfigSpec() hcldec.ObjectSpec

func (*HCL2PostProcessor) Configure added in v1.6.1

func (p *HCL2PostProcessor) Configure(args ...interface{}) error

func (*HCL2PostProcessor) HCL2Prepare added in v1.6.1

func (p *HCL2PostProcessor) HCL2Prepare(buildVars map[string]interface{}) error

func (*HCL2PostProcessor) PostProcess added in v1.6.1

type HCL2Provisioner added in v1.6.1

type HCL2Provisioner struct {
	Provisioner packersdk.Provisioner
	// contains filtered or unexported fields
}

HCL2Provisioner has a reference to the part of the HCL2 body where it is defined, allowing to completely reconfigure the Provisioner right before calling Provision: with contextual variables. This permits using "${build.ID}" values for example.

func (*HCL2Provisioner) ConfigSpec added in v1.6.1

func (p *HCL2Provisioner) ConfigSpec() hcldec.ObjectSpec

func (*HCL2Provisioner) HCL2Prepare added in v1.6.1

func (p *HCL2Provisioner) HCL2Prepare(buildVars map[string]interface{}) error

func (*HCL2Provisioner) Prepare added in v1.6.1

func (p *HCL2Provisioner) Prepare(args ...interface{}) error

func (*HCL2Provisioner) Provision added in v1.6.1

func (p *HCL2Provisioner) Provision(ctx context.Context, ui packersdk.Ui, c packersdk.Communicator, vars map[string]interface{}) error

type HCL2Ref

type HCL2Ref struct {
	// references
	DefRange     hcl.Range
	TypeRange    hcl.Range
	LabelsRanges []hcl.Range

	// remainder of unparsed body
	Rest hcl.Body
}

HCL2Ref references to the source definition in configuration text file. It is used to tell were something was wrong, - like a warning or an error - long after it was parsed; allowing to give pointers as to where change/fix things in a file.

type HCPPackerRegistryBlock added in v1.7.5

type HCPPackerRegistryBlock struct {
	// Bucket slug
	Slug string
	// Bucket description
	Description string
	// Bucket labels
	BucketLabels map[string]string
	// Build labels
	BuildLabels map[string]string

	HCL2Ref
}

func (*HCPPackerRegistryBlock) WriteToBucketConfig added in v1.7.5

func (b *HCPPackerRegistryBlock) WriteToBucketConfig(bucket *packerregistry.Bucket)

type LocalBlock added in v1.6.1

type LocalBlock struct {
	Name string
	Expr hcl.Expression
	// When Sensitive is set to true Packer will try its best to hide/obfuscate
	// the variable from the output stream. By replacing the text.
	Sensitive bool
}

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

type OnlyExcept added in v1.6.0

type OnlyExcept struct {
	Only   []string `json:"only,omitempty"`
	Except []string `json:"except,omitempty"`
}

OnlyExcept is a struct that is meant to be embedded that contains the logic required for "only" and "except" meta-parameters.

func (*OnlyExcept) Skip added in v1.6.0

func (o *OnlyExcept) Skip(n string) bool

Skip says whether or not to skip the build with the given name.

func (*OnlyExcept) Validate added in v1.6.0

func (o *OnlyExcept) Validate() hcl.Diagnostics

Validate validates that the OnlyExcept settings are correct for a thing.

type PackerConfig

type PackerConfig struct {
	Packer struct {
		VersionConstraints []VersionConstraint
		RequiredPlugins    []*RequiredPlugins
	}

	// Directory where the config files are defined
	Basedir string

	// Core Packer version, for reference by plugins and template functions.
	CorePackerVersionString string

	// directory Packer was called from
	Cwd string

	// Available Source blocks
	Sources map[SourceRef]SourceBlock

	// InputVariables and LocalVariables are the list of defined input and
	// local variables. They are of the same type but are not used in the same
	// way. Local variables will not be decoded from any config file, env var,
	// or ect. Like the Input variables will.
	InputVariables Variables
	LocalVariables Variables

	Datasources Datasources

	LocalBlocks []*LocalBlock

	ValidationOptions

	// Builds is the list of Build blocks defined in the config files.
	Builds Builds
	// contains filtered or unexported fields
}

PackerConfig represents a loaded Packer HCL config. It will contain references to all possible blocks of the allowed configuration.

func (*PackerConfig) CheckCoreVersionRequirements added in v1.6.5

func (cfg *PackerConfig) CheckCoreVersionRequirements(coreVersion *version.Version) hcl.Diagnostics

CheckCoreVersionRequirements visits each of the block in the given configuration and verifies that any given Core version constraints match with the version of Packer Core that is being used.

The returned diagnostics will contain errors if any constraints do not match. The returned diagnostics might also return warnings, which should be displayed to the user.

func (*PackerConfig) ConfiguredArtifactMetadataPublisher added in v1.7.5

func (cfg *PackerConfig) ConfiguredArtifactMetadataPublisher() (*packerregistry.Bucket, hcl.Diagnostics)

ConfiguredArtifactMetadataPublisher returns a configured image bucket that can be used for publishing build image artifacts to a configured Packer Registry destination.

func (*PackerConfig) EvalContext added in v1.5.2

func (cfg *PackerConfig) EvalContext(ctx BlockContext, variables map[string]cty.Value) *hcl.EvalContext

EvalContext returns the *hcl.EvalContext that will be passed to an hcl decoder in order to tell what is the actual value of a var or a local and the list of defined functions.

func (*PackerConfig) EvaluateExpression added in v1.6.0

func (p *PackerConfig) EvaluateExpression(line string) (out string, exit bool, diags hcl.Diagnostics)

func (*PackerConfig) FixConfig added in v1.6.0

func (p *PackerConfig) FixConfig(_ packer.FixConfigOptions) (diags hcl.Diagnostics)

func (*PackerConfig) GetBuilds added in v1.6.0

func (cfg *PackerConfig) GetBuilds(opts packer.GetBuildsOptions) ([]packersdk.Build, hcl.Diagnostics)

GetBuilds returns a list of packer Build based on the HCL2 parsed build blocks. All Builders, Provisioners and Post Processors will be started and configured.

func (*PackerConfig) Initialize added in v1.6.1

func (cfg *PackerConfig) Initialize(opts packer.InitializeOptions) hcl.Diagnostics

func (*PackerConfig) InspectConfig added in v1.6.1

func (p *PackerConfig) InspectConfig(opts packer.InspectConfigOptions) int

func (*PackerConfig) PluginRequirements added in v1.7.0

func (cfg *PackerConfig) PluginRequirements() (plugingetter.Requirements, hcl.Diagnostics)

PluginRequirements returns a sorted list of plugin requirements.

type Parser

type Parser struct {
	CorePackerVersion *version.Version

	CorePackerVersionString string

	*hclparse.Parser

	PluginConfig *packer.PluginConfig
}

Parser helps you parse HCL folders. It will parse an hcl file or directory and start builders, provisioners and post-processors to configure them with the parsed HCL and then return a []packersdk.Build. Packer will use that list of Builds to run everything in order.

func (*Parser) Parse

func (p *Parser) Parse(filename string, varFiles []string, argVars map[string]string) (*PackerConfig, hcl.Diagnostics)

Parse will Parse all HCL files in filename. Path can be a folder or a file.

Parse will first Parse packer and variables blocks, omitting the rest, which can be expanded with dynamic blocks. We need to evaluate all variables for that, so that data sources can expand dynamic blocks too.

Parse returns a PackerConfig that contains configuration layout of a packer build; sources(builders)/provisioners/posts-processors will not be started and their contents wont be verified; Most syntax errors will cause an error, init should be called next to expand dynamic blocks and verify that used things do exist.

type PluginDependencyReason added in v1.7.1

type PluginDependencyReason int

PluginDependencyReason is an enumeration of reasons why a dependency might be present.

const (
	// PluginDependencyExplicit means that there is an explicit
	// "required_plugin" block in the configuration.
	PluginDependencyExplicit PluginDependencyReason = iota

	// PluginDependencyImplicit means that there is no explicit
	// "required_plugin" block but there is at least one resource that uses this
	// plugin.
	PluginDependencyImplicit
)

type PostProcessorBlock added in v1.5.0

type PostProcessorBlock struct {
	PType             string
	PName             string
	OnlyExcept        OnlyExcept
	KeepInputArtifact *bool

	HCL2Ref
}

ProvisionerBlock references a detected but unparsed post processor

func (*PostProcessorBlock) String added in v1.5.2

func (p *PostProcessorBlock) String() string

type ProvisionerBlock added in v1.5.0

type ProvisionerBlock struct {
	PType       string
	PName       string
	PauseBefore time.Duration
	MaxRetries  int
	Timeout     time.Duration
	Override    map[string]interface{}
	OnlyExcept  OnlyExcept
	HCL2Ref
}

ProvisionerBlock references a detected but unparsed provisioner

func (*ProvisionerBlock) String added in v1.5.2

func (p *ProvisionerBlock) String() string

type RequiredPlugin added in v1.7.0

type RequiredPlugin struct {
	Name string
	// Source used to be able to tell how the template referenced this source,
	// for example, "awesomecloud" instead of github.com/awesome/awesomecloud.
	// This one is left here in case we want to go back to allowing inexplicit
	// source url definitions.
	Source      string
	Type        *addrs.Plugin
	Requirement VersionConstraint
	DeclRange   hcl.Range
	PluginDependencyReason
}

RequiredPlugin represents a declaration of a dependency on a particular Plugin version or source.

type RequiredPlugins added in v1.7.0

type RequiredPlugins struct {
	RequiredPlugins map[string]*RequiredPlugin
	DeclRange       hcl.Range
}

type SourceBlock added in v1.5.2

type SourceBlock struct {
	// Type of source; ex: virtualbox-iso
	Type string
	// Given name; if any
	Name string

	// LocalName can be set in a singular source block from a build block, it
	// allows to give a special name to a build in the logs.
	LocalName string
	// contains filtered or unexported fields
}

SourceBlock references an HCL 'source' block to be used in a build for example.

func (*SourceBlock) Ref added in v1.5.2

func (source *SourceBlock) Ref() SourceRef

type SourceRef

type SourceRef struct {
	// Type of the source, for example `virtualbox-iso`
	Type string
	// Name of the source, for example `source_name`
	Name string
}

SourceRef is a nice way to put `virtualbox-iso.source_name`

var NoSource SourceRef

NoSource is the zero value of sourceRef, representing the absense of an source.

func (SourceRef) String

func (r SourceRef) String() string

type SourceUseBlock added in v1.7.0

type SourceUseBlock struct {
	// reference to an actual source block definition, or SourceBlock.
	SourceRef

	// LocalName can be set in a singular source block from a build block, it
	// allows to give a special name to a build in the logs.
	LocalName string

	// Rest of the body, in case the build.source block has more specific
	// content
	// Body can be expanded by a dynamic tag.
	Body hcl.Body
}

SourceUseBlock is a SourceBlock 'usage' from a config stand point. For example when one uses `build.sources = ["..."]` or `build.source "..." {...}`.

func (*SourceUseBlock) String added in v1.7.0

func (b *SourceUseBlock) String() string

type ValidationOptions added in v1.5.5

type ValidationOptions struct {
	Strict bool
}

type Variable added in v1.5.2

type Variable struct {
	// Values contains possible values for the variable; The last value set
	// from these will be the one used. If none is set; an error will be
	// returned by Value().
	Values []VariableAssignment

	// Validations contains all variables validation rules to be applied to the
	// used value. Only the used value - the last value from Values - is
	// validated.
	Validations []*VariableValidation

	// Cty Type of the variable. If the default value or a collected value is
	// not of this type nor can be converted to this type an error diagnostic
	// will show up. This allows us to assume that values are valid later in
	// code.
	//
	// When a default value - and no type - is passed in the variable
	// declaration, the type of the default variable will be used. This will
	// allow to ensure that users set this variable correctly.
	Type cty.Type
	// Common name of the variable
	Name string
	// Description of the variable
	Description string
	// When Sensitive is set to true Packer will try it best to hide/obfuscate
	// the variable from the output stream. By replacing the text.
	Sensitive bool

	Range hcl.Range
}

func (*Variable) GoString added in v1.5.2

func (v *Variable) GoString() string

func (*Variable) ValidateValue added in v1.7.1

func (v *Variable) ValidateValue() hcl.Diagnostics

ValidateValue tells if the selected value for the Variable is valid according to its validation settings.

func (*Variable) Value added in v1.5.2

func (v *Variable) Value() cty.Value

Value returns the last found value from the list of variable settings.

type VariableAssignment added in v1.6.6

type VariableAssignment struct {
	// From tells were it was taken from, command/varfile/env/default
	From  string
	Value cty.Value
	Expr  hcl.Expression
}

VariableAssignment represents a way a variable was set: the expression setting it and the value of that expression. It helps pinpoint were something was set in diagnostics.

type VariableValidation added in v1.6.6

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

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

	DeclRange hcl.Range
}

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

type Variables added in v1.5.2

type Variables map[string]*Variable

func (Variables) Keys added in v1.6.3

func (variables Variables) Keys() []string

func (Variables) ValidateValues added in v1.7.1

func (variables Variables) ValidateValues() hcl.Diagnostics

func (Variables) Values added in v1.5.2

func (variables Variables) Values() map[string]cty.Value

type VersionConstraint added in v1.6.5

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

VersionConstraint represents a version constraint on some resource that carries with it a source range so that a helpful diagnostic can be printed in the event that a particular constraint does not match.

Directories

Path Synopsis
Package addrs contains types that represent "addresses", which are references to specific objects within a Packer configuration.
Package addrs contains types that represent "addresses", which are references to specific objects within a Packer configuration.
Package repl provides the structs and functions necessary to run REPL for HCL2.
Package repl provides the structs and functions necessary to run REPL for HCL2.

Jump to

Keyboard shortcuts

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