aws: kms_key - Iterate over all aliases (not just 50)

This commit is contained in:
Radek Simko 2015-11-14 20:48:00 +00:00 committed by Radek Simko
parent ff2d040d28
commit 347913a3be
2 changed files with 43 additions and 16 deletions

View File

@ -67,21 +67,21 @@ func resourceAwsKmsAliasRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).kmsconn conn := meta.(*AWSClient).kmsconn
name := d.Get("name").(string) name := d.Get("name").(string)
req := &kms.ListAliasesInput{} alias, err := findKmsAliasByName(conn, name, nil)
resp, err := conn.ListAliases(req)
if err != nil { if err != nil {
return err return err
} }
for _, e := range resp.Aliases { if alias == nil {
if name == *e.AliasName { log.Printf("[DEBUG] Removing KMS Alias %q as it's already gone", name)
d.Set("arn", e.AliasArn) d.SetId("")
d.Set("target_key_id", e.TargetKeyId)
return nil return nil
} }
}
log.Printf("[DEBUG] KMS alias read: alias not found") log.Printf("[DEBUG] Found KMS Alias: %s", alias)
d.SetId("")
d.Set("arn", alias.AliasArn)
d.Set("target_key_id", alias.TargetKeyId)
return nil return nil
} }
@ -128,3 +128,33 @@ func resourceAwsKmsAliasDelete(d *schema.ResourceData, meta interface{}) error {
d.SetId("") d.SetId("")
return nil return nil
} }
// API by default limits results to 50 aliases
// This is how we make sure we won't miss any alias
// See http://docs.aws.amazon.com/kms/latest/APIReference/API_ListAliases.html
func findKmsAliasByName(conn *kms.KMS, name string, marker *string) (*kms.AliasListEntry, error) {
req := kms.ListAliasesInput{
Limit: aws.Int64(int64(100)),
}
if marker != nil {
req.Marker = marker
}
log.Printf("[DEBUG] Listing KMS aliases: %s", req)
resp, err := conn.ListAliases(&req)
if err != nil {
return nil, err
}
for _, entry := range resp.Aliases {
if *entry.AliasName == name {
return entry, nil
}
}
if *resp.Truncated {
log.Printf("[DEBUG] KMS alias list is truncated, listing more via %s", *resp.NextMarker)
return findKmsAliasByName(conn, name, resp.NextMarker)
}
return nil, nil
}

View File

@ -5,7 +5,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
) )
@ -57,14 +56,12 @@ func testAccCheckAWSKmsAliasDestroy(s *terraform.State) error {
continue continue
} }
resp, err := conn.ListAliases(&kms.ListAliasesInput{}) entry, err := findKmsAliasByName(conn, rs.Primary.ID, nil)
if err != nil { if err != nil {
return err return err
} }
for _, e := range resp.Aliases { if entry != nil {
if *e.AliasName == rs.Primary.ID { return fmt.Errorf("KMS alias still exists:\n%#v", entry)
return fmt.Errorf("KMS alias still exists:\n%#v", e)
}
} }
return nil return nil