Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tech debt: Reduce tags boilerplate code - Plugin SDK resources kms (Phase 3c) #30590

Merged
merged 2 commits into from
Apr 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 11 additions & 31 deletions internal/service/kms/external_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ import (
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
"github.com/hashicorp/terraform-provider-aws/names"
)

// @SDKResource("aws_kms_external_key")
// @SDKResource("aws_kms_external_key", name="External Key")
// @Tags(identifierAttribute="id")
func ResourceExternalKey() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceExternalKeyCreate,
Expand Down Expand Up @@ -104,8 +106,8 @@ func ResourceExternalKey() *schema.Resource {
return json
},
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
"valid_to": {
Type: schema.TypeString,
Optional: true,
Expand All @@ -118,13 +120,12 @@ func ResourceExternalKey() *schema.Resource {
func resourceExternalKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).KMSConn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(ctx, d.Get("tags").(map[string]interface{})))

input := &kms.CreateKeyInput{
BypassPolicyLockoutSafetyCheck: aws.Bool(d.Get("bypass_policy_lockout_safety_check").(bool)),
KeyUsage: aws.String(kms.KeyUsageTypeEncryptDecrypt),
Origin: aws.String(kms.OriginTypeExternal),
Tags: GetTagsIn(ctx),
}

if v, ok := d.GetOk("description"); ok {
Expand All @@ -144,24 +145,20 @@ func resourceExternalKeyCreate(ctx context.Context, d *schema.ResourceData, meta
input.Policy = aws.String(p)
}

if len(tags) > 0 {
input.Tags = Tags(tags.IgnoreAWS())
}

// AWS requires any principal in the policy to exist before the key is created.
// The KMS service's awareness of principals is limited by "eventual consistency".
// KMS will report this error until it can validate the policy itself.
// They acknowledge this here:
// http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html
outputRaw, err := WaitIAMPropagation(ctx, func() (interface{}, error) {
output, err := WaitIAMPropagation(ctx, func() (*kms.CreateKeyOutput, error) {
return conn.CreateKeyWithContext(ctx, input)
})

if err != nil {
return sdkdiag.AppendErrorf(diags, "creating KMS External Key: %s", err)
}

d.SetId(aws.StringValue(outputRaw.(*kms.CreateKeyOutput).KeyMetadata.KeyId))
d.SetId(aws.StringValue(output.KeyMetadata.KeyId))

if v, ok := d.GetOk("key_material_base64"); ok {
validTo := d.Get("valid_to").(string)
Expand Down Expand Up @@ -194,7 +191,7 @@ func resourceExternalKeyCreate(ctx context.Context, d *schema.ResourceData, meta
}
}

if len(tags) > 0 {
if tags := KeyValueTags(ctx, GetTagsIn(ctx)); len(tags) > 0 {
if err := WaitTagsPropagated(ctx, conn, d.Id(), tags); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS External Key (%s) tag propagation: %s", d.Id(), err)
}
Expand All @@ -206,8 +203,6 @@ func resourceExternalKeyCreate(ctx context.Context, d *schema.ResourceData, meta
func resourceExternalKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).KMSConn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

key, err := findKey(ctx, conn, d.Id(), d.IsNewResource())

Expand Down Expand Up @@ -255,16 +250,7 @@ func resourceExternalKeyRead(ctx context.Context, d *schema.ResourceData, meta i
d.Set("valid_to", nil)
}

tags := key.tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)

//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return sdkdiag.AppendErrorf(diags, "setting tags: %s", err)
}

if err := d.Set("tags_all", tags.Map()); err != nil {
return sdkdiag.AppendErrorf(diags, "setting tags_all: %s", err)
}
SetTagsOut(ctx, key.tags)

return diags
}
Expand Down Expand Up @@ -316,13 +302,7 @@ func resourceExternalKeyUpdate(ctx context.Context, d *schema.ResourceData, meta
}

if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")

if err := UpdateTags(ctx, conn, d.Id(), o, n); err != nil {
return sdkdiag.AppendErrorf(diags, "updating KMS External Key (%s) tags: %s", d.Id(), err)
}

if err := WaitTagsPropagated(ctx, conn, d.Id(), tftags.New(ctx, n)); err != nil {
if err := WaitTagsPropagated(ctx, conn, d.Id(), tftags.New(ctx, d.Get("tags_all").(map[string]interface{}))); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS External Key (%s) tag propagation: %s", d.Id(), err)
}
}
Expand Down
50 changes: 15 additions & 35 deletions internal/service/kms/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
"github.com/hashicorp/terraform-provider-aws/names"
)

