From f3158e0a1838321eecba563b909da92af43bcc7b Mon Sep 17 00:00:00 2001 From: Denis O Date: Thu, 5 Oct 2023 13:43:35 -0700 Subject: [PATCH] Add configuration of default terraform executable --- modules/terraform/cmd.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/modules/terraform/cmd.go b/modules/terraform/cmd.go index 39b3a8d99..ab050fd7e 100644 --- a/modules/terraform/cmd.go +++ b/modules/terraform/cmd.go @@ -2,6 +2,7 @@ package terraform import ( "fmt" + "os/exec" "github.com/gruntwork-io/terratest/modules/collections" "github.com/gruntwork-io/terratest/modules/retry" @@ -30,10 +31,20 @@ var commandsWithParallelism = []string{ "destroy-all", } +const ( + // TofuDefaultPath command to run tofu + TofuDefaultPath = "tofu" + + // TerraformDefaultPath to run terraform + TerraformDefaultPath = "terraform" +) + +var defaultExecutable = defaultTerraformExecutable() + // GetCommonOptions extracts commons terraform options func GetCommonOptions(options *Options, args ...string) (*Options, []string) { if options.TerraformBinary == "" { - options.TerraformBinary = "tofu" + options.TerraformBinary = defaultExecutable } if options.TerraformBinary == "terragrunt" { @@ -112,3 +123,17 @@ func GetExitCodeForTerraformCommandE(t testing.TestingT, additionalOptions *Opti } return DefaultErrorExitCode, getExitCodeErr } + +func defaultTerraformExecutable() string { + cmd := exec.Command(TerraformDefaultPath, "-version") + cmd.Stdin = nil + cmd.Stdout = nil + cmd.Stderr = nil + + if err := cmd.Run(); err == nil { + return TerraformDefaultPath + } + + // fallback to Tofu if terraform is not available + return TofuDefaultPath +}