github.com/ggriffiths/terraform@v0.9.0-beta1.0.20170222213024-79c4935604cb/backend/local/backend_refresh.go (about) 1 package local 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 8 "github.com/hashicorp/errwrap" 9 "github.com/hashicorp/go-multierror" 10 "github.com/hashicorp/terraform/backend" 11 clistate "github.com/hashicorp/terraform/command/state" 12 "github.com/hashicorp/terraform/state" 13 ) 14 15 func (b *Local) opRefresh( 16 ctx context.Context, 17 op *backend.Operation, 18 runningOp *backend.RunningOperation) { 19 // Check if our state exists if we're performing a refresh operation. We 20 // only do this if we're managing state with this backend. 21 if b.Backend == nil { 22 if _, err := os.Stat(b.StatePath); err != nil { 23 if os.IsNotExist(err) { 24 runningOp.Err = fmt.Errorf( 25 "The Terraform state file for your infrastructure does not\n"+ 26 "exist. The 'refresh' command only works and only makes sense\n"+ 27 "when there is existing state that Terraform is managing. Please\n"+ 28 "double-check the value given below and try again. If you\n"+ 29 "haven't created infrastructure with Terraform yet, use the\n"+ 30 "'terraform apply' command.\n\n"+ 31 "Path: %s", 32 b.StatePath) 33 return 34 } 35 36 runningOp.Err = fmt.Errorf( 37 "There was an error reading the Terraform state that is needed\n"+ 38 "for refreshing. The path and error are shown below.\n\n"+ 39 "Path: %s\n\nError: %s", 40 b.StatePath, err) 41 return 42 } 43 } 44 45 // Get our context 46 tfCtx, opState, err := b.context(op) 47 if err != nil { 48 runningOp.Err = err 49 return 50 } 51 52 if op.LockState { 53 lockInfo := state.NewLockInfo() 54 lockInfo.Operation = op.Type.String() 55 lockID, err := clistate.Lock(opState, lockInfo, b.CLI, b.Colorize()) 56 if err != nil { 57 runningOp.Err = errwrap.Wrapf("Error locking state: {{err}}", err) 58 return 59 } 60 61 defer func() { 62 if err := clistate.Unlock(opState, lockID, b.CLI, b.Colorize()); err != nil { 63 runningOp.Err = multierror.Append(runningOp.Err, err) 64 } 65 }() 66 } 67 68 // Set our state 69 runningOp.State = opState.State() 70 71 // Perform operation and write the resulting state to the running op 72 newState, err := tfCtx.Refresh() 73 runningOp.State = newState 74 if err != nil { 75 runningOp.Err = errwrap.Wrapf("Error refreshing state: {{err}}", err) 76 return 77 } 78 79 // Write and persist the state 80 if err := opState.WriteState(newState); err != nil { 81 runningOp.Err = errwrap.Wrapf("Error writing state: {{err}}", err) 82 return 83 } 84 if err := opState.PersistState(); err != nil { 85 runningOp.Err = errwrap.Wrapf("Error saving state: {{err}}", err) 86 return 87 } 88 }