diff --git a/command/command_test.go b/command/command_test.go index efcefd55b..074db94b8 100644 --- a/command/command_test.go +++ b/command/command_test.go @@ -42,6 +42,21 @@ func testPlanFile(t *testing.T, plan *terraform.Plan) string { return path } +func testReadPlan(t *testing.T, path string) *terraform.Plan { + f, err := os.Open(path) + if err != nil { + t.Fatalf("err: %s", err) + } + defer f.Close() + + p, err := terraform.ReadPlan(f) + if err != nil { + t.Fatalf("err: %s", err) + } + + return p +} + func testStateFile(t *testing.T, s *terraform.State) string { path := testTempFile(t) diff --git a/command/plan.go b/command/plan.go index 3085e1ae9..7967e330f 100644 --- a/command/plan.go +++ b/command/plan.go @@ -20,10 +20,11 @@ type PlanCommand struct { } func (c *PlanCommand) Run(args []string) int { - var refresh bool + var destroy, refresh bool var outPath, statePath string cmdFlags := flag.NewFlagSet("plan", flag.ContinueOnError) + cmdFlags.BoolVar(&destroy, "destroy", false, "destroy") cmdFlags.BoolVar(&refresh, "refresh", true, "refresh") cmdFlags.StringVar(&outPath, "out", "", "path") cmdFlags.StringVar(&statePath, "state", "", "path") @@ -80,8 +81,9 @@ func (c *PlanCommand) Run(args []string) int { } plan, err := tf.Plan(&terraform.PlanOpts{ - Config: b, - State: state, + Config: b, + Destroy: destroy, + State: state, }) if err != nil { c.Ui.Error(fmt.Sprintf("Error running plan: %s", err)) diff --git a/command/plan_test.go b/command/plan_test.go index ff2f77dd0..4ef71cb2e 100644 --- a/command/plan_test.go +++ b/command/plan_test.go @@ -10,6 +10,43 @@ import ( "github.com/mitchellh/cli" ) +func TestPlan_destroy(t *testing.T) { + originalState := &terraform.State{ + Resources: map[string]*terraform.ResourceState{ + "test_instance.foo": &terraform.ResourceState{ + ID: "bar", + Type: "test_instance", + }, + }, + } + + outPath := testTempFile(t) + statePath := testStateFile(t, originalState) + + p := testProvider() + ui := new(cli.MockUi) + c := &PlanCommand{ + TFConfig: testTFConfig(p), + Ui: ui, + } + + args := []string{ + "-destroy", + "-out", outPath, + "-state", statePath, + testFixturePath("plan"), + } + if code := c.Run(args); code != 0 { + t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) + } + + plan := testReadPlan(t, outPath) + for _, r := range plan.Diff.Resources { + if !r.Destroy { + t.Fatalf("bad: %#v", r) + } + } +} func TestPlan_noState(t *testing.T) { p := testProvider() ui := new(cli.MockUi) diff --git a/terraform/terraform.go b/terraform/terraform.go index 92e3a1f70..f060bf0b5 100644 --- a/terraform/terraform.go +++ b/terraform/terraform.go @@ -253,6 +253,8 @@ func (t *Terraform) planWalkFn(result *Plan, opts *PlanOpts) depgraph.WalkFunc { if r.State.ID != "" { log.Printf("[DEBUG] %s: Making for destroy", r.Id) diff = &ResourceDiff{Destroy: true} + } else { + log.Printf("[DEBUG] %s: Not marking for destroy, no ID", r.Id) } } else if r.Config == nil { log.Printf("[DEBUG] %s: Orphan, marking for destroy", r.Id)