7
7
"context"
8
8
"os/exec"
9
9
"strings"
10
+ "sync"
10
11
)
11
12
12
13
func (tf * Terraform ) runTerraformCmd (ctx context.Context , cmd * exec.Cmd ) error {
@@ -46,13 +47,17 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
46
47
return tf .wrapExitError (ctx , err , "" )
47
48
}
48
49
49
- exitChLen := 2
50
- exitCh := make (chan error , exitChLen )
50
+ var errStdout , errStderr error
51
+ var wg sync.WaitGroup
52
+ wg .Add (2 )
51
53
go func () {
52
- exitCh <- writeOutput (stdoutPipe , stdoutWriter )
54
+ errStdout = writeOutput (stdoutPipe , stdoutWriter )
55
+ wg .Done ()
53
56
}()
57
+
54
58
go func () {
55
- exitCh <- writeOutput (stderrPipe , stderrWriter )
59
+ errStderr = writeOutput (stderrPipe , stderrWriter )
60
+ wg .Done ()
56
61
}()
57
62
58
63
err = cmd .Wait ()
@@ -63,16 +68,16 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
63
68
return tf .wrapExitError (ctx , err , errBuf .String ())
64
69
}
65
70
66
- // Wait for the logs to finish writing
67
- counter := 0
68
- for {
69
- counter ++
70
- err := <- exitCh
71
- if err != nil && err != context .Canceled {
72
- return tf .wrapExitError (ctx , err , errBuf .String ())
73
- }
74
- if counter >= exitChLen {
75
- return ctx .Err ()
76
- }
71
+ // Ensure that outputs are done writing after Wait to be safe
72
+ wg .Wait ()
73
+
74
+ // Return error if there was an issue reading the std out/err
75
+ if errStdout != nil && ctx .Err () != nil {
76
+ return tf .wrapExitError (ctx , errStdout , errBuf .String ())
77
77
}
78
+ if errStderr != nil && ctx .Err () != nil {
79
+ return tf .wrapExitError (ctx , errStderr , errBuf .String ())
80
+ }
81
+
82
+ return nil
78
83
}
0 commit comments