iacprovisioner

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2025 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// TofuDefaultPath command to run tofu
	TofuDefaultPath = "tofu"

	// TerraformDefaultPath to run terraform
	TerraformDefaultPath = "terraform"

	// TerragruntDefaultPath to run terragrunt
	TerragruntDefaultPath = "terragrunt"
)

Variables

View Source
var (
	DefaultMaxRetries               = 3
	DefaultTimeBetweenRetries       = 5 * time.Second
	DefaultRetryableTerraformErrors = map[string]string{

		".*read: connection reset by peer.*": "Failed to reach helm charts repository.",
		".*transport is closing.*":           "Failed to reach Kubernetes API.",

		".*unable to verify signature.*":                  "Failed to retrieve plugin due to transient network error.",
		".*unable to verify checksum.*":                   "Failed to retrieve plugin due to transient network error.",
		".*no provider exists with the given name.*":      "Failed to retrieve plugin due to transient network error.",
		".*registry service is unreachable.*":             "Failed to retrieve plugin due to transient network error.",
		".*Error installing provider.*":                   "Failed to retrieve plugin due to transient network error.",
		".*Failed to query available provider packages.*": "Failed to retrieve plugin due to transient network error.",
		".*timeout while waiting for plugin to start.*":   "Failed to retrieve plugin due to transient network error.",
		".*timed out waiting for server handshake.*":      "Failed to retrieve plugin due to transient network error.",
		"could not query provider registry for":           "Failed to retrieve plugin due to transient network error.",

		".*Provider produced inconsistent result after apply.*": "Provider eventual consistency error.",
	}
)
View Source
var DefaultExecutable = defaultExecutable()
View Source
var TerraformCommandsWithLockSupport = []string{
	"plan",
	"plan-all",
	"apply",
	"apply-all",
	"destroy",
	"destroy-all",
	"init",
	"refresh",
	"taint",
	"untaint",
	"import",
}

TerraformCommandsWithLockSupport is a list of all the Terraform commands that can obtain locks on Terraform state

View Source
var TerraformCommandsWithPlanFileSupport = []string{
	"plan",
	"apply",
	"show",
	"graph",
}

TerraformCommandsWithPlanFileSupport is a list of all the Terraform commands that support interacting with plan files.

Functions

func Apply

func Apply(options *Options) (string, error)

Apply runs apply with the given options and return stdout/stderr. Note that this method does NOT call destroy and assumes the caller is responsible for cleaning up any resources created by running apply.

func CopyTerraformFolderToDest added in v0.1.0

func CopyTerraformFolderToDest(src, dest string) error

CopyTerraformFolderToDest copies the contents of the source folder to the destination folder. It filters out files that shouldn't be copied for clean Terraform testing: - Hidden files and directories (except .terraform-version and .terraform.lock.hcl) - Terraform state files (terraform.tfstate, terraform.tfstate.backup) - Terraform variable files (terraform.tfvars, terraform.tfvars.json)

func CopyTerraformFolderToTemp added in v0.1.0

func CopyTerraformFolderToTemp(folderPath string, tempFolderPrefix string) (string, error)

CopyTerraformFolderToTemp copies the given folder to a temp folder and returns the path to the copied folder. This is useful for running Terraform operations in isolation without modifying the original source directory. It filters out state files, tfvars files, and hidden files (except .terraform-version and .terraform.lock.hcl).

func Destroy

func Destroy(options *Options) (string, error)

Destroy runs terraform destroy with the given options and return stdout/stderr.

func FormatArgs

func FormatArgs(options *Options, args ...string) []string

FormatArgs converts the inputs to a format palatable to terraform. This includes converting the given vars to the format the Terraform CLI expects (-var key=value).

func FormatTerraformArgs

func FormatTerraformArgs(argName string, args []string) []string

FormatTerraformArgs will format multiple args with the arg name (e.g. "-var-file", []string{"foo.tfvars", "bar.tfvars", "baz.tfvars.json"}) returns "-var-file foo.tfvars -var-file bar.tfvars -var-file baz.tfvars.json"

func FormatTerraformBackendConfigAsArgs

func FormatTerraformBackendConfigAsArgs(vars map[string]interface{}) []string

FormatTerraformBackendConfigAsArgs formats the given variables as backend config args for Terraform (e.g. of the format -backend-config=key=value).

func FormatTerraformLockAsArgs

func FormatTerraformLockAsArgs(lockCheck bool, lockTimeout string) []string

FormatTerraformLockAsArgs formats the lock and lock-timeout variables -lock, -lock-timeout

func FormatTerraformPlanFileAsArg

func FormatTerraformPlanFileAsArg(commandType, outPath string) []string

