Documentation
¶
Index ¶
- Constants
- Variables
- func Apply(options *Options) (string, error)
- func CopyTerraformFolderToDest(src, dest string) error
- func CopyTerraformFolderToTemp(folderPath string, tempFolderPrefix string) (string, error)
- func Destroy(options *Options) (string, error)
- func FormatArgs(options *Options, args ...string) []string
- func FormatTerraformArgs(argName string, args []string) []string
- func FormatTerraformBackendConfigAsArgs(vars map[string]interface{}) []string
- func FormatTerraformLockAsArgs(lockCheck bool, lockTimeout string) []string
- func FormatTerraformPlanFileAsArg(commandType, outPath string) []string
- func FormatTerraformPluginDirAsArgs(pluginDir string) []string
- func FormatTerraformVarsAsArgs(vars map[string]interface{}) []string
- func Init(options *Options) (string, error)
- func InitAndApply(options *Options) (string, error)
- func Output(options *Options, key string) (string, error)
- func OutputAll(options *Options) (map[string]interface{}, error)
- func OutputForKeys(options *Options, keys []string) (map[string]interface{}, error)
- func OutputJson(options *Options, key string) (string, error)
- func OutputList(options *Options, key string) ([]string, error)
- func OutputListOfObjects(options *Options, key string) ([]map[string]interface{}, error)
- func OutputMap(options *Options, key string) (map[string]string, error)
- func OutputMapOfObjects(options *Options, key string) (map[string]interface{}, error)
- func OutputRequired(options *Options, key string) (string, error)
- func OutputStruct(options *Options, key string, v interface{}) error
- func RunCommand(additionalOptions *Options, additionalArgs ...string) (string, error)
- type EmptyOutput
- type ExtraArgs
- type Options
- type OutputKeyNotFound
- type UnexpectedOutputType
- type Var
Constants ¶
const ( // TofuDefaultPath command to run tofu TofuDefaultPath = "tofu" // TerraformDefaultPath to run terraform TerraformDefaultPath = "terraform" // TerragruntDefaultPath to run terragrunt TerragruntDefaultPath = "terragrunt" )
Variables ¶
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.", } )
var DefaultExecutable = defaultExecutable()
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
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 ¶
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
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
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 FormatArgs ¶
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 ¶
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 ¶
FormatTerraformBackendConfigAsArgs formats the given variables as backend config args for Terraform (e.g. of the format -backend-config=key=value).
func FormatTerraformLockAsArgs ¶
FormatTerraformLockAsArgs formats the lock and lock-timeout variables -lock, -lock-timeout
func FormatTerraformPlanFileAsArg ¶
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 ¶
FormatTerraformPluginDirAsArgs formats the plugin-dir variable -plugin-dir
func FormatTerraformVarsAsArgs ¶
FormatTerraformVarsAsArgs formats the given variables as command-line args for Terraform (e.g. of the format -var key=value).
func InitAndApply ¶
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 ¶
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 OutputForKeys ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
OutputRequired calls terraform output for the given variable and return its value. If the value is empty, return an error.
func OutputStruct ¶
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.
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 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 ¶
GetCommonOptions extracts commons terraform options
func WithDefaultRetryableErrors ¶
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.
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 ¶
UnexpectedOutputType is an error that occurs when the output is not of the type we expect
func (UnexpectedOutputType) Error ¶
func (err UnexpectedOutputType) Error() string