/
state.go
480 lines (407 loc) · 13.7 KB
/
state.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package jsonstate
import (
"encoding/json"
"fmt"
"sort"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/lang/marks"
"github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/states/statefile"
"github.com/hashicorp/terraform/internal/terraform"
)
// FormatVersion represents the version of the json format and will be
// incremented for any change to this format that requires changes to a
// consuming parser.
const FormatVersion = "1.0"
// state is the top-level representation of the json format of a terraform
// state.
type state struct {
FormatVersion string `json:"format_version,omitempty"`
TerraformVersion string `json:"terraform_version,omitempty"`
Values *stateValues `json:"values,omitempty"`
}
// stateValues is the common representation of resolved values for both the prior
// state (which is always complete) and the planned new state.
type stateValues struct {
Outputs map[string]output `json:"outputs,omitempty"`
RootModule module `json:"root_module,omitempty"`
}
type output struct {
Sensitive bool `json:"sensitive"`
Value json.RawMessage `json:"value,omitempty"`
Type json.RawMessage `json:"type,omitempty"`
}
// module is the representation of a module in state. This can be the root module
// or a child module
type module struct {
// Resources are sorted in a user-friendly order that is undefined at this
// time, but consistent.
Resources []resource `json:"resources,omitempty"`
// Address is the absolute module address, omitted for the root module
Address string `json:"address,omitempty"`
// Each module object can optionally have its own nested "child_modules",
// recursively describing the full module tree.
ChildModules []module `json:"child_modules,omitempty"`
}
// Resource is the representation of a resource in the state.
type resource struct {
// Address is the absolute resource address
Address string `json:"address,omitempty"`
// Mode can be "managed" or "data"
Mode string `json:"mode,omitempty"`
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
// Index is omitted for a resource not using `count` or `for_each`.
Index addrs.InstanceKey `json:"index,omitempty"`
// ProviderName allows the property "type" to be interpreted unambiguously
// in the unusual situation where a provider offers a resource type whose
// name does not start with its own name, such as the "googlebeta" provider
// offering "google_compute_instance".
ProviderName string `json:"provider_name"`
// SchemaVersion indicates which version of the resource type schema the
// "values" property conforms to.
SchemaVersion uint64 `json:"schema_version"`
// AttributeValues is the JSON representation of the attribute values of the
// resource, whose structure depends on the resource type schema. Any
// unknown values are omitted or set to null, making them indistinguishable
// from absent values.
AttributeValues attributeValues `json:"values,omitempty"`
// SensitiveValues is similar to AttributeValues, but with all sensitive
// values replaced with true, and all non-sensitive leaf values omitted.
SensitiveValues json.RawMessage `json:"sensitive_values,omitempty"`
// DependsOn contains a list of the resource's dependencies. The entries are
// addresses relative to the containing module.
DependsOn []string `json:"depends_on,omitempty"`
// Tainted is true if the resource is tainted in terraform state.
Tainted bool `json:"tainted,omitempty"`
// Deposed is set if the resource is deposed in terraform state.
DeposedKey string `json:"deposed_key,omitempty"`
}
// attributeValues is the JSON representation of the attribute values of the
// resource, whose structure depends on the resource type schema.
type attributeValues map[string]interface{}
func marshalAttributeValues(value cty.Value) attributeValues {
// unmark our value to show all values
value, _ = value.UnmarkDeep()
if value == cty.NilVal || value.IsNull() {
return nil
}
ret := make(attributeValues)
it := value.ElementIterator()
for it.Next() {
k, v := it.Element()
vJSON, _ := ctyjson.Marshal(v, v.Type())
ret[k.AsString()] = json.RawMessage(vJSON)
}
return ret
}
// newState() returns a minimally-initialized state
func newState() *state {
return &state{
FormatVersion: FormatVersion,
}
}
// Marshal returns the json encoding of a terraform state.
func Marshal(sf *statefile.File, schemas *terraform.Schemas) ([]byte, error) {
output := newState()
if sf == nil || sf.State.Empty() {
ret, err := json.Marshal(output)
return ret, err
}
if sf.TerraformVersion != nil {
output.TerraformVersion = sf.TerraformVersion.String()
}
// output.StateValues
err := output.marshalStateValues(sf.State, schemas)
if err != nil {
return nil, err
}
ret, err := json.Marshal(output)
return ret, err
}
func (jsonstate *state) marshalStateValues(s *states.State, schemas *terraform.Schemas) error {
var sv stateValues
var err error
// only marshal the root module outputs
sv.Outputs, err = marshalOutputs(s.RootModule().OutputValues)
if err != nil {
return err
}
// use the state and module map to build up the module structure
sv.RootModule, err = marshalRootModule(s, schemas)
if err != nil {
return err
}
jsonstate.Values = &sv
return nil
}
func marshalOutputs(outputs map[string]*states.OutputValue) (map[string]output, error) {
if outputs == nil {
return nil, nil
}
ret := make(map[string]output)
for k, v := range outputs {
ty := v.Value.Type()
ov, err := ctyjson.Marshal(v.Value, ty)
if err != nil {
return ret, err
}
ot, err := ctyjson.MarshalType(ty)
if err != nil {
return ret, err
}
ret[k] = output{
Value: ov,
Type: ot,
Sensitive: v.Sensitive,
}
}
return ret, nil
}
func marshalRootModule(s *states.State, schemas *terraform.Schemas) (module, error) {
var ret module
var err error
ret.Address = ""
rs, err := marshalResources(s.RootModule().Resources, addrs.RootModuleInstance, schemas)
if err != nil {
return ret, err
}
ret.Resources = rs
// build a map of module -> set[child module addresses]
moduleChildSet := make(map[string]map[string]struct{})
for _, mod := range s.Modules {
if mod.Addr.IsRoot() {
continue
} else {
for childAddr := mod.Addr; !childAddr.IsRoot(); childAddr = childAddr.Parent() {
if _, ok := moduleChildSet[childAddr.Parent().String()]; !ok {
moduleChildSet[childAddr.Parent().String()] = map[string]struct{}{}
}
moduleChildSet[childAddr.Parent().String()][childAddr.String()] = struct{}{}
}
}
}
// transform the previous map into map of module -> [child module addresses]
moduleMap := make(map[string][]addrs.ModuleInstance)
for parent, children := range moduleChildSet {
for child := range children {
childModuleInstance, diags := addrs.ParseModuleInstanceStr(child)
if diags.HasErrors() {
return ret, diags.Err()
}
moduleMap[parent] = append(moduleMap[parent], childModuleInstance)
}
}
// use the state and module map to build up the module structure
ret.ChildModules, err = marshalModules(s, schemas, moduleMap[""], moduleMap)
return ret, err
}
// marshalModules is an ungainly recursive function to build a module structure
// out of terraform state.
func marshalModules(
s *states.State,
schemas *terraform.Schemas,
modules []addrs.ModuleInstance,
moduleMap map[string][]addrs.ModuleInstance,
) ([]module, error) {
var ret []module
for _, child := range modules {
// cm for child module, naming things is hard.
cm := module{Address: child.String()}
// the module may be resourceless and contain only submodules, it will then be nil here
stateMod := s.Module(child)
if stateMod != nil {
rs, err := marshalResources(stateMod.Resources, stateMod.Addr, schemas)
if err != nil {
return nil, err
}
cm.Resources = rs
}
if moduleMap[child.String()] != nil {
moreChildModules, err := marshalModules(s, schemas, moduleMap[child.String()], moduleMap)
if err != nil {
return nil, err
}
cm.ChildModules = moreChildModules
}
ret = append(ret, cm)
}
// sort the child modules by address for consistency.
sort.Slice(ret, func(i, j int) bool {
return ret[i].Address < ret[j].Address
})
return ret, nil
}
func marshalResources(resources map[string]*states.Resource, module addrs.ModuleInstance, schemas *terraform.Schemas) ([]resource, error) {
var ret []resource
for _, r := range resources {
for k, ri := range r.Instances {
resAddr := r.Addr.Resource
current := resource{
Address: r.Addr.Instance(k).String(),
Index: k,
Type: resAddr.Type,
Name: resAddr.Name,
ProviderName: r.ProviderConfig.Provider.String(),
}
switch resAddr.Mode {
case addrs.ManagedResourceMode:
current.Mode = "managed"
case addrs.DataResourceMode:
current.Mode = "data"
default:
return ret, fmt.Errorf("resource %s has an unsupported mode %s",
resAddr.String(),
resAddr.Mode.String(),
)
}
schema, version := schemas.ResourceTypeConfig(
r.ProviderConfig.Provider,
resAddr.Mode,
resAddr.Type,
)
// It is possible that the only instance is deposed
if ri.Current != nil {
if version != ri.Current.SchemaVersion {
return nil, fmt.Errorf("schema version %d for %s in state does not match version %d from the provider", ri.Current.SchemaVersion, resAddr, version)
}
current.SchemaVersion = ri.Current.SchemaVersion
if schema == nil {
return nil, fmt.Errorf("no schema found for %s (in provider %s)", resAddr.String(), r.ProviderConfig.Provider)
}
riObj, err := ri.Current.Decode(schema.ImpliedType())
if err != nil {
return nil, err
}
current.AttributeValues = marshalAttributeValues(riObj.Value)
s := SensitiveAsBool(riObj.Value)
v, err := ctyjson.Marshal(s, s.Type())
if err != nil {
return nil, err
}
current.SensitiveValues = v
if len(riObj.Dependencies) > 0 {
dependencies := make([]string, len(riObj.Dependencies))
for i, v := range riObj.Dependencies {
dependencies[i] = v.String()
}
current.DependsOn = dependencies
}
if riObj.Status == states.ObjectTainted {
current.Tainted = true
}
ret = append(ret, current)
}
for deposedKey, rios := range ri.Deposed {
// copy the base fields from the current instance
deposed := resource{
Address: current.Address,
Type: current.Type,
Name: current.Name,
ProviderName: current.ProviderName,
Mode: current.Mode,
Index: current.Index,
}
riObj, err := rios.Decode(schema.ImpliedType())
if err != nil {
return nil, err
}
deposed.AttributeValues = marshalAttributeValues(riObj.Value)
s := SensitiveAsBool(riObj.Value)
v, err := ctyjson.Marshal(s, s.Type())
if err != nil {
return nil, err
}
deposed.SensitiveValues = v
if len(riObj.Dependencies) > 0 {
dependencies := make([]string, len(riObj.Dependencies))
for i, v := range riObj.Dependencies {
dependencies[i] = v.String()
}
deposed.DependsOn = dependencies
}
if riObj.Status == states.ObjectTainted {
deposed.Tainted = true
}
deposed.DeposedKey = deposedKey.String()
ret = append(ret, deposed)
}
}
}
sort.Slice(ret, func(i, j int) bool {
return ret[i].Address < ret[j].Address
})
return ret, nil
}
func SensitiveAsBool(val cty.Value) cty.Value {
if val.HasMark(marks.Sensitive) {
return cty.True
}
ty := val.Type()
switch {
case val.IsNull(), ty.IsPrimitiveType(), ty.Equals(cty.DynamicPseudoType):
return cty.False
case ty.IsListType() || ty.IsTupleType() || ty.IsSetType():
if !val.IsKnown() {
// If the collection is unknown we can't say anything about the
// sensitivity of its contents
return cty.EmptyTupleVal
}
length := val.LengthInt()
if length == 0 {
// If there are no elements then we can't have sensitive values
return cty.EmptyTupleVal
}
vals := make([]cty.Value, 0, length)
it := val.ElementIterator()
for it.Next() {
_, v := it.Element()
vals = append(vals, SensitiveAsBool(v))
}
// The above transform may have changed the types of some of the
// elements, so we'll always use a tuple here in case we've now made
// different elements have different types. Our ultimate goal is to
// marshal to JSON anyway, and all of these sequence types are
// indistinguishable in JSON.
return cty.TupleVal(vals)
case ty.IsMapType() || ty.IsObjectType():
if !val.IsKnown() {
// If the map/object is unknown we can't say anything about the
// sensitivity of its attributes
return cty.EmptyObjectVal
}
var length int
switch {
case ty.IsMapType():
length = val.LengthInt()
default:
length = len(val.Type().AttributeTypes())
}
if length == 0 {
// If there are no elements then we can't have sensitive values
return cty.EmptyObjectVal
}
vals := make(map[string]cty.Value)
it := val.ElementIterator()
for it.Next() {
k, v := it.Element()
s := SensitiveAsBool(v)
// Omit all of the "false"s for non-sensitive values for more
// compact serialization
if !s.RawEquals(cty.False) {
vals[k.AsString()] = s
}
}
// The above transform may have changed the types of some of the
// elements, so we'll always use an object here in case we've now made
// different elements have different types. Our ultimate goal is to
// marshal to JSON anyway, and all of these mapping types are
// indistinguishable in JSON.
return cty.ObjectVal(vals)
default:
// Should never happen, since the above should cover all types
panic(fmt.Sprintf("sensitiveAsBool cannot handle %#v", val))
}
}