FormatTerraformPlanFileAsArg formats the out variable as a command-line arg for Terraform (e.g. of the format -out=/some/path/to/plan.out or /some/path/to/plan.out). Only plan supports passing in the plan file as -out; the other commands expect it as the first positional argument. This returns an empty string if outPath is empty string.

func FormatTerraformPluginDirAsArgs

func FormatTerraformPluginDirAsArgs(pluginDir string) []string

FormatTerraformPluginDirAsArgs formats the plugin-dir variable -plugin-dir

func FormatTerraformVarsAsArgs

func FormatTerraformVarsAsArgs(vars map[string]interface{}) []string

FormatTerraformVarsAsArgs formats the given variables as command-line args for Terraform (e.g. of the format -var key=value).

func Init

func Init(options *Options) (string, error)

Init calls terraform init and return stdout/stderr.

func InitAndApply

func InitAndApply(options *Options) (string, error)

InitAndApply runs terraform init and apply with the given options and return stdout/stderr from the apply command. Note that this method does NOT call destroy and assumes the caller is responsible for cleaning up any resources created by running apply.

If options.CopyToTemp is true, this will copy the Terraform configuration to a temporary directory before running init and apply. This is useful for running tests in parallel without file conflicts or to avoid polluting the original source directory with generated files.

func Output

func Output(options *Options, key string) (string, error)

Output calls terraform output for the given variable and return its string value representation. It only designed to work with primitive terraform types: string, number and bool. Please use OutputStructE for anything else.

func OutputAll

func OutputAll(options *Options) (map[string]interface{}, error)

OutputAll calls terraform and returns all the outputs as a map

func OutputForKeys

func OutputForKeys(options *Options, keys []string) (map[string]interface{}, error)

OutputForKeys calls terraform output for the given key list and returns values as a map. The returned values are of type interface{} and need to be type casted as necessary. Refer to output_test.go

func OutputJson

func OutputJson(options *Options, key string) (string, error)

OutputJson calls terraform output for the given variable and returns the result as the json string. If key is an empty string, it will return all the output variables.

func OutputList

func OutputList(options *Options, key string) ([]string, error)

OutputList calls terraform output for the given variable and returns its value as a list. If the output value is not a list type, then it returns an error.

func OutputListOfObjects

func OutputListOfObjects(options *Options, key string) ([]map[string]interface{}, error)

OutputListOfObjects calls terraform output for the given variable and returns its value as a list of maps/lists. Also returns an error object if an error was generated. If the output value is not a list of maps/lists, then it fails the test.

func OutputMap

func OutputMap(options *Options, key string) (map[string]string, error)

OutputMap calls terraform output for the given variable and returns its value as a map. If the output value is not a map type, then it returns an error.

func OutputMapOfObjects

func OutputMapOfObjects(options *Options, key string) (map[string]interface{}, error)

OutputMapOfObjects calls terraform output for the given variable and returns its value as a map of lists/maps. Also returns an error object if an error was generated. If the output value is not a map of lists/maps, then it fails the test.

func OutputRequired

func OutputRequired(options *Options, key string) (string, error)

OutputRequired calls terraform output for the given variable and return its value. If the value is empty, return an error.

func OutputStruct

func OutputStruct(options *Options, key string, v interface{}) error

OutputStruct calls terraform output for the given variable and stores the result in the value pointed to by v. If v is nil or not a pointer, or if the value returned by Terraform is not appropriate for a given target type, it returns an error.

func RunCommand

func RunCommand(additionalOptions *Options, additionalArgs ...string) (string, error)

RunCommand runs the IaC Provisioner with the given arguments and options and return stdout/stderr.

Types

type EmptyOutput

type EmptyOutput string

EmptyOutput is an error that occurs when an output is empty.

func (EmptyOutput) Error

func (outputName EmptyOutput) Error() string

type ExtraArgs

type ExtraArgs struct {
	Apply           []string
	Destroy         []string
	Get             []string
	Init            []string
	Plan            []string
	Validate        []string
	ValidateInputs  []string
	WorkspaceDelete []string
	WorkspaceSelect []string
	WorkspaceNew    []string
	Output          []string
	Show            []string
}

type Options

