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