forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
meta_backend.go
1739 lines (1469 loc) · 52.1 KB
/
meta_backend.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 command
// This file contains all the Backend-related function calls on Meta,
// exported and private.
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"path/filepath"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/hcl"
"github.com/hashicorp/terraform/backend"
"github.com/hashicorp/terraform/command/clistate"
"github.com/hashicorp/terraform/config"
"github.com/hashicorp/terraform/state"
"github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/mapstructure"
backendinit "github.com/hashicorp/terraform/backend/init"
backendlocal "github.com/hashicorp/terraform/backend/local"
)
// BackendOpts are the options used to initialize a backend.Backend.
type BackendOpts struct {
// Module is the root module from which we will extract the terraform and
// backend configuration.
Config *config.Config
// ConfigFile is a path to a file that contains configuration that
// is merged directly into the backend configuration when loaded
// from a file.
ConfigFile string
// ConfigExtra is extra configuration to merge into the backend
// configuration after the extra file above.
ConfigExtra map[string]interface{}
// Plan is a plan that is being used. If this is set, the backend
// configuration and output configuration will come from this plan.
Plan *terraform.Plan
// Init should be set to true if initialization is allowed. If this is
// false, then any configuration that requires configuration will show
// an error asking the user to reinitialize.
Init bool
// ForceLocal will force a purely local backend, including state.
// You probably don't want to set this.
ForceLocal bool
}
// Backend initializes and returns the backend for this CLI session.
//
// The backend is used to perform the actual Terraform operations. This
// abstraction enables easily sliding in new Terraform behavior such as
// remote state storage, remote operations, etc. while allowing the CLI
// to remain mostly identical.
//
// This will initialize a new backend for each call, which can carry some
// overhead with it. Please reuse the returned value for optimal behavior.
//
// Only one backend should be used per Meta. This function is stateful
// and is unsafe to create multiple backends used at once. This function
// can be called multiple times with each backend being "live" (usable)
// one at a time.
func (m *Meta) Backend(opts *BackendOpts) (backend.Enhanced, error) {
// If no opts are set, then initialize
if opts == nil {
opts = &BackendOpts{}
}
// Initialize a backend from the config unless we're forcing a purely
// local operation.
var b backend.Backend
if !opts.ForceLocal {
var err error
// If we have a plan then, we get the the backend from there. Otherwise,
// the backend comes from the configuration.
if opts.Plan != nil {
b, err = m.backendFromPlan(opts)
} else {
b, err = m.backendFromConfig(opts)
}
if err != nil {
return nil, err
}
log.Printf("[INFO] command: backend initialized: %T", b)
}
// Setup the CLI opts we pass into backends that support it
cliOpts := &backend.CLIOpts{
CLI: m.Ui,
CLIColor: m.Colorize(),
StatePath: m.statePath,
StateOutPath: m.stateOutPath,
StateBackupPath: m.backupPath,
ContextOpts: m.contextOpts(),
Input: m.Input(),
}
// Don't validate if we have a plan. Validation is normally harmless here,
// but validation requires interpolation, and `file()` function calls may
// not have the original files in the current execution context.
cliOpts.Validation = opts.Plan == nil
// If the backend supports CLI initialization, do it.
if cli, ok := b.(backend.CLI); ok {
if err := cli.CLIInit(cliOpts); err != nil {
return nil, fmt.Errorf(
"Error initializing backend %T: %s\n\n"+
"This is a bug, please report it to the backend developer",
b, err)
}
}
// If the result of loading the backend is an enhanced backend,
// then return that as-is. This works even if b == nil (it will be !ok).
if enhanced, ok := b.(backend.Enhanced); ok {
return enhanced, nil
}
// We either have a non-enhanced backend or no backend configured at
// all. In either case, we use local as our enhanced backend and the
// non-enhanced (if any) as the state backend.
if !opts.ForceLocal {
log.Printf("[INFO] command: backend %T is not enhanced, wrapping in local", b)
}
// Build the local backend
local := &backendlocal.Local{Backend: b}
if err := local.CLIInit(cliOpts); err != nil {
// Local backend isn't allowed to fail. It would be a bug.
panic(err)
}
return local, nil
}
// IsLocalBackend returns true if the backend is a local backend. We use this
// for some checks that require a remote backend.
func (m *Meta) IsLocalBackend(b backend.Backend) bool {
// Is it a local backend?
bLocal, ok := b.(*backendlocal.Local)
// If it is, does it not have an alternate state backend?
if ok {
ok = bLocal.Backend == nil
}
return ok
}
// Operation initializes a new backend.Operation struct.
//
// This prepares the operation. After calling this, the caller is expected
// to modify fields of the operation such as Sequence to specify what will
// be called.
func (m *Meta) Operation() *backend.Operation {
return &backend.Operation{
PlanOutBackend: m.backendState,
Targets: m.targets,
UIIn: m.UIInput(),
UIOut: m.Ui,
Workspace: m.Workspace(),
LockState: m.stateLock,
StateLockTimeout: m.stateLockTimeout,
}
}
// backendConfig returns the local configuration for the backend
func (m *Meta) backendConfig(opts *BackendOpts) (*config.Backend, error) {
if opts.Config == nil {
// check if the config was missing, or just not required
conf, err := m.Config(".")
if err != nil {
return nil, err
}
if conf == nil {
log.Println("[INFO] command: no config, returning nil")
return nil, nil
}
log.Println("[WARNING] BackendOpts.Config not set, but config found")
opts.Config = conf
}
c := opts.Config
// If there is no Terraform configuration block, no backend config
if c.Terraform == nil {
log.Println("[INFO] command: empty terraform config, returning nil")
return nil, nil
}
// Get the configuration for the backend itself.
backend := c.Terraform.Backend
if backend == nil {
log.Println("[INFO] command: empty backend config, returning nil")
return nil, nil
}
// If we have a config file set, load that and merge.
if opts.ConfigFile != "" {
log.Printf(
"[DEBUG] command: loading extra backend config from: %s",
opts.ConfigFile)
rc, err := m.backendConfigFile(opts.ConfigFile)
if err != nil {
return nil, fmt.Errorf(
"Error loading extra configuration file for backend: %s", err)
}
// Merge in the configuration
backend.RawConfig = backend.RawConfig.Merge(rc)
}
// If we have extra config values, merge that
if len(opts.ConfigExtra) > 0 {
log.Printf(
"[DEBUG] command: adding extra backend config from CLI")
rc, err := config.NewRawConfig(opts.ConfigExtra)
if err != nil {
return nil, fmt.Errorf(
"Error adding extra configuration file for backend: %s", err)
}
// Merge in the configuration
backend.RawConfig = backend.RawConfig.Merge(rc)
}
// Validate the backend early. We have to do this before the normal
// config validation pass since backend loading happens earlier.
if errs := backend.Validate(); len(errs) > 0 {
return nil, multierror.Append(nil, errs...)
}
// Return the configuration which may or may not be set
return backend, nil
}
// backendConfigFile loads the extra configuration to merge with the
// backend configuration from an extra file if specified by
// BackendOpts.ConfigFile.
func (m *Meta) backendConfigFile(path string) (*config.RawConfig, error) {
// Read the file
d, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
// Parse it
hclRoot, err := hcl.Parse(string(d))
if err != nil {
return nil, err
}
// Decode it
var c map[string]interface{}
if err := hcl.DecodeObject(&c, hclRoot); err != nil {
return nil, err
}
return config.NewRawConfig(c)
}
// backendFromConfig returns the initialized (not configured) backend
// directly from the config/state..
//
// This function handles any edge cases around backend config loading. For
// example: legacy remote state, new config changes, backend type changes,
// etc.
//
// This function may query the user for input unless input is disabled, in
// which case this function will error.
func (m *Meta) backendFromConfig(opts *BackendOpts) (backend.Backend, error) {
// Get the local backend configuration.
c, err := m.backendConfig(opts)
if err != nil {
return nil, fmt.Errorf("Error loading backend config: %s", err)
}
// cHash defaults to zero unless c is set
var cHash uint64
if c != nil {
// We need to rehash to get the value since we may have merged the
// config with an extra ConfigFile. We don't do this when merging
// because we do want the ORIGINAL value on c so that we store
// that to not detect drift. This is covered in tests.
cHash = c.Rehash()
}
// Get the path to where we store a local cache of backend configuration
// if we're using a remote backend. This may not yet exist which means
// we haven't used a non-local backend before. That is okay.
statePath := filepath.Join(m.DataDir(), DefaultStateFilename)
sMgr := &state.LocalState{Path: statePath}
if err := sMgr.RefreshState(); err != nil {
return nil, fmt.Errorf("Error loading state: %s", err)
}
// Load the state, it must be non-nil for the tests below but can be empty
s := sMgr.State()
if s == nil {
log.Printf("[DEBUG] command: no data state file found for backend config")
s = terraform.NewState()
}
// if we want to force reconfiguration of the backend, we set the backend
// state to nil on this copy. This will direct us through the correct
// configuration path in the switch statement below.
if m.reconfigure {
s.Backend = nil
}
// Upon return, we want to set the state we're using in-memory so that
// we can access it for commands.
m.backendState = nil
defer func() {
if s := sMgr.State(); s != nil && !s.Backend.Empty() {
m.backendState = s.Backend
}
}()
// This giant switch statement covers all eight possible combinations
// of state settings between: configuring new backends, saved (previously-
// configured) backends, and legacy remote state.
switch {
// No configuration set at all. Pure local state.
case c == nil && s.Remote.Empty() && s.Backend.Empty():
return nil, nil
// We're unsetting a backend (moving from backend => local)
case c == nil && s.Remote.Empty() && !s.Backend.Empty():
if !opts.Init {
initReason := fmt.Sprintf(
"Unsetting the previously set backend %q",
s.Backend.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
return m.backend_c_r_S(c, sMgr, true)
// We have a legacy remote state configuration but no new backend config
case c == nil && !s.Remote.Empty() && s.Backend.Empty():
return m.backend_c_R_s(c, sMgr)
// We have a legacy remote state configuration simultaneously with a
// saved backend configuration while at the same time disabling backend
// configuration.
//
// This is a naturally impossible case: Terraform will never put you
// in this state, though it is theoretically possible through manual edits
case c == nil && !s.Remote.Empty() && !s.Backend.Empty():
if !opts.Init {
initReason := fmt.Sprintf(
"Unsetting the previously set backend %q",
s.Backend.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
return m.backend_c_R_S(c, sMgr)
// Configuring a backend for the first time.
case c != nil && s.Remote.Empty() && s.Backend.Empty():
if !opts.Init {
initReason := fmt.Sprintf(
"Initial configuration of the requested backend %q",
c.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
return m.backend_C_r_s(c, sMgr)
// Potentially changing a backend configuration
case c != nil && s.Remote.Empty() && !s.Backend.Empty():
// If our configuration is the same, then we're just initializing
// a previously configured remote backend.
if !s.Backend.Empty() {
hash := s.Backend.Hash
// on init we need an updated hash containing any extra options
// that were added after merging.
if opts.Init {
hash = s.Backend.Rehash()
}
if hash == cHash {
return m.backend_C_r_S_unchanged(c, sMgr)
}
}
if !opts.Init {
initReason := fmt.Sprintf(
"Backend configuration changed for %q",
c.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
log.Printf(
"[WARN] command: backend config change! saved: %d, new: %d",
s.Backend.Hash, cHash)
return m.backend_C_r_S_changed(c, sMgr, true)
// Configuring a backend for the first time while having legacy
// remote state. This is very possible if a Terraform user configures
// a backend prior to ever running Terraform on an old state.
case c != nil && !s.Remote.Empty() && s.Backend.Empty():
if !opts.Init {
initReason := fmt.Sprintf(
"Initial configuration for backend %q",
c.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
return m.backend_C_R_s(c, sMgr)
// Configuring a backend with both a legacy remote state set
// and a pre-existing backend saved.
case c != nil && !s.Remote.Empty() && !s.Backend.Empty():
// If the hashes are the same, we have a legacy remote state with
// an unchanged stored backend state.
hash := s.Backend.Hash
if opts.Init {
hash = s.Backend.Rehash()
}
if hash == cHash {
if !opts.Init {
initReason := fmt.Sprintf(
"Legacy remote state found with configured backend %q",
c.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
return m.backend_C_R_S_unchanged(c, sMgr, true)
}
if !opts.Init {
initReason := fmt.Sprintf(
"Reconfiguring the backend %q",
c.Type)
m.backendInitRequired(initReason)
return nil, errBackendInitRequired
}
// We have change in all three
return m.backend_C_R_S_changed(c, sMgr)
default:
// This should be impossible since all state possibilties are
// tested above, but we need a default case anyways and we should
// protect against the scenario where a case is somehow removed.
return nil, fmt.Errorf(
"Unhandled backend configuration state. This is a bug. Please\n"+
"report this error with the following information.\n\n"+
"Config Nil: %v\n"+
"Saved Backend Empty: %v\n"+
"Legacy Remote Empty: %v\n",
c == nil, s.Backend.Empty(), s.Remote.Empty())
}
}
// backendFromPlan loads the backend from a given plan file.
func (m *Meta) backendFromPlan(opts *BackendOpts) (backend.Backend, error) {
// Precondition check
if opts.Plan == nil {
panic("plan should not be nil")
}
// We currently don't allow "-state" to be specified.
if m.statePath != "" {
return nil, fmt.Errorf(
"State path cannot be specified with a plan file. The plan itself contains\n" +
"the state to use. If you wish to change that, please create a new plan\n" +
"and specify the state path when creating the plan.")
}
planBackend := opts.Plan.Backend
planState := opts.Plan.State
if planState == nil {
// The state can be nil, we just have to make it empty for the logic
// in this function.
planState = terraform.NewState()
}
// Validation only for non-local plans
local := planState.Remote.Empty() && planBackend.Empty()
if !local {
// We currently don't allow "-state-out" to be specified.
if m.stateOutPath != "" {
return nil, fmt.Errorf(strings.TrimSpace(errBackendPlanStateFlag))
}
}
/*
// Determine the path where we'd be writing state
path := DefaultStateFilename
if !planState.Remote.Empty() || !planBackend.Empty() {
path = filepath.Join(m.DataDir(), DefaultStateFilename)
}
// If the path exists, then we need to verify we're writing the same
// state lineage. If the path doesn't exist that's okay.
_, err := os.Stat(path)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("Error checking state destination: %s", err)
}
if err == nil {
// The file exists, we need to read it and compare
if err := m.backendFromPlan_compareStates(state, path); err != nil {
return nil, err
}
}
*/
// If we have a stateOutPath, we must also specify it as the
// input path so we can check it properly. We restore it after this
// function exits.
original := m.statePath
m.statePath = m.stateOutPath
defer func() { m.statePath = original }()
var b backend.Backend
var err error
switch {
// No remote state at all, all local
case planState.Remote.Empty() && planBackend.Empty():
log.Printf("[INFO] command: initializing local backend from plan (not set)")
// Get the local backend
b, err = m.Backend(&BackendOpts{ForceLocal: true})
// New backend configuration set
case planState.Remote.Empty() && !planBackend.Empty():
log.Printf(
"[INFO] command: initializing backend from plan: %s",
planBackend.Type)
b, err = m.backendInitFromSaved(planBackend)
// Legacy remote state set
case !planState.Remote.Empty() && planBackend.Empty():
log.Printf(
"[INFO] command: initializing legacy remote backend from plan: %s",
planState.Remote.Type)
// Write our current state to an inmemory state just so that we
// have it in the format of state.State
inmem := &state.InmemState{}
inmem.WriteState(planState)
// Get the backend through the normal means of legacy state
b, err = m.backend_c_R_s(nil, inmem)
// Both set, this can't happen in a plan.
case !planState.Remote.Empty() && !planBackend.Empty():
return nil, fmt.Errorf(strings.TrimSpace(errBackendPlanBoth))
}
// If we had an error, return that
if err != nil {
return nil, err
}
env := m.Workspace()
// Get the state so we can determine the effect of using this plan
realMgr, err := b.State(env)
if err != nil {
return nil, fmt.Errorf("Error reading state: %s", err)
}
if m.stateLock {
lockCtx, cancel := context.WithTimeout(context.Background(), m.stateLockTimeout)
defer cancel()
// Lock the state if we can
lockInfo := state.NewLockInfo()
lockInfo.Operation = "backend from plan"
lockID, err := clistate.Lock(lockCtx, realMgr, lockInfo, m.Ui, m.Colorize())
if err != nil {
return nil, fmt.Errorf("Error locking state: %s", err)
}
defer clistate.Unlock(realMgr, lockID, m.Ui, m.Colorize())
}
if err := realMgr.RefreshState(); err != nil {
return nil, fmt.Errorf("Error reading state: %s", err)
}
real := realMgr.State()
if real != nil {
// If they're not the same lineage, don't allow this
if !real.SameLineage(planState) {
return nil, fmt.Errorf(strings.TrimSpace(errBackendPlanLineageDiff))
}
// Compare ages
comp, err := real.CompareAges(planState)
if err != nil {
return nil, fmt.Errorf("Error comparing state ages for safety: %s", err)
}
switch comp {
case terraform.StateAgeEqual:
// State ages are equal, this is perfect
case terraform.StateAgeReceiverOlder:
// Real state is somehow older, this is okay.
case terraform.StateAgeReceiverNewer:
// If we have an older serial it is a problem but if we have a
// differing serial but are still identical, just let it through.
if real.Equal(planState) {
log.Printf(
"[WARN] command: state in plan has older serial, but Equal is true")
break
}
// The real state is newer, this is not allowed.
return nil, fmt.Errorf(
strings.TrimSpace(errBackendPlanOlder),
planState.Serial, real.Serial)
}
}
// Write the state
newState := opts.Plan.State.DeepCopy()
if newState != nil {
newState.Remote = nil
newState.Backend = nil
}
// realMgr locked above
if err := realMgr.WriteState(newState); err != nil {
return nil, fmt.Errorf("Error writing state: %s", err)
}
if err := realMgr.PersistState(); err != nil {
return nil, fmt.Errorf("Error writing state: %s", err)
}
return b, nil
}
//-------------------------------------------------------------------
// Backend Config Scenarios
//
// The functions below cover handling all the various scenarios that
// can exist when loading a backend. They are named in the format of
// "backend_C_R_S" where C, R, S may be upper or lowercase. Lowercase
// means it is false, uppercase means it is true. The full set of eight
// possible cases is handled.
//
// The fields are:
//
// * C - Backend configuration is set and changed in TF files
// * R - Legacy remote state is set
// * S - Backend configuration is set in the state
//
//-------------------------------------------------------------------
// Unconfiguring a backend (moving from backend => local).
func (m *Meta) backend_c_r_S(
c *config.Backend, sMgr state.State, output bool) (backend.Backend, error) {
s := sMgr.State()
// Get the backend type for output
backendType := s.Backend.Type
copy := m.forceInitCopy
if !copy {
var err error
// Confirm with the user that the copy should occur
copy, err = m.confirm(&terraform.InputOpts{
Id: "backend-migrate-to-local",
Query: fmt.Sprintf("Do you want to copy the state from %q?", s.Backend.Type),
Description: fmt.Sprintf(
strings.TrimSpace(inputBackendMigrateLocal), s.Backend.Type),
})
if err != nil {
return nil, fmt.Errorf(
"Error asking for state copy action: %s", err)
}
}
// If we're copying, perform the migration
if copy {
// Grab a purely local backend to get the local state if it exists
localB, err := m.Backend(&BackendOpts{ForceLocal: true})
if err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendLocalRead), err)
}
// Initialize the configured backend
b, err := m.backend_C_r_S_unchanged(c, sMgr)
if err != nil {
return nil, fmt.Errorf(
strings.TrimSpace(errBackendSavedUnsetConfig), s.Backend.Type, err)
}
// Perform the migration
err = m.backendMigrateState(&backendMigrateOpts{
OneType: s.Backend.Type,
TwoType: "local",
One: b,
Two: localB,
})
if err != nil {
return nil, err
}
}
// Remove the stored metadata
s.Backend = nil
if err := sMgr.WriteState(s); err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendClearSaved), err)
}
if err := sMgr.PersistState(); err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendClearSaved), err)
}
if output {
m.Ui.Output(m.Colorize().Color(fmt.Sprintf(
"[reset][green]\n\n"+
strings.TrimSpace(successBackendUnset), backendType)))
}
// Return no backend
return nil, nil
}
// Legacy remote state
func (m *Meta) backend_c_R_s(
c *config.Backend, sMgr state.State) (backend.Backend, error) {
s := sMgr.State()
// Warn the user
m.Ui.Warn(strings.TrimSpace(warnBackendLegacy) + "\n")
// We need to convert the config to map[string]interface{} since that
// is what the backends expect.
var configMap map[string]interface{}
if err := mapstructure.Decode(s.Remote.Config, &configMap); err != nil {
return nil, fmt.Errorf("Error configuring remote state: %s", err)
}
// Create the config
rawC, err := config.NewRawConfig(configMap)
if err != nil {
return nil, fmt.Errorf("Error configuring remote state: %s", err)
}
config := terraform.NewResourceConfig(rawC)
// Get the backend
f := backendinit.Backend(s.Remote.Type)
if f == nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendLegacyUnknown), s.Remote.Type)
}
b := f()
// Configure
if err := b.Configure(config); err != nil {
return nil, fmt.Errorf(errBackendLegacyConfig, err)
}
return b, nil
}
// Unsetting backend, saved backend, legacy remote state
func (m *Meta) backend_c_R_S(
c *config.Backend, sMgr state.State) (backend.Backend, error) {
// Notify the user
m.Ui.Output(m.Colorize().Color(fmt.Sprintf(
"[reset]%s\n\n",
strings.TrimSpace(outputBackendUnsetWithLegacy))))
// Get the backend type for later
backendType := sMgr.State().Backend.Type
// First, perform the configured => local tranasition
if _, err := m.backend_c_r_S(c, sMgr, false); err != nil {
return nil, err
}
// Grab a purely local backend
localB, err := m.Backend(&BackendOpts{ForceLocal: true})
if err != nil {
return nil, fmt.Errorf(errBackendLocalRead, err)
}
// Grab the state
s := sMgr.State()
// Ask the user if they want to migrate their existing remote state
copy := m.forceInitCopy
if !copy {
copy, err = m.confirm(&terraform.InputOpts{
Id: "backend-migrate-to-new",
Query: fmt.Sprintf(
"Do you want to copy the legacy remote state from %q?",
s.Remote.Type),
Description: strings.TrimSpace(inputBackendMigrateLegacyLocal),
})
if err != nil {
return nil, fmt.Errorf(
"Error asking for state copy action: %s", err)
}
}
// If the user wants a copy, copy!
if copy {
// Initialize the legacy backend
oldB, err := m.backendInitFromLegacy(s.Remote)
if err != nil {
return nil, err
}
// Perform the migration
err = m.backendMigrateState(&backendMigrateOpts{
OneType: s.Remote.Type,
TwoType: "local",
One: oldB,
Two: localB,
})
if err != nil {
return nil, err
}
}
// Unset the remote state
s = sMgr.State()
if s == nil {
s = terraform.NewState()
}
s.Remote = nil
if err := sMgr.WriteState(s); err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendClearLegacy), err)
}
if err := sMgr.PersistState(); err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendClearLegacy), err)
}
m.Ui.Output(m.Colorize().Color(fmt.Sprintf(
"[reset][green]\n\n"+
strings.TrimSpace(successBackendUnset), backendType)))
return nil, nil
}
// Configuring a backend for the first time with legacy remote state.
func (m *Meta) backend_C_R_s(
c *config.Backend, sMgr state.State) (backend.Backend, error) {
// Notify the user
m.Ui.Output(m.Colorize().Color(fmt.Sprintf(
"[reset]%s\n\n",
strings.TrimSpace(outputBackendConfigureWithLegacy))))
// First, configure the new backend
b, err := m.backendInitFromConfig(c)
if err != nil {
return nil, err
}
// Next, save the new configuration. This will not overwrite our
// legacy remote state. We'll handle that after.
s := sMgr.State()
if s == nil {
s = terraform.NewState()
}
s.Backend = &terraform.BackendState{
Type: c.Type,
Config: c.RawConfig.Raw,
Hash: c.Hash,
}
if err := sMgr.WriteState(s); err != nil {
return nil, fmt.Errorf(errBackendWriteSaved, err)
}
if err := sMgr.PersistState(); err != nil {
return nil, fmt.Errorf(errBackendWriteSaved, err)
}
// I don't know how this is possible but if we don't have remote
// state config anymore somehow, just return the backend. This
// shouldn't be possible, though.
if s.Remote.Empty() {
return b, nil
}
// Finally, ask the user if they want to copy the state from
// their old remote state location.
copy := m.forceInitCopy
if !copy {
copy, err = m.confirm(&terraform.InputOpts{
Id: "backend-migrate-to-new",
Query: fmt.Sprintf(
"Do you want to copy the legacy remote state from %q?",
s.Remote.Type),
Description: strings.TrimSpace(inputBackendMigrateLegacy),
})
if err != nil {
return nil, fmt.Errorf(
"Error asking for state copy action: %s", err)
}
}
// If the user wants a copy, copy!
if copy {
// Initialize the legacy backend
oldB, err := m.backendInitFromLegacy(s.Remote)
if err != nil {
return nil, err
}
// Perform the migration
err = m.backendMigrateState(&backendMigrateOpts{
OneType: s.Remote.Type,
TwoType: c.Type,
One: oldB,
Two: b,
})
if err != nil {
return nil, err
}
}
// Unset the remote state
s = sMgr.State()
if s == nil {
s = terraform.NewState()
}
s.Remote = nil
if err := sMgr.WriteState(s); err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendClearLegacy), err)
}
if err := sMgr.PersistState(); err != nil {
return nil, fmt.Errorf(strings.TrimSpace(errBackendClearLegacy), err)
}
m.Ui.Output(m.Colorize().Color(fmt.Sprintf(
"[reset][green]\n"+strings.TrimSpace(successBackendSet), s.Backend.Type)))
return b, nil
}
// Configuring a backend for the first time.
func (m *Meta) backend_C_r_s(
c *config.Backend, sMgr state.State) (backend.Backend, error) {
// Get the backend
b, err := m.backendInitFromConfig(c)
if err != nil {
return nil, err
}
// Grab a purely local backend to get the local state if it exists
localB, err := m.Backend(&BackendOpts{ForceLocal: true})
if err != nil {
return nil, fmt.Errorf(errBackendLocalRead, err)
}
env := m.Workspace()
localState, err := localB.State(env)
if err != nil {
return nil, fmt.Errorf(errBackendLocalRead, err)
}
if err := localState.RefreshState(); err != nil {
return nil, fmt.Errorf(errBackendLocalRead, err)
}
// If the local state is not empty, we need to potentially do a
// state migration to the new backend (with user permission), unless the
// destination is also "local"
if localS := localState.State(); !localS.Empty() {
// Perform the migration
err = m.backendMigrateState(&backendMigrateOpts{
OneType: "local",
TwoType: c.Type,
One: localB,
Two: b,
})
if err != nil {
return nil, err
}
// we usually remove the local state after migration to prevent
// confusion, but adding a default local backend block to the config
// can get us here too. Don't delete our state if the old and new paths
// are the same.
erase := true
if newLocalB, ok := b.(*backendlocal.Local); ok {