-
Notifications
You must be signed in to change notification settings - Fork 131
/
server_plan.go
171 lines (139 loc) · 4.37 KB
/
server_plan.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package runner
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/hashicorp/terraform-exec/tfexec"
tfjson "github.com/hashicorp/terraform-json"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"sigs.k8s.io/controller-runtime"
ctrl "sigs.k8s.io/controller-runtime"
)
func (r *TerraformRunnerServer) tfShowPlanFile(ctx context.Context, planPath string, opts ...tfexec.ShowOption) (*tfjson.Plan, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
// This is the only place where we disable the logger
r.tf.SetStdout(io.Discard)
r.tf.SetStderr(io.Discard)
defer r.initLogger(log)
return r.tf.ShowPlanFile(ctx, planPath, opts...)
}
func (r *TerraformRunnerServer) tfShowPlanFileRaw(ctx context.Context, planPath string, opts ...tfexec.ShowOption) (string, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
// This is the only place where we disable the logger
r.tf.SetStdout(io.Discard)
r.tf.SetStderr(io.Discard)
defer r.initLogger(log)
return r.tf.ShowPlanFileRaw(ctx, planPath, opts...)
}
func sanitizeLog(log string) string {
lines := strings.Split(log, "\n")
for i := 0; i < len(lines); i++ {
if strings.Contains(lines[i], "on generated.auto.tfvars.json line") {
if i+1 < len(lines) {
// Extract the JSON part after the line number
parts := strings.SplitN(lines[i+1], ": ", 2)
if len(parts) < 2 {
continue
}
var jsonObj map[string]interface{}
if err := json.Unmarshal([]byte(parts[1]), &jsonObj); err != nil {
continue
}
for key := range jsonObj {
jsonObj[key] = "***"
}
sanitizedJson, err := json.Marshal(jsonObj)
if err != nil {
continue
}
lines[i+1] = parts[0] + ": " + string(sanitizedJson)
}
}
}
return strings.Join(lines, "\n")
}
func (r *TerraformRunnerServer) tfPlan(ctx context.Context, opts ...tfexec.PlanOption) (bool, error) {
log := ctrl.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
// This is the only place where we disable the logger
r.tf.SetStdout(io.Discard)
errBuf := &bytes.Buffer{}
r.tf.SetStderr(errBuf)
defer r.initLogger(log)
diff, err := r.tf.Plan(ctx, opts...)
// sanitize the error message only if it's not a state lock error
var sl *tfexec.ErrStateLocked
if err != nil && errors.As(err, &sl) == false {
fmt.Fprint(os.Stderr, sanitizeLog(errBuf.String()))
err = errors.New(sanitizeLog(err.Error()))
}
return diff, err
}
func (r *TerraformRunnerServer) Plan(ctx context.Context, req *PlanRequest) (*PlanReply, error) {
log := controllerruntime.LoggerFrom(ctx, "instance-id", r.InstanceID).WithName(loggerName)
log.Info("creating a plan")
ctx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-r.Done:
cancel()
case <-ctx.Done():
}
}()
if req.TfInstance != r.InstanceID {
err := fmt.Errorf("no TF instance found")
log.Error(err, "no terraform")
return nil, err
}
var planOpt []tfexec.PlanOption
if req.Out != "" {
planOpt = append(planOpt, tfexec.Out(req.Out))
} else {
// if backend is disabled completely, there will be no plan output file (req.Out = "")
log.Info("backend seems to be disabled completely, so there will be no plan output file")
}
if req.Refresh == false {
planOpt = append(planOpt, tfexec.Refresh(req.Refresh))
}
if req.Destroy {
planOpt = append(planOpt, tfexec.Destroy(req.Destroy))
}
for _, target := range req.Targets {
planOpt = append(planOpt, tfexec.Target(target))
}
drifted, err := r.tfPlan(ctx, planOpt...)
if err != nil {
st := status.New(codes.Internal, err.Error())
var stateErr *tfexec.ErrStateLocked
if errors.As(err, &stateErr) {
st, err = st.WithDetails(&PlanReply{Message: "not ok", StateLockIdentifier: stateErr.ID})
if err != nil {
return nil, err
}
}
log.Error(err, "error creating the plan")
return nil, st.Err()
}
planCreated := false
if req.Out != "" {
planCreated = true
plan, err := r.tfShowPlanFile(ctx, req.Out)
if err != nil {
return nil, err
}
// This is the case when the plan is empty.
if plan.PlannedValues.Outputs == nil &&
plan.PlannedValues.RootModule.Resources == nil &&
plan.ResourceChanges == nil &&
plan.PriorState == nil &&
plan.OutputChanges == nil {
planCreated = false
}
}
return &PlanReply{Message: "ok", Drifted: drifted, PlanCreated: planCreated}, nil
}