// @SDKResource("aws_kms_key")
// @SDKResource("aws_kms_key", name="Key")
// @Tags(identifierAttribute="id")
func ResourceKey() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceKeyCreate,
Expand Down Expand Up @@ -107,22 +109,21 @@ func ResourceKey() *schema.Resource {
return json
},
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
},
}
}

func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).KMSConn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(ctx, d.Get("tags").(map[string]interface{})))

input := &kms.CreateKeyInput{
BypassPolicyLockoutSafetyCheck: aws.Bool(d.Get("bypass_policy_lockout_safety_check").(bool)),
CustomerMasterKeySpec: aws.String(d.Get("customer_master_key_spec").(string)),
KeyUsage: aws.String(d.Get("key_usage").(string)),
Tags: GetTagsIn(ctx),
}

if v, ok := d.GetOk("description"); ok {
Expand All @@ -147,25 +148,19 @@ func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interfa
input.CustomKeyStoreId = aws.String(v.(string))
}

if len(tags) > 0 {
input.Tags = Tags(tags.IgnoreAWS())
}

// AWS requires any principal in the policy to exist before the key is created.
// The KMS service's awareness of principals is limited by "eventual consistency".
// They acknowledge this here:
// http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html
log.Printf("[DEBUG] Creating KMS Key: %s", input)

outputRaw, err := WaitIAMPropagation(ctx, func() (interface{}, error) {
output, err := WaitIAMPropagation(ctx, func() (*kms.CreateKeyOutput, error) {
return conn.CreateKeyWithContext(ctx, input)
})

if err != nil {
return sdkdiag.AppendErrorf(diags, "creating KMS Key: %s", err)
}

d.SetId(aws.StringValue(outputRaw.(*kms.CreateKeyOutput).KeyMetadata.KeyId))
d.SetId(aws.StringValue(output.KeyMetadata.KeyId))

if enableKeyRotation := d.Get("enable_key_rotation").(bool); enableKeyRotation {
if err := updateKeyRotationEnabled(ctx, conn, d.Id(), enableKeyRotation); err != nil {
Expand All @@ -186,7 +181,7 @@ func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interfa
}
}

if len(tags) > 0 {
if tags := KeyValueTags(ctx, GetTagsIn(ctx)); len(tags) > 0 {
if err := WaitTagsPropagated(ctx, conn, d.Id(), tags); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS Key (%s) tag propagation: %s", d.Id(), err)
}
Expand All @@ -198,8 +193,6 @@ func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interfa
func resourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).KMSConn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

key, err := findKey(ctx, conn, d.Id(), d.IsNewResource())

Expand Down Expand Up @@ -234,16 +227,7 @@ func resourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interface

d.Set("policy", policyToSet)

tags := key.tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)

//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return sdkdiag.AppendErrorf(diags, "setting tags: %s", err)
}

if err := d.Set("tags_all", tags.Map()); err != nil {
return sdkdiag.AppendErrorf(diags, "setting tags_all: %s", err)
}
SetTagsOut(ctx, key.tags)

return diags
}
Expand Down Expand Up @@ -285,13 +269,7 @@ func resourceKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interfa
}

if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")

if err := UpdateTags(ctx, conn, d.Id(), o, n); err != nil {
return sdkdiag.AppendErrorf(diags, "updating KMS Key (%s) tags: %s", d.Id(), err)
}

if err := WaitTagsPropagated(ctx, conn, d.Id(), tftags.New(ctx, n)); err != nil {
if err := WaitTagsPropagated(ctx, conn, d.Id(), tftags.New(ctx, d.Get("tags_all").(map[string]interface{}))); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS Key (%s) tag propagation: %s", d.Id(), err)
}
}
Expand Down Expand Up @@ -337,7 +315,7 @@ type kmsKey struct {
metadata *kms.KeyMetadata
policy string
rotation *bool
tags tftags.KeyValueTags
tags []*kms.Tag
}

func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource bool) (*kmsKey, error) {
Expand Down Expand Up @@ -372,7 +350,7 @@ func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource boo
}
}

key.tags, err = ListTags(ctx, conn, keyID)
tags, err := ListTags(ctx, conn, keyID)

if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) {
return nil, &retry.NotFoundError{LastError: err}
Expand All @@ -382,6 +360,8 @@ func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource boo
return nil, fmt.Errorf("listing tags for KMS Key (%s): %w", keyID, err)
}

key.tags = Tags(tags)

return &key, nil
}, isNewResource)