type Options struct {
	Binary     string // Name of the binary that will be used to run the IaC code.
	WorkingDir string // The path to the folder where the IaC code is stored.

	// If set to true, Terraform configurations will be copied to a temporary directory before running.
	// This is useful for running tests in parallel without file conflicts or to avoid polluting the
	// original source directory with generated files. The temporary directory will be created with
	// the TempFolderPrefix as a prefix.
	CopyToTemp bool

	// The prefix to use when creating temporary directories for Terraform configurations.
	// Only used when CopyToTemp is true. If empty, defaults to "infraspec-terraform-".
	TempFolderPrefix string

	// The original working directory before copying to temp. This is set automatically when CopyToTemp
	// is true and should not be set manually.
	OriginalWorkingDir string

	// The vars to pass to Terraform commands using the -var option. Note that terraform does not support passing `null`
	// as a variable value through the command line. That is, if you use `map[string]interface{}{"foo": nil}` as `Vars`,
	// this will translate to the string literal `"null"` being assigned to the variable `foo`. However, nulls in
	// lists and maps/objects are supported. E.g., the following var will be set as expected (`{ bar = null }`:
	// map[string]interface{}{
	//     "foo": map[string]interface{}{"bar": nil},
	// }
	Vars map[string]interface{}

	VarFiles                 []string               // The var file paths to pass to Terraform commands using -var-file option.
	MixedVars                []Var                  // Mix of `-var` and `-var-file` in arbritrary order, use `VarInline()` `VarFile()` to set the value.
	Targets                  []string               // The target resources to pass to the terraform command with -target
	Lock                     bool                   // The lock option to pass to the terraform command with -lock
	LockTimeout              string                 // The lock timeout option to pass to the terraform command with -lock-timeout
	EnvVars                  map[string]string      // Environment variables to set when running Terraform
	BackendConfig            map[string]interface{} // The vars to pass to the terraform init command for extra configuration for the backend
	RetryableTerraformErrors map[string]string      // If Terraform apply fails with one of these (transient) errors, retry. The keys are a regexp to match against the error and the message is what to display to a user if that error is matched.
	MaxRetries               int                    // Maximum number of times to retry errors matching RetryableTerraformErrors
	TimeBetweenRetries       time.Duration          // The amount of time to wait between retries
	Upgrade                  bool                   // Whether the -upgrade flag of the terraform init command should be set to true or not
	Reconfigure              bool                   // Set the -reconfigure flag to the terraform init command
	MigrateState             bool                   // Set the -migrate-state and -force-copy (suppress 'yes' answer prompt) flag to the terraform init command
	NoColor                  bool                   // Whether the -no-color flag will be set for any Terraform command or not
	NoStderr                 bool                   // Disable stderr redirection
	SshAgent                 *ssh.SshAgent          // Overrides local SSH agent with the given in-process agent
	OutputMaxLineSize        int                    // The max size of one line in stdout and stderr (in bytes)
	Parallelism              int                    // Set the parallelism setting for Terraform
	PlanFilePath             string                 // The path to output a plan file to (for the plan command) or read one from (for the apply command)
	PluginDir                string                 // The path of downloaded plugins to pass to the terraform init command (-plugin-dir)
	SetVarsAfterVarFiles     bool                   // Pass -var options after -var-file options to Terraform commands
	WarningsAsErrors         map[string]string      // Terraform warning messages that should be treated as errors. The keys are a regexp to match against the warning and the value is what to display to a user if that warning is matched.
	ExtraArgs                ExtraArgs              // Extra arguments passed to Terraform commands
}

Options for running IaC Provisioner commands

func GetCommonOptions

func GetCommonOptions(options *Options, args ...string) (*Options, []string)

GetCommonOptions extracts commons terraform options

func WithDefaultRetryableErrors

func WithDefaultRetryableErrors(originalOptions *Options) (*Options, error)

WithDefaultRetryableErrors makes a copy of the Options object and returns an updated object with sensible defaults for retryable errors. The included retryable errors are typical errors that most terraform modules encounter during testing, and are known to self resolve upon retrying. This will fail the test if there are any errors in the cloning process.

func (*Options) Clone

func (options *Options) Clone() (*Options, error)

Clone makes a deep copy of most fields on the Options object and returns it.

NOTE: options.Logger CANNOT be deep copied, so the original values are retained.

type OutputKeyNotFound

type OutputKeyNotFound string

OutputKeyNotFound occurs when terraform output does not contain a value for the key specified in the function call

func (OutputKeyNotFound) Error

func (err OutputKeyNotFound) Error() string

type UnexpectedOutputType

type UnexpectedOutputType struct {
	Key          string
	ExpectedType string
	ActualType   string
}

UnexpectedOutputType is an error that occurs when the output is not of the type we expect

func (UnexpectedOutputType) Error

func (err UnexpectedOutputType) Error() string

type Var

type Var interface {
	Args() []string
	// contains filtered or unexported methods
}

func VarFile

func VarFile(path string) Var

func VarInline

func VarInline(name string, value interface{}) Var

Jump to

Keyboard shortcuts

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