From f06a6224c93463961d2eaa2cc5f313340f95c1f7 Mon Sep 17 00:00:00 2001 From: kterada0509 Date: Tue, 25 Dec 2018 18:46:53 +0900 Subject: [PATCH] Fix to not return err when instance is already terminated --- aws/resource_aws_instance.go | 7 ++++++ aws/resource_aws_instance_test.go | 37 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/aws/resource_aws_instance.go b/aws/resource_aws_instance.go index 1076494d30d..9ae7e3b1d9e 100644 --- a/aws/resource_aws_instance.go +++ b/aws/resource_aws_instance.go @@ -1925,9 +1925,16 @@ func awsTerminateInstance(conn *ec2.EC2, id string, timeout time.Duration) error InstanceIds: []*string{aws.String(id)}, } if _, err := conn.TerminateInstances(req); err != nil { + if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" { + return nil + } return fmt.Errorf("Error terminating instance: %s", err) } + return waitForInstanceDeletion(conn, id, timeout) +} + +func waitForInstanceDeletion(conn *ec2.EC2, id string, timeout time.Duration) error { log.Printf("[DEBUG] Waiting for instance (%s) to become terminated", id) stateConf := &resource.StateChangeConf{ diff --git a/aws/resource_aws_instance_test.go b/aws/resource_aws_instance_test.go index f6fad820400..4225d30798a 100644 --- a/aws/resource_aws_instance_test.go +++ b/aws/resource_aws_instance_test.go @@ -1942,6 +1942,27 @@ func TestAccAWSInstance_creditSpecification_unlimitedCpuCredits_t2Tot3Taint(t *t }) } +func TestAccAWSInstance_disappears(t *testing.T) { + var conf ec2.Instance + rInt := acctest.RandInt() + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists("aws_instance.foo", &conf), + testAccCheckInstanceDisappears(&conf), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSInstance_UserData_EmptyStringToUnspecified(t *testing.T) { var instance ec2.Instance rInt := acctest.RandInt() @@ -2075,6 +2096,22 @@ func testAccCheckInstanceExistsWithProvider(n string, i *ec2.Instance, providerF } } +func testAccCheckInstanceDisappears(conf *ec2.Instance) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + params := &ec2.TerminateInstancesInput{ + InstanceIds: []*string{conf.InstanceId}, + } + + if _, err := conn.TerminateInstances(params); err != nil { + return err + } + + return waitForInstanceDeletion(conn, *conf.InstanceId, 10*time.Minute) + } +} + func TestInstanceTenancySchema(t *testing.T) { actualSchema := resourceAwsInstance().Schema["tenancy"] expectedSchema := &schema.Schema{