From cba46e02ca68727b121e33b88f6baacb6714338e 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 | 14 ++++++++++++-- 2 files changed, 22 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 bbad5c12..5ae787aa 100644 --- a/tfexec/terraform_cmd.go +++ b/tfexec/terraform_cmd.go @@ -2,6 +2,7 @@ package tfexec import ( "context" + "log" "os" "os/exec" "strings" @@ -58,7 +59,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[inputEnvVar] = "0" menv[automationEnvVar] = "1" @@ -77,7 +87,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)) + log.Printf("[INFO] running Terraform command: %s", cmdString(cmd)) return cmd }