forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plan.go
349 lines (300 loc) · 8.44 KB
/
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package format
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/hashicorp/terraform/config"
"github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/colorstring"
)
// Plan is a representation of a plan optimized for display to
// an end-user, as opposed to terraform.Plan which is for internal use.
//
// DisplayPlan excludes implementation details that may otherwise appear
// in the main plan, such as destroy actions on data sources (which are
// there only to clean up the state).
type Plan struct {
Resources []*InstanceDiff
}
// InstanceDiff is a representation of an instance diff optimized
// for display, in conjunction with DisplayPlan.
type InstanceDiff struct {
Addr *terraform.ResourceAddress
Action terraform.DiffChangeType
// Attributes describes changes to the attributes of the instance.
//
// For destroy diffs this is always nil.
Attributes []*AttributeDiff
Tainted bool
Deposed bool
}
// AttributeDiff is a representation of an attribute diff optimized
// for display, in conjunction with DisplayInstanceDiff.
type AttributeDiff struct {
// Path is a dot-delimited traversal through possibly many levels of list and map structure,
// intended for display purposes only.
Path string
Action terraform.DiffChangeType
OldValue string
NewValue string
NewComputed bool
Sensitive bool
ForcesNew bool
}
// PlanStats gives summary counts for a Plan.
type PlanStats struct {
ToAdd, ToChange, ToDestroy int
}
// NewPlan produces a display-oriented Plan from a terraform.Plan.
func NewPlan(plan *terraform.Plan) *Plan {
ret := &Plan{}
if plan == nil || plan.Diff == nil || plan.Diff.Empty() {
// Nothing to do!
return ret
}
for _, m := range plan.Diff.Modules {
var modulePath []string
if !m.IsRoot() {
// trim off the leading "root" path segment, since it's implied
// when we use a path in a resource address.
modulePath = m.Path[1:]
}
for k, r := range m.Resources {
if r.Empty() {
continue
}
addr, err := terraform.ParseResourceAddressForInstanceDiff(modulePath, k)
if err != nil {
// should never happen; indicates invalid diff
panic("invalid resource address in diff")
}
dataSource := addr.Mode == config.DataResourceMode
// We create "destroy" actions for data resources so we can clean
// up their entries in state, but this is an implementation detail
// that users shouldn't see.
if dataSource && r.ChangeType() == terraform.DiffDestroy {
continue
}
did := &InstanceDiff{
Addr: addr,
Action: r.ChangeType(),
Tainted: r.DestroyTainted,
Deposed: r.DestroyDeposed,
}
if dataSource && did.Action == terraform.DiffCreate {
// Use "refresh" as the action for display, since core
// currently uses Create for this.
did.Action = terraform.DiffRefresh
}
ret.Resources = append(ret.Resources, did)
if did.Action == terraform.DiffDestroy {
// Don't show any outputs for destroy actions
continue
}
for k, a := range r.Attributes {
var action terraform.DiffChangeType
switch {
case a.NewRemoved:
action = terraform.DiffDestroy
case did.Action == terraform.DiffCreate:
action = terraform.DiffCreate
default:
action = terraform.DiffUpdate
}
did.Attributes = append(did.Attributes, &AttributeDiff{
Path: k,
Action: action,
OldValue: a.Old,
NewValue: a.New,
Sensitive: a.Sensitive,
ForcesNew: a.RequiresNew,
NewComputed: a.NewComputed,
})
}
// Sort the attributes by their paths for display
sort.Slice(did.Attributes, func(i, j int) bool {
iPath := did.Attributes[i].Path
jPath := did.Attributes[j].Path
// as a special case, "id" is always first
switch {
case iPath != jPath && (iPath == "id" || jPath == "id"):
return iPath == "id"
default:
return iPath < jPath
}
})
}
}
// Sort the instance diffs by their addresses for display.
sort.Slice(ret.Resources, func(i, j int) bool {
iAddr := ret.Resources[i].Addr
jAddr := ret.Resources[j].Addr
return iAddr.Less(jAddr)
})
return ret
}
// Format produces and returns a text representation of the receiving plan
// intended for display in a terminal.
//
// If color is not nil, it is used to colorize the output.
func (p *Plan) Format(color *colorstring.Colorize) string {
if p.Empty() {
return "This plan does nothing."
}
if color == nil {
color = &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Reset: false,
}
}
// Find the longest path length of all the paths that are changing,
// so we can align them all.
keyLen := 0
for _, r := range p.Resources {
for _, attr := range r.Attributes {
key := attr.Path
if len(key) > keyLen {
keyLen = len(key)
}
}
}
buf := new(bytes.Buffer)
for _, r := range p.Resources {
formatPlanInstanceDiff(buf, r, keyLen, color)
}
return strings.TrimSpace(buf.String())
}
// Stats returns statistics about the plan
func (p *Plan) Stats() PlanStats {
var ret PlanStats
for _, r := range p.Resources {
switch r.Action {
case terraform.DiffCreate:
ret.ToAdd++
case terraform.DiffUpdate:
ret.ToChange++
case terraform.DiffDestroyCreate:
ret.ToAdd++
ret.ToDestroy++
case terraform.DiffDestroy:
ret.ToDestroy++
}
}
return ret
}
// ActionCounts returns the number of diffs for each action type
func (p *Plan) ActionCounts() map[terraform.DiffChangeType]int {
ret := map[terraform.DiffChangeType]int{}
for _, r := range p.Resources {
ret[r.Action]++
}
return ret
}
// Empty returns true if there is at least one resource diff in the receiving plan.
func (p *Plan) Empty() bool {
return len(p.Resources) == 0
}
// DiffActionSymbol returns a string that, once passed through a
// colorstring.Colorize, will produce a result that can be written
// to a terminal to produce a symbol made of three printable
// characters, possibly interspersed with VT100 color codes.
func DiffActionSymbol(action terraform.DiffChangeType) string {
switch action {
case terraform.DiffDestroyCreate:
return "[red]-[reset]/[green]+[reset]"
case terraform.DiffCreate:
return " [green]+[reset]"
case terraform.DiffDestroy:
return " [red]-[reset]"
case terraform.DiffRefresh:
return " [cyan]<=[reset]"
default:
return " [yellow]~[reset]"
}
}
// formatPlanInstanceDiff writes the text representation of the given instance diff
// to the given buffer, using the given colorizer.
func formatPlanInstanceDiff(buf *bytes.Buffer, r *InstanceDiff, keyLen int, colorizer *colorstring.Colorize) {
addrStr := r.Addr.String()
// Determine the color for the text (green for adding, yellow
// for change, red for delete), and symbol, and output the
// resource header.
color := "yellow"
symbol := DiffActionSymbol(r.Action)
oldValues := true
switch r.Action {
case terraform.DiffDestroyCreate:
color = "yellow"
case terraform.DiffCreate:
color = "green"
oldValues = false
case terraform.DiffDestroy:
color = "red"
case terraform.DiffRefresh:
color = "cyan"
oldValues = false
}
var extraStr string
if r.Tainted {
extraStr = extraStr + " (tainted)"
}
if r.Deposed {
extraStr = extraStr + " (deposed)"
}
if r.Action == terraform.DiffDestroyCreate {
extraStr = extraStr + colorizer.Color(" [red][bold](new resource required)")
}
buf.WriteString(
colorizer.Color(fmt.Sprintf(
"[%s]%s [%s]%s%s\n",
color, symbol, color, addrStr, extraStr,
)),
)
for _, attr := range r.Attributes {
v := attr.NewValue
var dispV string
switch {
case v == "" && attr.NewComputed:
dispV = "<computed>"
case attr.Sensitive:
dispV = "<sensitive>"
default:
dispV = fmt.Sprintf("%q", v)
}
updateMsg := ""
switch {
case attr.ForcesNew && r.Action == terraform.DiffDestroyCreate:
updateMsg = colorizer.Color(" [red](forces new resource)")
case attr.Sensitive && oldValues:
updateMsg = colorizer.Color(" [yellow](attribute changed)")
}
if oldValues {
u := attr.OldValue
var dispU string
switch {
case attr.Sensitive:
dispU = "<sensitive>"
default:
dispU = fmt.Sprintf("%q", u)
}
buf.WriteString(fmt.Sprintf(
" %s:%s %s => %s%s\n",
attr.Path,
strings.Repeat(" ", keyLen-len(attr.Path)),
dispU, dispV,
updateMsg,
))
} else {
buf.WriteString(fmt.Sprintf(
" %s:%s %s%s\n",
attr.Path,
strings.Repeat(" ", keyLen-len(attr.Path)),
dispV,
updateMsg,
))
}
}
// Write the reset color so we don't bleed color into later text
buf.WriteString(colorizer.Color("[reset]\n"))
}