@@ -3,6 +3,7 @@ package command
33import (
44 "flag"
55 "fmt"
6+ "os"
67 "strings"
78
89 "github.com/hashicorp/terraform/config"
@@ -18,7 +19,11 @@ type ApplyCommand struct {
1819}
1920
2021func (c * ApplyCommand ) Run (args []string ) int {
22+ var statePath , stateOutPath string
23+
2124 cmdFlags := flag .NewFlagSet ("apply" , flag .ContinueOnError )
25+ cmdFlags .StringVar (& statePath , "state" , "terraform.tfstate" , "path" )
26+ cmdFlags .StringVar (& stateOutPath , "state-out" , "" , "path" )
2227 cmdFlags .Usage = func () { c .Ui .Error (c .Help ()) }
2328 if err := cmdFlags .Parse (args ); err != nil {
2429 return 1
@@ -33,6 +38,16 @@ func (c *ApplyCommand) Run(args []string) int {
3338 return 1
3439 }
3540
41+ // TODO: if state, but not exist, -init required
42+
43+ if statePath == "" {
44+ c .Ui .Error ("-state cannot be blank" )
45+ return 1
46+ }
47+ if stateOutPath == "" {
48+ stateOutPath = statePath
49+ }
50+
3651 b , err := config .Load (args [0 ])
3752 if err != nil {
3853 c .Ui .Error (fmt .Sprintf ("Error loading blueprint: %s" , err ))
@@ -60,6 +75,19 @@ func (c *ApplyCommand) Run(args []string) int {
6075 return 1
6176 }
6277
78+ // Write state out to the file
79+ f , err := os .Create (stateOutPath )
80+ if err != nil {
81+ c .Ui .Error (fmt .Sprintf ("Failed to save state: %s" , err ))
82+ return 1
83+ }
84+ defer f .Close ()
85+
86+ if err := terraform .WriteState (state , f ); err != nil {
87+ c .Ui .Error (fmt .Sprintf ("Failed to save state: %s" , err ))
88+ return 1
89+ }
90+
6391 c .Ui .Output (strings .TrimSpace (state .String ()))
6492
6593 return 0
@@ -74,8 +102,15 @@ Usage: terraform apply [terraform.tf]
74102
75103Options:
76104
77- -init If specified, it is okay to build brand new infrastructure
78- (with no state file specified).
105+ -init If specified, it is okay to build brand new
106+ infrastructure (with no state file specified).
107+
108+ -state=terraform.tfstate Path to the state file to build off of. This file
109+ will also be written to with updated state unless
110+ -state-out is specified.
111+
112+ -state-out=file.tfstate Path to save the new state. If not specified, the
113+ -state value will be used.
79114
80115`
81116 return strings .TrimSpace (helpText )
0 commit comments