From 10402aa039baa454a529be6c8ad3c4632677dfab Mon Sep 17 00:00:00 2001 From: Brian Flad Date: Wed, 13 Apr 2022 10:25:03 -0400 Subject: [PATCH] tfexec: Add (Terraform).SetLog() method Reference: https://github.com/hashicorp/terraform-exec/issues/290 --- tfexec/cmd.go | 3 +-- tfexec/terraform.go | 30 +++++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/tfexec/cmd.go b/tfexec/cmd.go index 83abd22d..21243624 100644 --- a/tfexec/cmd.go +++ b/tfexec/cmd.go @@ -149,8 +149,7 @@ func (tf *Terraform) buildEnv(mergeEnv map[string]string) []string { env[logPathEnvVar] = "" } else { env[logPathEnvVar] = tf.logPath - // Log levels other than TRACE are currently unreliable, the CLI recommends using TRACE only. - env[logEnvVar] = "TRACE" + env[logEnvVar] = tf.log } // constant automation override env vars diff --git a/tfexec/terraform.go b/tfexec/terraform.go index 2ad143a4..a743ef30 100644 --- a/tfexec/terraform.go +++ b/tfexec/terraform.go @@ -48,9 +48,14 @@ type Terraform struct { skipProviderVerify bool env map[string]string - stdout io.Writer - stderr io.Writer - logger printfer + stdout io.Writer + stderr io.Writer + logger printfer + + // TF_LOG environment variable, defaults to TRACE if logPath is set. + log string + + // TF_LOG_PATH environment variable logPath string versionLock sync.Mutex @@ -122,10 +127,29 @@ func (tf *Terraform) SetStderr(w io.Writer) { tf.stderr = w } +// SetLog sets the TF_LOG environment variable for Terraform CLI execution. +// This must be combined with a call to SetLogPath to take effect. +// +// This is only compatible with Terraform CLI 0.15.0 or later as setting the +// log level was unreliable in earlier versions. It will default to TRACE for +// those earlier versions when SetLogPath is called. +func (tf *Terraform) SetLog(log string) error { + err := tf.compatible(context.Background(), nil, tf0_15_0) + if err != nil { + return err + } + tf.log = log + return nil +} + // SetLogPath sets the TF_LOG_PATH environment variable for Terraform CLI // execution. func (tf *Terraform) SetLogPath(path string) error { tf.logPath = path + // Prevent setting the log path without enabling logging + if tf.log == "" { + tf.log = "TRACE" + } return nil }