github.com/profects/terraform@v0.9.0-beta1.0.20170227135739-92d4809db30d/command/state_meta.go (about) 1 package command 2 3 import ( 4 "errors" 5 "fmt" 6 "time" 7 8 backendlocal "github.com/hashicorp/terraform/backend/local" 9 "github.com/hashicorp/terraform/state" 10 "github.com/hashicorp/terraform/terraform" 11 ) 12 13 // StateMeta is the meta struct that should be embedded in state subcommands. 14 type StateMeta struct{} 15 16 // State returns the state for this meta. This is different then Meta.State 17 // in the way that backups are done. This configures backups to be timestamped 18 // rather than just the original state path plus a backup path. 19 func (c *StateMeta) State(m *Meta) (state.State, error) { 20 // Load the backend 21 b, err := m.Backend(nil) 22 if err != nil { 23 return nil, err 24 } 25 26 // Get the state 27 s, err := b.State() 28 if err != nil { 29 return nil, err 30 } 31 32 // Get a local backend 33 localRaw, err := m.Backend(&BackendOpts{ForceLocal: true}) 34 if err != nil { 35 // This should never fail 36 panic(err) 37 } 38 localB := localRaw.(*backendlocal.Local) 39 40 // Determine the backup path. stateOutPath is set to the resulting 41 // file where state is written (cached in the case of remote state) 42 backupPath := fmt.Sprintf( 43 "%s.%d%s", 44 localB.StateOutPath, 45 time.Now().UTC().Unix(), 46 DefaultBackupExtension) 47 48 // Wrap it for backups 49 s = &state.BackupState{ 50 Real: s, 51 Path: backupPath, 52 } 53 54 return s, nil 55 } 56 57 // filterInstance filters a single instance out of filter results. 58 func (c *StateMeta) filterInstance(rs []*terraform.StateFilterResult) (*terraform.StateFilterResult, error) { 59 var result *terraform.StateFilterResult 60 for _, r := range rs { 61 if _, ok := r.Value.(*terraform.InstanceState); !ok { 62 continue 63 } 64 65 if result != nil { 66 return nil, errors.New(errStateMultiple) 67 } 68 69 result = r 70 } 71 72 return result, nil 73 } 74 75 const errStateMultiple = `Multiple instances found for the given pattern! 76 77 This command requires that the pattern match exactly one instance 78 of a resource. To view the matched instances, use "terraform state list". 79 Please modify the pattern to match only a single instance.`