forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_meta.go
104 lines (87 loc) · 2.52 KB
/
state_meta.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
package command
import (
"errors"
"fmt"
"time"
backendLocal "github.com/hashicorp/terraform/backend/local"
"github.com/hashicorp/terraform/state"
"github.com/hashicorp/terraform/terraform"
)
// StateMeta is the meta struct that should be embedded in state subcommands.
type StateMeta struct {
Meta
}
// State returns the state for this meta. This gets the appropriate state from
// the backend, but changes the way that backups are done. This configures
// backups to be timestamped rather than just the original state path plus a
// backup path.
func (c *StateMeta) State() (state.State, error) {
var realState state.State
backupPath := c.backupPath
stateOutPath := c.statePath
// use the specified state
if c.statePath != "" {
realState = &state.LocalState{
Path: c.statePath,
}
} else {
// Load the backend
b, err := c.Backend(nil)
if err != nil {
return nil, err
}
env := c.Workspace()
// Get the state
s, err := b.State(env)
if err != nil {
return nil, err
}
// Get a local backend
localRaw, err := c.Backend(&BackendOpts{ForceLocal: true})
if err != nil {
// This should never fail
panic(err)
}
localB := localRaw.(*backendLocal.Local)
_, stateOutPath, _ = localB.StatePaths(env)
if err != nil {
return nil, err
}
realState = s
}
// We always backup state commands, so set the back if none was specified
// (the default is "-", but some tests bypass the flag parsing).
if backupPath == "-" || backupPath == "" {
// Determine the backup path. stateOutPath is set to the resulting
// file where state is written (cached in the case of remote state)
backupPath = fmt.Sprintf(
"%s.%d%s",
stateOutPath,
time.Now().UTC().Unix(),
DefaultBackupExtension)
}
// Wrap it for backups
realState = &state.BackupState{
Real: realState,
Path: backupPath,
}
return realState, nil
}
// filterInstance filters a single instance out of filter results.
func (c *StateMeta) filterInstance(rs []*terraform.StateFilterResult) (*terraform.StateFilterResult, error) {
var result *terraform.StateFilterResult
for _, r := range rs {
if _, ok := r.Value.(*terraform.InstanceState); !ok {
continue
}
if result != nil {
return nil, errors.New(errStateMultiple)
}
result = r
}
return result, nil
}
const errStateMultiple = `Multiple instances found for the given pattern!
This command requires that the pattern match exactly one instance
of a resource. To view the matched instances, use "terraform state list".
Please modify the pattern to match only a single instance.`