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