forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
2118 lines (1763 loc) · 50.4 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package terraform
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-version"
"github.com/hashicorp/terraform/config"
"github.com/mitchellh/copystructure"
"github.com/satori/go.uuid"
)
const (
// StateVersion is the current version for our state file
StateVersion = 3
)
// rootModulePath is the path of the root module
var rootModulePath = []string{"root"}
// normalizeModulePath takes a raw module path and returns a path that
// has the rootModulePath prepended to it. If I could go back in time I
// would've never had a rootModulePath (empty path would be root). We can
// still fix this but thats a big refactor that my branch doesn't make sense
// for. Instead, this function normalizes paths.
func normalizeModulePath(p []string) []string {
k := len(rootModulePath)
// If we already have a root module prefix, we're done
if len(p) >= len(rootModulePath) {
if reflect.DeepEqual(p[:k], rootModulePath) {
return p
}
}
// None? Prefix it
result := make([]string, len(rootModulePath)+len(p))
copy(result, rootModulePath)
copy(result[k:], p)
return result
}
// State keeps track of a snapshot state-of-the-world that Terraform
// can use to keep track of what real world resources it is actually
// managing.
type State struct {
// Version is the state file protocol version.
Version int `json:"version"`
// TFVersion is the version of Terraform that wrote this state.
TFVersion string `json:"terraform_version,omitempty"`
// Serial is incremented on any operation that modifies
// the State file. It is used to detect potentially conflicting
// updates.
Serial int64 `json:"serial"`
// Lineage is set when a new, blank state is created and then
// never updated. This allows us to determine whether the serials
// of two states can be meaningfully compared.
// Apart from the guarantee that collisions between two lineages
// are very unlikely, this value is opaque and external callers
// should only compare lineage strings byte-for-byte for equality.
Lineage string `json:"lineage"`
// Remote is used to track the metadata required to
// pull and push state files from a remote storage endpoint.
Remote *RemoteState `json:"remote,omitempty"`
// Backend tracks the configuration for the backend in use with
// this state. This is used to track any changes in the backend
// configuration.
Backend *BackendState `json:"backend,omitempty"`
// Modules contains all the modules in a breadth-first order
Modules []*ModuleState `json:"modules"`
mu sync.Mutex
}
func (s *State) Lock() { s.mu.Lock() }
func (s *State) Unlock() { s.mu.Unlock() }
// NewState is used to initialize a blank state
func NewState() *State {
s := &State{}
s.init()
return s
}
// Children returns the ModuleStates that are direct children of
// the given path. If the path is "root", for example, then children
// returned might be "root.child", but not "root.child.grandchild".
func (s *State) Children(path []string) []*ModuleState {
s.Lock()
defer s.Unlock()
// TODO: test
return s.children(path)
}
func (s *State) children(path []string) []*ModuleState {
result := make([]*ModuleState, 0)
for _, m := range s.Modules {
if m == nil {
continue
}
if len(m.Path) != len(path)+1 {
continue
}
if !reflect.DeepEqual(path, m.Path[:len(path)]) {
continue
}
result = append(result, m)
}
return result
}
// AddModule adds the module with the given path to the state.
//
// This should be the preferred method to add module states since it
// allows us to optimize lookups later as well as control sorting.
func (s *State) AddModule(path []string) *ModuleState {
s.Lock()
defer s.Unlock()
return s.addModule(path)
}
func (s *State) addModule(path []string) *ModuleState {
// check if the module exists first
m := s.moduleByPath(path)
if m != nil {
return m
}
m = &ModuleState{Path: path}
m.init()
s.Modules = append(s.Modules, m)
s.sort()
return m
}
// ModuleByPath is used to lookup the module state for the given path.
// This should be the preferred lookup mechanism as it allows for future
// lookup optimizations.
func (s *State) ModuleByPath(path []string) *ModuleState {
if s == nil {
return nil
}
s.Lock()
defer s.Unlock()
return s.moduleByPath(path)
}
func (s *State) moduleByPath(path []string) *ModuleState {
for _, mod := range s.Modules {
if mod == nil {
continue
}
if mod.Path == nil {
panic("missing module path")
}
if reflect.DeepEqual(mod.Path, path) {
return mod
}
}
return nil
}
// ModuleOrphans returns all the module orphans in this state by
// returning their full paths. These paths can be used with ModuleByPath
// to return the actual state.
func (s *State) ModuleOrphans(path []string, c *config.Config) [][]string {
s.Lock()
defer s.Unlock()
return s.moduleOrphans(path, c)
}
func (s *State) moduleOrphans(path []string, c *config.Config) [][]string {
// direct keeps track of what direct children we have both in our config
// and in our state. childrenKeys keeps track of what isn't an orphan.
direct := make(map[string]struct{})
childrenKeys := make(map[string]struct{})
if c != nil {
for _, m := range c.Modules {
childrenKeys[m.Name] = struct{}{}
direct[m.Name] = struct{}{}
}
}
// Go over the direct children and find any that aren't in our keys.
var orphans [][]string
for _, m := range s.children(path) {
key := m.Path[len(m.Path)-1]
// Record that we found this key as a direct child. We use this
// later to find orphan nested modules.
direct[key] = struct{}{}
// If we have a direct child still in our config, it is not an orphan
if _, ok := childrenKeys[key]; ok {
continue
}
orphans = append(orphans, m.Path)
}
// Find the orphans that are nested...
for _, m := range s.Modules {
if m == nil {
continue
}
// We only want modules that are at least grandchildren
if len(m.Path) < len(path)+2 {
continue
}
// If it isn't part of our tree, continue
if !reflect.DeepEqual(path, m.Path[:len(path)]) {
continue
}
// If we have the direct child, then just skip it.
key := m.Path[len(path)]
if _, ok := direct[key]; ok {
continue
}
orphanPath := m.Path[:len(path)+1]
// Don't double-add if we've already added this orphan (which can happen if
// there are multiple nested sub-modules that get orphaned together).
alreadyAdded := false
for _, o := range orphans {
if reflect.DeepEqual(o, orphanPath) {
alreadyAdded = true
break
}
}
if alreadyAdded {
continue
}
// Add this orphan
orphans = append(orphans, orphanPath)
}
return orphans
}
// Empty returns true if the state is empty.
func (s *State) Empty() bool {
if s == nil {
return true
}
s.Lock()
defer s.Unlock()
return len(s.Modules) == 0
}
// HasResources returns true if the state contains any resources.
//
// This is similar to !s.Empty, but returns true also in the case where the
// state has modules but all of them are devoid of resources.
func (s *State) HasResources() bool {
if s.Empty() {
return false
}
for _, mod := range s.Modules {
if len(mod.Resources) > 0 {
return true
}
}
return false
}
// IsRemote returns true if State represents a state that exists and is
// remote.
func (s *State) IsRemote() bool {
if s == nil {
return false
}
s.Lock()
defer s.Unlock()
if s.Remote == nil {
return false
}
if s.Remote.Type == "" {
return false
}
return true
}
// Validate validates the integrity of this state file.
//
// Certain properties of the statefile are expected by Terraform in order
// to behave properly. The core of Terraform will assume that once it
// receives a State structure that it has been validated. This validation
// check should be called to ensure that.
//
// If this returns an error, then the user should be notified. The error
// response will include detailed information on the nature of the error.
func (s *State) Validate() error {
s.Lock()
defer s.Unlock()
var result error
// !!!! FOR DEVELOPERS !!!!
//
// Any errors returned from this Validate function will BLOCK TERRAFORM
// from loading a state file. Therefore, this should only contain checks
// that are only resolvable through manual intervention.
//
// !!!! FOR DEVELOPERS !!!!
// Make sure there are no duplicate module states. We open a new
// block here so we can use basic variable names and future validations
// can do the same.
{
found := make(map[string]struct{})
for _, ms := range s.Modules {
if ms == nil {
continue
}
key := strings.Join(ms.Path, ".")
if _, ok := found[key]; ok {
result = multierror.Append(result, fmt.Errorf(
strings.TrimSpace(stateValidateErrMultiModule), key))
continue
}
found[key] = struct{}{}
}
}
return result
}
// Remove removes the item in the state at the given address, returning
// any errors that may have occurred.
//
// If the address references a module state or resource, it will delete
// all children as well. To check what will be deleted, use a StateFilter
// first.
func (s *State) Remove(addr ...string) error {
s.Lock()
defer s.Unlock()
// Filter out what we need to delete
filter := &StateFilter{State: s}
results, err := filter.Filter(addr...)
if err != nil {
return err
}
// If we have no results, just exit early, we're not going to do anything.
// While what happens below is fairly fast, this is an important early
// exit since the prune below might modify the state more and we don't
// want to modify the state if we don't have to.
if len(results) == 0 {
return nil
}
// Go through each result and grab what we need
removed := make(map[interface{}]struct{})
for _, r := range results {
// Convert the path to our own type
path := append([]string{"root"}, r.Path...)
// If we removed this already, then ignore
if _, ok := removed[r.Value]; ok {
continue
}
// If we removed the parent already, then ignore
if r.Parent != nil {
if _, ok := removed[r.Parent.Value]; ok {
continue
}
}
// Add this to the removed list
removed[r.Value] = struct{}{}
switch v := r.Value.(type) {
case *ModuleState:
s.removeModule(path, v)
case *ResourceState:
s.removeResource(path, v)
case *InstanceState:
s.removeInstance(path, r.Parent.Value.(*ResourceState), v)
default:
return fmt.Errorf("unknown type to delete: %T", r.Value)
}
}
// Prune since the removal functions often do the bare minimum to
// remove a thing and may leave around dangling empty modules, resources,
// etc. Prune will clean that all up.
s.prune()
return nil
}
func (s *State) removeModule(path []string, v *ModuleState) {
for i, m := range s.Modules {
if m == v {
s.Modules, s.Modules[len(s.Modules)-1] = append(s.Modules[:i], s.Modules[i+1:]...), nil
return
}
}
}
func (s *State) removeResource(path []string, v *ResourceState) {
// Get the module this resource lives in. If it doesn't exist, we're done.
mod := s.moduleByPath(path)
if mod == nil {
return
}
// Find this resource. This is a O(N) lookup when if we had the key
// it could be O(1) but even with thousands of resources this shouldn't
// matter right now. We can easily up performance here when the time comes.
for k, r := range mod.Resources {
if r == v {
// Found it
delete(mod.Resources, k)
return
}
}
}
func (s *State) removeInstance(path []string, r *ResourceState, v *InstanceState) {
// Go through the resource and find the instance that matches this
// (if any) and remove it.
// Check primary
if r.Primary == v {
r.Primary = nil
return
}
// Check lists
lists := [][]*InstanceState{r.Deposed}
for _, is := range lists {
for i, instance := range is {
if instance == v {
// Found it, remove it
is, is[len(is)-1] = append(is[:i], is[i+1:]...), nil
// Done
return
}
}
}
}
// RootModule returns the ModuleState for the root module
func (s *State) RootModule() *ModuleState {
root := s.ModuleByPath(rootModulePath)
if root == nil {
panic("missing root module")
}
return root
}
// Equal tests if one state is equal to another.
func (s *State) Equal(other *State) bool {
// If one is nil, we do a direct check
if s == nil || other == nil {
return s == other
}
s.Lock()
defer s.Unlock()
return s.equal(other)
}
func (s *State) equal(other *State) bool {
if s == nil || other == nil {
return s == other
}
// If the versions are different, they're certainly not equal
if s.Version != other.Version {
return false
}
// If any of the modules are not equal, then this state isn't equal
if len(s.Modules) != len(other.Modules) {
return false
}
for _, m := range s.Modules {
// This isn't very optimal currently but works.
otherM := other.moduleByPath(m.Path)
if otherM == nil {
return false
}
// If they're not equal, then we're not equal!
if !m.Equal(otherM) {
return false
}
}
return true
}
type StateAgeComparison int
const (
StateAgeEqual StateAgeComparison = 0
StateAgeReceiverNewer StateAgeComparison = 1
StateAgeReceiverOlder StateAgeComparison = -1
)
// CompareAges compares one state with another for which is "older".
//
// This is a simple check using the state's serial, and is thus only as
// reliable as the serial itself. In the normal case, only one state
// exists for a given combination of lineage/serial, but Terraform
// does not guarantee this and so the result of this method should be
// used with care.
//
// Returns an integer that is negative if the receiver is older than
// the argument, positive if the converse, and zero if they are equal.
// An error is returned if the two states are not of the same lineage,
// in which case the integer returned has no meaning.
func (s *State) CompareAges(other *State) (StateAgeComparison, error) {
// nil states are "older" than actual states
switch {
case s != nil && other == nil:
return StateAgeReceiverNewer, nil
case s == nil && other != nil:
return StateAgeReceiverOlder, nil
case s == nil && other == nil:
return StateAgeEqual, nil
}
if !s.SameLineage(other) {
return StateAgeEqual, fmt.Errorf(
"can't compare two states of differing lineage",
)
}
s.Lock()
defer s.Unlock()
switch {
case s.Serial < other.Serial:
return StateAgeReceiverOlder, nil
case s.Serial > other.Serial:
return StateAgeReceiverNewer, nil
default:
return StateAgeEqual, nil
}
}
// SameLineage returns true only if the state given in argument belongs
// to the same "lineage" of states as the receiver.
func (s *State) SameLineage(other *State) bool {
s.Lock()
defer s.Unlock()
// If one of the states has no lineage then it is assumed to predate
// this concept, and so we'll accept it as belonging to any lineage
// so that a lineage string can be assigned to newer versions
// without breaking compatibility with older versions.
if s.Lineage == "" || other.Lineage == "" {
return true
}
return s.Lineage == other.Lineage
}
// DeepCopy performs a deep copy of the state structure and returns
// a new structure.
func (s *State) DeepCopy() *State {
copy, err := copystructure.Config{Lock: true}.Copy(s)
if err != nil {
panic(err)
}
return copy.(*State)
}
// IncrementSerialMaybe increments the serial number of this state
// if it different from the other state.
func (s *State) IncrementSerialMaybe(other *State) {
if s == nil {
return
}
if other == nil {
return
}
s.Lock()
defer s.Unlock()
if s.Serial > other.Serial {
return
}
if other.TFVersion != s.TFVersion || !s.equal(other) {
if other.Serial > s.Serial {
s.Serial = other.Serial
}
s.Serial++
}
}
// FromFutureTerraform checks if this state was written by a Terraform
// version from the future.
func (s *State) FromFutureTerraform() bool {
s.Lock()
defer s.Unlock()
// No TF version means it is certainly from the past
if s.TFVersion == "" {
return false
}
v := version.Must(version.NewVersion(s.TFVersion))
return SemVersion.LessThan(v)
}
func (s *State) Init() {
s.Lock()
defer s.Unlock()
s.init()
}
func (s *State) init() {
if s.Version == 0 {
s.Version = StateVersion
}
if s.moduleByPath(rootModulePath) == nil {
s.addModule(rootModulePath)
}
s.ensureHasLineage()
for _, mod := range s.Modules {
if mod != nil {
mod.init()
}
}
if s.Remote != nil {
s.Remote.init()
}
}
func (s *State) EnsureHasLineage() {
s.Lock()
defer s.Unlock()
s.ensureHasLineage()
}
func (s *State) ensureHasLineage() {
if s.Lineage == "" {
s.Lineage = uuid.NewV4().String()
log.Printf("[DEBUG] New state was assigned lineage %q\n", s.Lineage)
} else {
log.Printf("[TRACE] Preserving existing state lineage %q\n", s.Lineage)
}
}
// AddModuleState insert this module state and override any existing ModuleState
func (s *State) AddModuleState(mod *ModuleState) {
mod.init()
s.Lock()
defer s.Unlock()
s.addModuleState(mod)
}
func (s *State) addModuleState(mod *ModuleState) {
for i, m := range s.Modules {
if reflect.DeepEqual(m.Path, mod.Path) {
s.Modules[i] = mod
return
}
}
s.Modules = append(s.Modules, mod)
s.sort()
}
// prune is used to remove any resources that are no longer required
func (s *State) prune() {
if s == nil {
return
}
// Filter out empty modules.
// A module is always assumed to have a path, and it's length isn't always
// bounds checked later on. Modules may be "emptied" during destroy, but we
// never want to store those in the state.
for i := 0; i < len(s.Modules); i++ {
if s.Modules[i] == nil || len(s.Modules[i].Path) == 0 {
s.Modules = append(s.Modules[:i], s.Modules[i+1:]...)
i--
}
}
for _, mod := range s.Modules {
mod.prune()
}
if s.Remote != nil && s.Remote.Empty() {
s.Remote = nil
}
}
// sort sorts the modules
func (s *State) sort() {
sort.Sort(moduleStateSort(s.Modules))
// Allow modules to be sorted
for _, m := range s.Modules {
if m != nil {
m.sort()
}
}
}
func (s *State) String() string {
if s == nil {
return "<nil>"
}
s.Lock()
defer s.Unlock()
var buf bytes.Buffer
for _, m := range s.Modules {
mStr := m.String()
// If we're the root module, we just write the output directly.
if reflect.DeepEqual(m.Path, rootModulePath) {
buf.WriteString(mStr + "\n")
continue
}
buf.WriteString(fmt.Sprintf("module.%s:\n", strings.Join(m.Path[1:], ".")))
s := bufio.NewScanner(strings.NewReader(mStr))
for s.Scan() {
text := s.Text()
if text != "" {
text = " " + text
}
buf.WriteString(fmt.Sprintf("%s\n", text))
}
}
return strings.TrimSpace(buf.String())
}
// BackendState stores the configuration to connect to a remote backend.
type BackendState struct {
Type string `json:"type"` // Backend type
Config map[string]interface{} `json:"config"` // Backend raw config
// Hash is the hash code to uniquely identify the original source
// configuration. We use this to detect when there is a change in
// configuration even when "type" isn't changed.
Hash uint64 `json:"hash"`
}
// Empty returns true if BackendState has no state.
func (s *BackendState) Empty() bool {
return s == nil || s.Type == ""
}
// Rehash returns a unique content hash for this backend's configuration
// as a uint64 value.
// The Hash stored in the backend state needs to match the config itself, but
// we need to compare the backend config after it has been combined with all
// options.
// This function must match the implementation used by config.Backend.
func (s *BackendState) Rehash() uint64 {
if s == nil {
return 0
}
cfg := config.Backend{
Type: s.Type,
RawConfig: &config.RawConfig{
Raw: s.Config,
},
}
return cfg.Rehash()
}
// RemoteState is used to track the information about a remote
// state store that we push/pull state to.
type RemoteState struct {
// Type controls the client we use for the remote state
Type string `json:"type"`
// Config is used to store arbitrary configuration that
// is type specific
Config map[string]string `json:"config"`
mu sync.Mutex
}
func (s *RemoteState) Lock() { s.mu.Lock() }
func (s *RemoteState) Unlock() { s.mu.Unlock() }
func (r *RemoteState) init() {
r.Lock()
defer r.Unlock()
if r.Config == nil {
r.Config = make(map[string]string)
}
}
func (r *RemoteState) deepcopy() *RemoteState {
r.Lock()
defer r.Unlock()
confCopy := make(map[string]string, len(r.Config))
for k, v := range r.Config {
confCopy[k] = v
}
return &RemoteState{
Type: r.Type,
Config: confCopy,
}
}
func (r *RemoteState) Empty() bool {
if r == nil {
return true
}
r.Lock()
defer r.Unlock()
return r.Type == ""
}
func (r *RemoteState) Equals(other *RemoteState) bool {
r.Lock()
defer r.Unlock()
if r.Type != other.Type {
return false
}
if len(r.Config) != len(other.Config) {
return false
}
for k, v := range r.Config {
if other.Config[k] != v {
return false
}
}
return true
}
// OutputState is used to track the state relevant to a single output.
type OutputState struct {
// Sensitive describes whether the output is considered sensitive,
// which may lead to masking the value on screen in some cases.
Sensitive bool `json:"sensitive"`
// Type describes the structure of Value. Valid values are "string",
// "map" and "list"
Type string `json:"type"`
// Value contains the value of the output, in the structure described
// by the Type field.
Value interface{} `json:"value"`
mu sync.Mutex
}
func (s *OutputState) Lock() { s.mu.Lock() }
func (s *OutputState) Unlock() { s.mu.Unlock() }
func (s *OutputState) String() string {
return fmt.Sprintf("%#v", s.Value)
}
// Equal compares two OutputState structures for equality. nil values are
// considered equal.
func (s *OutputState) Equal(other *OutputState) bool {
if s == nil && other == nil {
return true
}
if s == nil || other == nil {
return false
}
s.Lock()
defer s.Unlock()
if s.Type != other.Type {
return false
}
if s.Sensitive != other.Sensitive {
return false
}
if !reflect.DeepEqual(s.Value, other.Value) {
return false
}
return true
}
func (s *OutputState) deepcopy() *OutputState {
if s == nil {
return nil
}
stateCopy, err := copystructure.Config{Lock: true}.Copy(s)
if err != nil {
panic(fmt.Errorf("Error copying output value: %s", err))
}
return stateCopy.(*OutputState)
}
// ModuleState is used to track all the state relevant to a single
// module. Previous to Terraform 0.3, all state belonged to the "root"
// module.
type ModuleState struct {
// Path is the import path from the root module. Modules imports are
// always disjoint, so the path represents amodule tree
Path []string `json:"path"`
// Outputs declared by the module and maintained for each module
// even though only the root module technically needs to be kept.
// This allows operators to inspect values at the boundaries.
Outputs map[string]*OutputState `json:"outputs"`
// Resources is a mapping of the logically named resource to
// the state of the resource. Each resource may actually have
// N instances underneath, although a user only needs to think
// about the 1:1 case.
Resources map[string]*ResourceState `json:"resources"`
// Dependencies are a list of things that this module relies on
// existing to remain intact. For example: an module may depend
// on a VPC ID given by an aws_vpc resource.
//
// Terraform uses this information to build valid destruction
// orders and to warn the user if they're destroying a module that
// another resource depends on.
//
// Things can be put into this list that may not be managed by
// Terraform. If Terraform doesn't find a matching ID in the
// overall state, then it assumes it isn't managed and doesn't
// worry about it.
Dependencies []string `json:"depends_on"`
mu sync.Mutex
}
func (s *ModuleState) Lock() { s.mu.Lock() }
func (s *ModuleState) Unlock() { s.mu.Unlock() }
// Equal tests whether one module state is equal to another.
func (m *ModuleState) Equal(other *ModuleState) bool {
m.Lock()
defer m.Unlock()
// Paths must be equal
if !reflect.DeepEqual(m.Path, other.Path) {
return false