-
Notifications
You must be signed in to change notification settings - Fork 109
/
validate.go
47 lines (37 loc) · 1.24 KB
/
validate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tfexec
import (
"bytes"
"context"
"encoding/json"
"fmt"
tfjson "github.com/hashicorp/terraform-json"
)
// Validate represents the validate subcommand to the Terraform CLI. The -json
// flag support was added in 0.12.0, so this will not work on earlier versions.
func (tf *Terraform) Validate(ctx context.Context) (*tfjson.ValidateOutput, error) {
err := tf.compatible(ctx, tf0_12_0, nil)
if err != nil {
return nil, fmt.Errorf("terraform validate -json was added in 0.12.0: %w", err)
}
cmd := tf.buildTerraformCmd(ctx, nil, "validate", "-no-color", "-json")
var outBuf = bytes.Buffer{}
cmd.Stdout = &outBuf
err = tf.runTerraformCmd(ctx, cmd)
// TODO: this command should not exit 1 if you pass -json as its hard to differentiate other errors
if err != nil && cmd.ProcessState.ExitCode() != 1 {
return nil, err
}
var ret tfjson.ValidateOutput
// TODO: ret.UseJSONNumber(true) validate output should support JSON numbers
jsonErr := json.Unmarshal(outBuf.Bytes(), &ret)
if jsonErr != nil {
// the original call was possibly bad, if it has an error, actually just return that
if err != nil {
return nil, err
}
return nil, jsonErr
}
return &ret, nil
}