Skip to content

Commit

Permalink
kms: Treat keys in PendingDeletion state as deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
radeksimko authored and Radek Simko committed Feb 26, 2016
1 parent 2a7e5c9 commit ca2d6ab
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
36 changes: 35 additions & 1 deletion builtin/providers/aws/resource_aws_kms_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ func resourceAwsKmsKeyRead(d *schema.ResourceData, meta interface{}) error {
}
metadata := resp.KeyMetadata

if *metadata.KeyState == "PendingDeletion" {
log.Printf("[WARN] Removing KMS key %s because it's already gone", d.Id())
d.SetId("")
return nil
}

d.SetId(*metadata.KeyId)

d.Set("arn", metadata.Arn)
Expand Down Expand Up @@ -337,7 +343,35 @@ func resourceAwsKmsKeyDelete(d *schema.ResourceData, meta interface{}) error {
return err
}

log.Printf("[DEBUG] KMS Key: %s deactivated.", keyId)
// Wait for propagation since KMS is eventually consistent
wait := resource.StateChangeConf{
Pending: []string{"Enabled", "Disabled"},
Target: []string{"PendingDeletion"},
Timeout: 5 * time.Minute,
MinTimeout: 2 * time.Second,
ContinuousTargetOccurence: 5,
Refresh: func() (interface{}, string, error) {
log.Printf("[DEBUG] Checking if KMS key %s state is PendingDeletion", keyId)
resp, err := conn.DescribeKey(&kms.DescribeKeyInput{
KeyId: aws.String(keyId),
})
if err != nil {
return resp, "Failed", err
}

metadata := *resp.KeyMetadata
log.Printf("[DEBUG] KMS key %s state is %s, retrying", keyId, *metadata.KeyState)

return resp, *metadata.KeyState, nil
},
}

_, err = wait.WaitForState()
if err != nil {
return fmt.Errorf("Failed deactivating KMS key %s: %s", keyId, err)
}

log.Printf("[DEBUG] KMS Key %s deactivated.", keyId)
d.SetId("")
return nil
}
10 changes: 7 additions & 3 deletions builtin/providers/aws/resource_aws_kms_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,15 @@ func testAccCheckAWSKmsKeyDestroy(s *terraform.State) error {
KeyId: aws.String(rs.Primary.ID),
})

if err == nil {
return fmt.Errorf("KMS key still exists:\n%#v", out.KeyMetadata)
if err != nil {
return err
}

if *out.KeyMetadata.KeyState == "PendingDeletion" {
return nil
}

return err
return fmt.Errorf("KMS key still exists:\n%#v", out.KeyMetadata)
}

return nil
Expand Down

0 comments on commit ca2d6ab

Please sign in to comment.