Skip to content

Commit

Permalink
feat: Also log command stderr at TRACE level
Browse files Browse the repository at this point in the history
  • Loading branch information
pdecat committed May 3, 2023
1 parent 4f7659c commit fcbd3ec
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions internal/provider/data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"os/exec"
"runtime"
"strings"

"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
Expand Down Expand Up @@ -213,32 +214,25 @@ The program must also be executable according to the platform where Terraform is
cmd.Dir = workingDir
cmd.Stdin = bytes.NewReader(queryJson)

var stderr strings.Builder
cmd.Stderr = &stderr

tflog.Trace(ctx, "Executing external program", map[string]interface{}{"program": cmd.String()})

resultJson, err := cmd.Output()

tflog.Trace(ctx, "Executed external program", map[string]interface{}{"program": cmd.String(), "output": string(resultJson)})
stderrStr := stderr.String()

if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
if exitErr.Stderr != nil && len(exitErr.Stderr) > 0 {
resp.Diagnostics.AddAttributeError(
path.Root("program"),
"External Program Execution Failed",
"The data source received an unexpected error while attempting to execute the program."+
fmt.Sprintf("\n\nProgram: %s", cmd.Path)+
fmt.Sprintf("\nError Message: %s", string(exitErr.Stderr))+
fmt.Sprintf("\nState: %s", err),
)
return
}
tflog.Trace(ctx, "Executed external program", map[string]interface{}{"program": cmd.String(), "output": string(resultJson), "stderr": stderrStr})

if err != nil {
if len(stderrStr) > 0 {
resp.Diagnostics.AddAttributeError(
path.Root("program"),
"External Program Execution Failed",
"The data source received an unexpected error while attempting to execute the program.\n\n"+
"The program was executed, however it returned no additional error messaging."+
"The data source received an unexpected error while attempting to execute the program."+
fmt.Sprintf("\n\nProgram: %s", cmd.Path)+
fmt.Sprintf("\nError Message: %s", stderrStr)+
fmt.Sprintf("\nState: %s", err),
)
return
Expand All @@ -247,9 +241,10 @@ The program must also be executable according to the platform where Terraform is
resp.Diagnostics.AddAttributeError(
path.Root("program"),
"External Program Execution Failed",
"The data source received an unexpected error while attempting to execute the program."+
"The data source received an unexpected error while attempting to execute the program.\n\n"+
"The program was executed, however it returned no additional error messaging."+
fmt.Sprintf("\n\nProgram: %s", cmd.Path)+
fmt.Sprintf("\nError: %s", err),
fmt.Sprintf("\nState: %s", err),
)
return
}
Expand Down

0 comments on commit fcbd3ec

Please sign in to comment.