Expand Down
43 changes: 11 additions & 32 deletions internal/service/kms/replica_external_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
"github.com/hashicorp/terraform-provider-aws/names"
)

// @SDKResource("aws_kms_replica_external_key")
// @SDKResource("aws_kms_replica_external_key", name="Replica External Key")
// @Tags(identifierAttribute="id")
func ResourceReplicaExternalKey() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceReplicaExternalKeyCreate,
Expand Down Expand Up @@ -95,8 +97,8 @@ func ResourceReplicaExternalKey() *schema.Resource {
ForceNew: true,
ValidateFunc: verify.ValidARN,
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
"valid_to": {
Type: schema.TypeString,
Optional: true,
Expand All @@ -109,8 +111,6 @@ func ResourceReplicaExternalKey() *schema.Resource {
func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).KMSConn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(ctx, d.Get("tags").(map[string]interface{})))

// e.g. arn:aws:kms:us-east-2:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab
primaryKeyARN, err := arn.Parse(d.Get("primary_key_arn").(string))
Expand All @@ -122,6 +122,7 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat
input := &kms.ReplicateKeyInput{
KeyId: aws.String(strings.TrimPrefix(primaryKeyARN.Resource, "key/")),
ReplicaRegion: aws.String(meta.(*conns.AWSClient).Region),
Tags: GetTagsIn(ctx),
}

if v, ok := d.GetOk("bypass_policy_lockout_safety_check"); ok {
Expand All @@ -136,10 +137,6 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat
input.Policy = aws.String(v.(string))
}

if len(tags) > 0 {
input.Tags = Tags(tags.IgnoreAWS())
}

// Replication is initiated in the primary key's region.
session, err := conns.NewSessionForRegion(&conn.Config, primaryKeyARN.Region, meta.(*conns.AWSClient).TerraformVersion)

Expand All @@ -149,16 +146,15 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat

replicateConn := kms.New(session)

log.Printf("[DEBUG] Creating KMS Replica External Key: %s", input)
outputRaw, err := WaitIAMPropagation(ctx, func() (interface{}, error) {
output, err := WaitIAMPropagation(ctx, func() (*kms.ReplicateKeyOutput, error) {
return replicateConn.ReplicateKeyWithContext(ctx, input)
})

if err != nil {
return sdkdiag.AppendErrorf(diags, "creating KMS Replica External Key: %s", err)
}

d.SetId(aws.StringValue(outputRaw.(*kms.ReplicateKeyOutput).ReplicaKeyMetadata.KeyId))
d.SetId(aws.StringValue(output.ReplicaKeyMetadata.KeyId))

if _, err := WaitReplicaExternalKeyCreated(ctx, conn, d.Id()); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS Replica External Key (%s) create: %s", d.Id(), err)
Expand Down Expand Up @@ -195,7 +191,7 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat
}
}

if len(tags) > 0 {
if tags := KeyValueTags(ctx, GetTagsIn(ctx)); len(tags) > 0 {
if err := WaitTagsPropagated(ctx, conn, d.Id(), tags); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS Replica External Key (%s) tag propagation: %s", d.Id(), err)
}
Expand All @@ -207,8 +203,6 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat
func resourceReplicaExternalKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).KMSConn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig

key, err := findKey(ctx, conn, d.Id(), d.IsNewResource())

Expand Down Expand Up @@ -257,16 +251,7 @@ func resourceReplicaExternalKeyRead(ctx context.Context, d *schema.ResourceData,
d.Set("valid_to", nil)
}

tags := key.tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)

//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return sdkdiag.AppendErrorf(diags, "setting tags: %s", err)
}

if err := d.Set("tags_all", tags.Map()); err != nil {
return sdkdiag.AppendErrorf(diags, "setting tags_all: %s", err)
}
SetTagsOut(ctx, key.tags)

return diags
}
Expand Down Expand Up @@ -318,13 +303,7 @@ func resourceReplicaExternalKeyUpdate(ctx context.Context, d *schema.ResourceDat
}

if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")

if err := UpdateTags(ctx, conn, d.Id(), o, n); err != nil {
return sdkdiag.AppendErrorf(diags, "updating KMS Replica External Key (%s) tags: %s", d.Id(), err)
}

if err := WaitTagsPropagated(ctx, conn, d.Id(), tftags.New(ctx, n)); err != nil {
if err := WaitTagsPropagated(ctx, conn, d.Id(), tftags.New(ctx, d.Get("tags_all").(map[string]interface{}))); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for KMS Replica External Key (%s) tag propagation: %s", d.Id(), err)
}
}
Expand Down
Loading