-
Notifications
You must be signed in to change notification settings - Fork 21
/
terraform.go
91 lines (76 loc) · 2.21 KB
/
terraform.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//go:generate packr2
package terraform
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
"get.porter.sh/porter/pkg/context" // We are not using go-yaml because of serialization problems with jsonschema, don't use this library elsewhere
"github.com/gobuffalo/packr/v2"
"github.com/pkg/errors"
)
// DefaultWorkingDir is the default working directory for Terraform
const DefaultWorkingDir = "/cnab/app/terraform"
// terraform is the logic behind the terraform mixin
type Mixin struct {
*context.Context
schema *packr.Box
WorkingDir string
}
// New terraform mixin client, initialized with useful defaults.
func New() *Mixin {
return &Mixin{
Context: context.New(),
schema: packr.New("schema", "./schema"),
WorkingDir: DefaultWorkingDir,
}
}
func (m *Mixin) getPayloadData() ([]byte, error) {
reader := bufio.NewReader(m.In)
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, errors.Wrap(err, "could not read the payload from STDIN")
}
return data, nil
}
func (m *Mixin) getOutput(outputName string) ([]byte, error) {
cmd := m.NewCommand("terraform", "output", outputName)
cmd.Stderr = m.Err
out, err := cmd.Output()
if err != nil {
prettyCmd := fmt.Sprintf("%s %s", cmd.Path, strings.Join(cmd.Args, " "))
return nil, errors.Wrap(err, fmt.Sprintf("couldn't run command %s", prettyCmd))
}
return out, nil
}
func (m *Mixin) handleOutputs(outputs []Output) error {
for _, output := range outputs {
bytes, err := m.getOutput(output.Name)
if err != nil {
return err
}
err = m.Context.WriteMixinOutputToFile(output.Name, bytes)
if err != nil {
return errors.Wrapf(err, "unable to write output '%s'", output.Name)
}
}
return nil
}
// commandPreRun runs setup tasks applicable for every action
func (m *Mixin) commandPreRun(step *Step) error {
if step.LogLevel != "" {
os.Setenv("TF_LOG", step.LogLevel)
}
// First, change to specified working dir
if err := os.Chdir(m.WorkingDir); err != nil {
return fmt.Errorf("could not change directory to specified working dir: %s", err)
}
// Initialize Terraform
fmt.Println("Initializing Terraform...")
err := m.Init(step.BackendConfig)
if err != nil {
return fmt.Errorf("could not init terraform, %s", err)
}
return nil
}