From 9eb6a2add9635c6dde2eb84b7f2362bc17770d1b Mon Sep 17 00:00:00 2001 From: Paul Tyng Date: Sat, 18 Jul 2020 12:48:51 -0400 Subject: [PATCH] Add TF_LOG_PATH support --- tfexec/terraform.go | 11 ++++++++++- tfexec/terraform_cmd.go | 13 +++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/tfexec/terraform.go b/tfexec/terraform.go index 808be0b0..065c26e7 100644 --- a/tfexec/terraform.go +++ b/tfexec/terraform.go @@ -15,7 +15,9 @@ type Terraform struct { workingDir string execVersion string env map[string]string - logger *log.Logger + + logger *log.Logger + logPath string } // NewTerraform returns a Terraform struct with default values for all fields. @@ -77,6 +79,13 @@ func (tf *Terraform) SetLogger(logger *log.Logger) { tf.logger = logger } +// SetLogPath sets the TF_LOG_PATH environment variable for Terraform CLI +// execution. +func (tf *Terraform) SetLogPath(path string) error { + tf.logPath = path + return nil +} + func (tf *Terraform) version() (string, error) { versionCmd := tf.buildTerraformCmd(context.Background(), "version") diff --git a/tfexec/terraform_cmd.go b/tfexec/terraform_cmd.go index 7946069e..b1816a3f 100644 --- a/tfexec/terraform_cmd.go +++ b/tfexec/terraform_cmd.go @@ -65,7 +65,16 @@ func (tf *Terraform) buildEnv() []string { menv[checkpointDisableEnvVar] = os.Getenv(checkpointDisableEnvVar) } - menv[logEnvVar] = "" // so logging can't pollute our stderr output + if tf.logPath == "" { + // so logging can't pollute our stderr output + menv[logEnvVar] = "" + menv[logPathEnvVar] = "" + } else { + menv[logPathEnvVar] = tf.logPath + // Log levels other than TRACE are currently unreliable, the CLI recommends using TRACE only. + menv[logEnvVar] = "TRACE" + } + menv[automationEnvVar] = "1" env := []string{} @@ -83,7 +92,7 @@ func (tf *Terraform) buildTerraformCmd(ctx context.Context, args ...string) *exe cmd.Env = env cmd.Dir = tf.workingDir - tf.logger.Printf("Terraform command: %s", cmdString(cmd)) + tf.logger.Printf("[INFO] running Terraform command: %s", cmdString(cmd)) return cmd }