command/apply: -refresh flag

This commit is contained in:
Mitchell Hashimoto 2014-07-26 17:50:13 -07:00
parent ef6fba754d
commit 795142c43c
2 changed files with 66 additions and 0 deletions

View File

@ -19,11 +19,13 @@ type ApplyCommand struct {
}
func (c *ApplyCommand) Run(args []string) int {
var refresh bool
var statePath, stateOutPath string
args = c.Meta.process(args)
cmdFlags := c.Meta.flagSet("apply")
cmdFlags.BoolVar(&refresh, "refresh", true, "refresh")
cmdFlags.StringVar(&statePath, "state", DefaultStateFilename, "path")
cmdFlags.StringVar(&stateOutPath, "state-out", "", "path")
cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
@ -69,6 +71,15 @@ func (c *ApplyCommand) Run(args []string) int {
// Plan if we haven't already
if !planned {
if refresh {
c.Ui.Output("Refreshing Terraform state prior to plan...\n")
if _, err := ctx.Refresh(); err != nil {
c.Ui.Error(fmt.Sprintf("Error refreshing state: %s", err))
return 1
}
c.Ui.Output("")
}
if _, err := ctx.Plan(nil); err != nil {
c.Ui.Error(fmt.Sprintf(
"Error creating plan: %s", err))
@ -194,6 +205,9 @@ Options:
-no-color If specified, output won't contain any color.
-refresh=true Update state prior to checking for differences. This
has no effect if a plan file is given to apply.
-state=path Path to read and save state (unless state-out
is specified). Defaults to "terraform.tfstate".

View File

@ -308,6 +308,58 @@ func TestApply_planVars(t *testing.T) {
}
}
func TestApply_refresh(t *testing.T) {
originalState := &terraform.State{
Resources: map[string]*terraform.ResourceState{
"test_instance.foo": &terraform.ResourceState{
ID: "bar",
Type: "test_instance",
},
},
}
statePath := testStateFile(t, originalState)
p := testProvider()
ui := new(cli.MockUi)
c := &ApplyCommand{
Meta: Meta{
ContextOpts: testCtxConfig(p),
Ui: ui,
},
}
args := []string{
"-state", statePath,
testFixturePath("apply"),
}
if code := c.Run(args); code != 0 {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
}
if !p.RefreshCalled {
t.Fatal("should call refresh")
}
if _, err := os.Stat(statePath); err != nil {
t.Fatalf("err: %s", err)
}
f, err := os.Open(statePath)
if err != nil {
t.Fatalf("err: %s", err)
}
defer f.Close()
state, err := terraform.ReadState(f)
if err != nil {
t.Fatalf("err: %s", err)
}
if state == nil {
t.Fatal("state should not be nil")
}
}
func TestApply_shutdown(t *testing.T) {
stopped := false
stopCh := make(chan struct{})