diff --git a/go.mod b/go.mod index bf225173316..5da22f7d1cb 100644 --- a/go.mod +++ b/go.mod @@ -228,6 +228,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.9.6 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.7 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.5 // indirect + github.com/aws/aws-sdk-go-v2/service/kms v1.31.0 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.23.4 // indirect github.com/bgentry/speakeasy v0.1.0 // indirect github.com/boombuler/barcode v1.0.1 // indirect diff --git a/go.sum b/go.sum index 76ab48f31e2..389e2e6cea1 100644 --- a/go.sum +++ b/go.sum @@ -230,6 +230,8 @@ github.com/aws/aws-sdk-go-v2/service/keyspaces v1.10.4 h1:b8U8xht0BhuuzDlKUq/QzB github.com/aws/aws-sdk-go-v2/service/keyspaces v1.10.4/go.mod h1:K0uQVx8xnUBI3CudcERApORx5cJrVUDew1K3deRDjLU= github.com/aws/aws-sdk-go-v2/service/kinesis v1.27.4 h1:Oe8awBiS/iitcsRJB5+DHa3iCxoA0KwJJf0JNrYMINY= github.com/aws/aws-sdk-go-v2/service/kinesis v1.27.4/go.mod h1:RCZCSFbieSgNG1RKegO26opXV4EXyef/vNBVJsUyHuw= +github.com/aws/aws-sdk-go-v2/service/kms v1.31.0 h1:yl7wcqbisxPzknJVfWTLnK83McUvXba+pz2+tPbIUmQ= +github.com/aws/aws-sdk-go-v2/service/kms v1.31.0/go.mod h1:2snWQJQUKsbN66vAawJuOGX7dr37pfOq9hb0tZDGIqQ= github.com/aws/aws-sdk-go-v2/service/lakeformation v1.32.0 h1:X7ydA78B8lmKVgGS3XEVUsgMKMHoYhmIwoxl3U2S2wg= github.com/aws/aws-sdk-go-v2/service/lakeformation v1.32.0/go.mod h1:0xTSto0XwDuPvY7P3XoEwOLH7sr5EzehNvxCoBaeuPU= github.com/aws/aws-sdk-go-v2/service/lambda v1.54.0 h1:gazALVrZ7RIG6gJXut3c7NKtPgs9eQ8BFCA9uoliayk= diff --git a/internal/conns/awsclient.go b/internal/conns/awsclient.go index e9ce0525daf..7630fc28b13 100644 --- a/internal/conns/awsclient.go +++ b/internal/conns/awsclient.go @@ -15,13 +15,13 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" config_sdkv2 "github.com/aws/aws-sdk-go-v2/config" apigatewayv2_types "github.com/aws/aws-sdk-go-v2/service/apigatewayv2/types" + kms_sdkv2 "github.com/aws/aws-sdk-go-v2/service/kms" s3_sdkv2 "github.com/aws/aws-sdk-go-v2/service/s3" aws_sdkv1 "github.com/aws/aws-sdk-go/aws" session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" directoryservice_sdkv1 "github.com/aws/aws-sdk-go/service/directoryservice" dynamodb_sdkv1 "github.com/aws/aws-sdk-go/service/dynamodb" efs_sdkv1 "github.com/aws/aws-sdk-go/service/efs" - kms_sdkv1 "github.com/aws/aws-sdk-go/service/kms" opsworks_sdkv1 "github.com/aws/aws-sdk-go/service/opsworks" rds_sdkv1 "github.com/aws/aws-sdk-go/service/rds" baselogging "github.com/hashicorp/aws-sdk-go-base/v2/logging" @@ -95,14 +95,14 @@ func (c *AWSClient) EFSConnForRegion(ctx context.Context, region string) *efs_sd return efs_sdkv1.New(c.session, aws_sdkv1.NewConfig().WithRegion(region)) } -// KMSConnForRegion returns an AWS SDK For Go v1 KMS API client for the specified AWS Region. +// KMSConnForRegion returns an AWS SDK For Go v2 KMS API client for the specified AWS Region. // If the specified region is not the default a new "simple" client is created. // This new client does not use any configured endpoint override. -func (c *AWSClient) KMSConnForRegion(ctx context.Context, region string) *kms_sdkv1.KMS { +func (c *AWSClient) KMSConnForRegion(ctx context.Context, region string) *kms_sdkv2.Client { if region == c.Region { - return c.KMSConn(ctx) + return c.KMSClient(ctx) } - return kms_sdkv1.New(c.session, aws_sdkv1.NewConfig().WithRegion(region)) + return kms_sdkv2.New(kms_sdkv2.Options{Region: region}) } // KMSConnForRegion returns an AWS SDK For Go v1 OpsWorks API client for the specified AWS Region. diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index ad4fe435f1b..b3ae817bc20 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -92,6 +92,7 @@ import ( kendra_sdkv2 "github.com/aws/aws-sdk-go-v2/service/kendra" keyspaces_sdkv2 "github.com/aws/aws-sdk-go-v2/service/keyspaces" kinesis_sdkv2 "github.com/aws/aws-sdk-go-v2/service/kinesis" + kms_sdkv2 "github.com/aws/aws-sdk-go-v2/service/kms" lakeformation_sdkv2 "github.com/aws/aws-sdk-go-v2/service/lakeformation" lambda_sdkv2 "github.com/aws/aws-sdk-go-v2/service/lambda" launchwizard_sdkv2 "github.com/aws/aws-sdk-go-v2/service/launchwizard" @@ -209,7 +210,6 @@ import ( kinesisanalytics_sdkv1 "github.com/aws/aws-sdk-go/service/kinesisanalytics" kinesisanalyticsv2_sdkv1 "github.com/aws/aws-sdk-go/service/kinesisanalyticsv2" kinesisvideo_sdkv1 "github.com/aws/aws-sdk-go/service/kinesisvideo" - kms_sdkv1 "github.com/aws/aws-sdk-go/service/kms" lambda_sdkv1 "github.com/aws/aws-sdk-go/service/lambda" lexmodelbuildingservice_sdkv1 "github.com/aws/aws-sdk-go/service/lexmodelbuildingservice" licensemanager_sdkv1 "github.com/aws/aws-sdk-go/service/licensemanager" @@ -770,8 +770,8 @@ func (c *AWSClient) IoTEventsConn(ctx context.Context) *iotevents_sdkv1.IoTEvent return errs.Must(conn[*iotevents_sdkv1.IoTEvents](ctx, c, names.IoTEvents, make(map[string]any))) } -func (c *AWSClient) KMSConn(ctx context.Context) *kms_sdkv1.KMS { - return errs.Must(conn[*kms_sdkv1.KMS](ctx, c, names.KMS, make(map[string]any))) +func (c *AWSClient) KMSClient(ctx context.Context) *kms_sdkv2.Client { + return errs.Must(client[*kms_sdkv2.Client](ctx, c, names.KMS, make(map[string]any))) } func (c *AWSClient) KafkaClient(ctx context.Context) *kafka_sdkv2.Client { diff --git a/internal/service/ec2/ebs_default_kms_key_test.go b/internal/service/ec2/ebs_default_kms_key_test.go index a9923f1eb57..2343ea477cf 100644 --- a/internal/service/ec2/ebs_default_kms_key_test.go +++ b/internal/service/ec2/ebs_default_kms_key_test.go @@ -103,7 +103,7 @@ func testAccCheckEBSDefaultKMSKey(ctx context.Context, name string) resource.Tes // testAccEBSManagedDefaultKey returns' the account's AWS-managed default CMK. func testAccEBSManagedDefaultKey(ctx context.Context) (*arn.ARN, error) { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) alias, err := tfkms.FindAliasByName(ctx, conn, "alias/aws/ebs") if err != nil { diff --git a/internal/service/kms/alias.go b/internal/service/kms/alias.go index bec4e842d25..b5d898bd181 100644 --- a/internal/service/kms/alias.go +++ b/internal/service/kms/alias.go @@ -7,13 +7,14 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -70,7 +71,7 @@ func ResourceAlias() *schema.Resource { func resourceAliasCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) namePrefix := d.Get("name_prefix").(string) if namePrefix == "" { @@ -84,11 +85,13 @@ func resourceAliasCreate(ctx context.Context, d *schema.ResourceData, meta inter } // KMS is eventually consistent. - log.Printf("[DEBUG] Creating KMS Alias: %s", input) + log.Printf("[DEBUG] Creating KMS Alias: %v", input) + + var NotFoundException = &awstypes.NotFoundException{} _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, KeyRotationUpdatedTimeout, func() (interface{}, error) { - return conn.CreateAliasWithContext(ctx, input) - }, kms.ErrCodeNotFoundException) + return conn.CreateAlias(ctx, input) + }, NotFoundException.ErrorCode()) if err != nil { return sdkdiag.AppendErrorf(diags, "creating KMS Alias (%s): %s", name, err) @@ -101,7 +104,7 @@ func resourceAliasCreate(ctx context.Context, d *schema.ResourceData, meta inter func resourceAliasRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, PropagationTimeout, func() (interface{}, error) { return FindAliasByName(ctx, conn, d.Id()) @@ -117,9 +120,9 @@ func resourceAliasRead(ctx context.Context, d *schema.ResourceData, meta interfa return sdkdiag.AppendErrorf(diags, "reading KMS Alias (%s): %s", d.Id(), err) } - alias := outputRaw.(*kms.AliasListEntry) - aliasARN := aws.StringValue(alias.AliasArn) - targetKeyID := aws.StringValue(alias.TargetKeyId) + alias := outputRaw.(*awstypes.AliasListEntry) + aliasARN := aws.ToString(alias.AliasArn) + targetKeyID := aws.ToString(alias.TargetKeyId) targetKeyARN, err := AliasARNToKeyARN(aliasARN, targetKeyID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading KMS Alias (%s): %s", d.Id(), err) @@ -127,7 +130,7 @@ func resourceAliasRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("arn", aliasARN) d.Set("name", alias.AliasName) - d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(alias.AliasName))) + d.Set("name_prefix", create.NamePrefixFromName(aws.ToString(alias.AliasName))) d.Set("target_key_arn", targetKeyARN) d.Set("target_key_id", targetKeyID) @@ -136,7 +139,7 @@ func resourceAliasRead(ctx context.Context, d *schema.ResourceData, meta interfa func resourceAliasUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) if d.HasChange("target_key_id") { input := &kms.UpdateAliasInput{ @@ -144,8 +147,8 @@ func resourceAliasUpdate(ctx context.Context, d *schema.ResourceData, meta inter TargetKeyId: aws.String(d.Get("target_key_id").(string)), } - log.Printf("[DEBUG] Updating KMS Alias: %s", input) - _, err := conn.UpdateAliasWithContext(ctx, input) + log.Printf("[DEBUG] Updating KMS Alias: %v", input) + _, err := conn.UpdateAlias(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating KMS Alias (%s): %s", d.Id(), err) @@ -157,14 +160,14 @@ func resourceAliasUpdate(ctx context.Context, d *schema.ResourceData, meta inter func resourceAliasDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) log.Printf("[DEBUG] Deleting KMS Alias: (%s)", d.Id()) - _, err := conn.DeleteAliasWithContext(ctx, &kms.DeleteAliasInput{ + _, err := conn.DeleteAlias(ctx, &kms.DeleteAliasInput{ AliasName: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } diff --git a/internal/service/kms/alias_data_source.go b/internal/service/kms/alias_data_source.go index a1c89de5ba9..e35eb651e2f 100644 --- a/internal/service/kms/alias_data_source.go +++ b/internal/service/kms/alias_data_source.go @@ -6,7 +6,7 @@ package kms import ( "context" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -41,7 +41,7 @@ func DataSourceAlias() *schema.Resource { func dataSourceAliasRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) target := d.Get("name").(string) @@ -51,7 +51,7 @@ func dataSourceAliasRead(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "reading KMS Alias (%s): %s", target, err) } - d.SetId(aws.StringValue(alias.AliasArn)) + d.SetId(aws.ToString(alias.AliasArn)) d.Set("arn", alias.AliasArn) // ListAliases can return an alias for an AWS service key (e.g. diff --git a/internal/service/kms/alias_test.go b/internal/service/kms/alias_test.go index 7a2614ecc12..f5ad2a4ca0c 100644 --- a/internal/service/kms/alias_test.go +++ b/internal/service/kms/alias_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -23,7 +23,7 @@ import ( func TestAccKMSAlias_basic(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" keyResourceName := "aws_kms_key.test" @@ -55,7 +55,7 @@ func TestAccKMSAlias_basic(t *testing.T) { func TestAccKMSAlias_disappears(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" @@ -79,7 +79,7 @@ func TestAccKMSAlias_disappears(t *testing.T) { func TestAccKMSAlias_Name_generated(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" @@ -108,7 +108,7 @@ func TestAccKMSAlias_Name_generated(t *testing.T) { func TestAccKMSAlias_namePrefix(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" @@ -137,7 +137,7 @@ func TestAccKMSAlias_namePrefix(t *testing.T) { func TestAccKMSAlias_updateKeyID(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" key1ResourceName := "aws_kms_key.test" @@ -176,7 +176,7 @@ func TestAccKMSAlias_updateKeyID(t *testing.T) { func TestAccKMSAlias_multipleAliasesForSameKey(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" alias2ResourceName := "aws_kms_alias.test2" @@ -210,7 +210,7 @@ func TestAccKMSAlias_multipleAliasesForSameKey(t *testing.T) { func TestAccKMSAlias_arnDiffSuppress(t *testing.T) { ctx := acctest.Context(t) - var alias kms.AliasListEntry + var alias awstypes.AliasListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_alias.test" @@ -243,7 +243,7 @@ func TestAccKMSAlias_arnDiffSuppress(t *testing.T) { func testAccCheckAliasDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_kms_alias" { @@ -267,7 +267,7 @@ func testAccCheckAliasDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckAliasExists(ctx context.Context, name string, v *kms.AliasListEntry) resource.TestCheckFunc { +func testAccCheckAliasExists(ctx context.Context, name string, v *awstypes.AliasListEntry) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -278,7 +278,7 @@ func testAccCheckAliasExists(ctx context.Context, name string, v *kms.AliasListE return fmt.Errorf("No KMS Alias ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) output, err := tfkms.FindAliasByName(ctx, conn, rs.Primary.ID) diff --git a/internal/service/kms/ciphertext.go b/internal/service/kms/ciphertext.go index 1a15eb68d81..959fd028d40 100644 --- a/internal/service/kms/ciphertext.go +++ b/internal/service/kms/ciphertext.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -52,7 +52,7 @@ func ResourceCiphertext() *schema.Resource { func resourceCiphertextCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID := d.Get("key_id").(string) input := &kms.EncryptInput{ @@ -61,10 +61,10 @@ func resourceCiphertextCreate(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("context"); ok && len(v.(map[string]interface{})) > 0 { - input.EncryptionContext = flex.ExpandStringMap(v.(map[string]interface{})) + input.EncryptionContext = flex.ExpandStringValueMap(v.(map[string]interface{})) } - output, err := conn.EncryptWithContext(ctx, input) + output, err := conn.Encrypt(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "encrypting with KMS Key (%s): %s", keyID, err) diff --git a/internal/service/kms/ciphertext_data_source.go b/internal/service/kms/ciphertext_data_source.go index b611b717ac0..fd83ae838fa 100644 --- a/internal/service/kms/ciphertext_data_source.go +++ b/internal/service/kms/ciphertext_data_source.go @@ -6,8 +6,8 @@ package kms import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -46,7 +46,7 @@ func DataSourceCiphertext() *schema.Resource { func dataSourceCiphertextRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID := d.Get("key_id").(string) input := &kms.EncryptInput{ @@ -55,16 +55,16 @@ func dataSourceCiphertextRead(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("context"); ok && len(v.(map[string]interface{})) > 0 { - input.EncryptionContext = flex.ExpandStringMap(v.(map[string]interface{})) + input.EncryptionContext = flex.ExpandStringValueMap(v.(map[string]interface{})) } - output, err := conn.EncryptWithContext(ctx, input) + output, err := conn.Encrypt(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "encrypting with KMS Key (%s): %s", keyID, err) } - d.SetId(aws.StringValue(output.KeyId)) + d.SetId(aws.ToString(output.KeyId)) d.Set("ciphertext_blob", itypes.Base64Encode(output.CiphertextBlob)) return diags diff --git a/internal/service/kms/custom_key_store.go b/internal/service/kms/custom_key_store.go index b4f63bb786e..34d5afacaa7 100644 --- a/internal/service/kms/custom_key_store.go +++ b/internal/service/kms/custom_key_store.go @@ -9,14 +9,15 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -69,7 +70,7 @@ const ( func resourceCustomKeyStoreCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) in := &kms.CreateCustomKeyStoreInput{ CloudHsmClusterId: aws.String(d.Get("cloud_hsm_cluster_id").(string)), @@ -78,7 +79,7 @@ func resourceCustomKeyStoreCreate(ctx context.Context, d *schema.ResourceData, m TrustAnchorCertificate: aws.String(d.Get("trust_anchor_certificate").(string)), } - out, err := conn.CreateCustomKeyStoreWithContext(ctx, in) + out, err := conn.CreateCustomKeyStore(ctx, in) if err != nil { return create.AppendDiagError(diags, names.KMS, create.ErrActionCreating, ResNameCustomKeyStore, d.Get("custom_key_store_name").(string), err) } @@ -87,7 +88,7 @@ func resourceCustomKeyStoreCreate(ctx context.Context, d *schema.ResourceData, m return create.AppendDiagError(diags, names.KMS, create.ErrActionCreating, ResNameCustomKeyStore, d.Get("custom_key_store_name").(string), errors.New("empty output")) } - d.SetId(aws.StringValue(out.CustomKeyStoreId)) + d.SetId(aws.ToString(out.CustomKeyStoreId)) return append(diags, resourceCustomKeyStoreRead(ctx, d, meta)...) } @@ -95,7 +96,7 @@ func resourceCustomKeyStoreCreate(ctx context.Context, d *schema.ResourceData, m func resourceCustomKeyStoreRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) in := &kms.DescribeCustomKeyStoresInput{ CustomKeyStoreId: aws.String(d.Id()), @@ -122,7 +123,7 @@ func resourceCustomKeyStoreRead(ctx context.Context, d *schema.ResourceData, met func resourceCustomKeyStoreUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) update := false @@ -145,7 +146,7 @@ func resourceCustomKeyStoreUpdate(ctx context.Context, d *schema.ResourceData, m return diags } - _, err := conn.UpdateCustomKeyStoreWithContext(ctx, in) + _, err := conn.UpdateCustomKeyStore(ctx, in) if err != nil { return create.AppendDiagError(diags, names.KMS, create.ErrActionUpdating, ResNameCustomKeyStore, d.Id(), err) } @@ -156,15 +157,15 @@ func resourceCustomKeyStoreUpdate(ctx context.Context, d *schema.ResourceData, m func resourceCustomKeyStoreDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) log.Printf("[INFO] Deleting KMS CustomKeyStore %s", d.Id()) - _, err := conn.DeleteCustomKeyStoreWithContext(ctx, &kms.DeleteCustomKeyStoreInput{ + _, err := conn.DeleteCustomKeyStore(ctx, &kms.DeleteCustomKeyStoreInput{ CustomKeyStoreId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } diff --git a/internal/service/kms/custom_key_store_data_source.go b/internal/service/kms/custom_key_store_data_source.go index 466c56d08a7..d541307d0f0 100644 --- a/internal/service/kms/custom_key_store_data_source.go +++ b/internal/service/kms/custom_key_store_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -60,7 +60,7 @@ const ( func dataSourceCustomKeyStoreRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) input := &kms.DescribeCustomKeyStoresInput{} @@ -80,7 +80,7 @@ func dataSourceCustomKeyStoreRead(ctx context.Context, d *schema.ResourceData, m return create.AppendDiagError(diags, names.KMS, create.ErrActionReading, DSNameCustomKeyStore, ksID, err) } - d.SetId(aws.StringValue(keyStore.CustomKeyStoreId)) + d.SetId(aws.ToString(keyStore.CustomKeyStoreId)) d.Set("custom_key_store_name", keyStore.CustomKeyStoreName) d.Set("custom_key_store_id", keyStore.CustomKeyStoreId) d.Set("cloud_hsm_cluster_id", keyStore.CloudHsmClusterId) diff --git a/internal/service/kms/custom_key_store_test.go b/internal/service/kms/custom_key_store_test.go index f4a52c07004..c1d3813e5be 100644 --- a/internal/service/kms/custom_key_store_test.go +++ b/internal/service/kms/custom_key_store_test.go @@ -10,8 +10,9 @@ import ( "os" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -37,7 +38,7 @@ func testAccCustomKeyStore_basic(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var customkeystore kms.CustomKeyStoresListEntry + var customkeystore awstypes.CustomKeyStoresListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_custom_key_store.test" @@ -47,7 +48,7 @@ func testAccCustomKeyStore_basic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, kms.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.KMSEndpointID) testAccCustomKeyStoresPreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.KMSServiceID), @@ -85,7 +86,7 @@ func testAccCustomKeyStore_update(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var customkeystore kms.CustomKeyStoresListEntry + var customkeystore awstypes.CustomKeyStoresListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_custom_key_store.test" @@ -95,7 +96,7 @@ func testAccCustomKeyStore_update(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, kms.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.KMSEndpointID) testAccCustomKeyStoresPreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.KMSServiceID), @@ -128,7 +129,7 @@ func testAccCustomKeyStore_disappears(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var customkeystore kms.CustomKeyStoresListEntry + var customkeystore awstypes.CustomKeyStoresListEntry rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_custom_key_store.test" @@ -138,7 +139,7 @@ func testAccCustomKeyStore_disappears(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, kms.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.KMSEndpointID) testAccCustomKeyStoresPreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.KMSServiceID), @@ -159,7 +160,7 @@ func testAccCustomKeyStore_disappears(t *testing.T) { func testAccCheckCustomKeyStoreDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_kms_custom_key_store" { @@ -182,7 +183,7 @@ func testAccCheckCustomKeyStoreDestroy(ctx context.Context) resource.TestCheckFu } } -func testAccCheckCustomKeyStoreExists(ctx context.Context, name string, customkeystore *kms.CustomKeyStoresListEntry) resource.TestCheckFunc { +func testAccCheckCustomKeyStoreExists(ctx context.Context, name string, customkeystore *awstypes.CustomKeyStoresListEntry) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -193,7 +194,7 @@ func testAccCheckCustomKeyStoreExists(ctx context.Context, name string, customke return create.Error(names.KMS, create.ErrActionCheckingExistence, tfkms.ResNameCustomKeyStore, name, errors.New("not set")) } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) in := &kms.DescribeCustomKeyStoresInput{ CustomKeyStoreId: aws.String(rs.Primary.ID), @@ -211,10 +212,10 @@ func testAccCheckCustomKeyStoreExists(ctx context.Context, name string, customke } func testAccCustomKeyStoresPreCheck(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) input := &kms.DescribeCustomKeyStoresInput{} - _, err := conn.DescribeCustomKeyStoresWithContext(ctx, input) + _, err := conn.DescribeCustomKeyStores(ctx, input) if acctest.PreCheckSkipError(err) { t.Skipf("skipping acceptance testing: %s", err) diff --git a/internal/service/kms/external_key.go b/internal/service/kms/external_key.go index eaa3e1c54c8..433c4c6c596 100644 --- a/internal/service/kms/external_key.go +++ b/internal/service/kms/external_key.go @@ -13,17 +13,19 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/logging" + "github.com/hashicorp/terraform-provider-aws/internal/slices" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" itypes "github.com/hashicorp/terraform-provider-aws/internal/types" @@ -124,12 +126,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(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) input := &kms.CreateKeyInput{ - BypassPolicyLockoutSafetyCheck: aws.Bool(d.Get("bypass_policy_lockout_safety_check").(bool)), - KeyUsage: aws.String(kms.KeyUsageTypeEncryptDecrypt), - Origin: aws.String(kms.OriginTypeExternal), + BypassPolicyLockoutSafetyCheck: d.Get("bypass_policy_lockout_safety_check").(bool), + KeyUsage: awstypes.KeyUsageTypeEncryptDecrypt, + Origin: awstypes.OriginTypeExternal, Tags: getTagsIn(ctx), } @@ -156,14 +158,14 @@ func resourceExternalKeyCreate(ctx context.Context, d *schema.ResourceData, meta // They acknowledge this here: // http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html output, err := WaitIAMPropagation(ctx, propagationTimeout, func() (*kms.CreateKeyOutput, error) { - return conn.CreateKeyWithContext(ctx, input) + return conn.CreateKey(ctx, input) }) if err != nil { return sdkdiag.AppendErrorf(diags, "creating KMS External Key: %s", err) } - d.SetId(aws.StringValue(output.KeyMetadata.KeyId)) + d.SetId(aws.ToString(output.KeyMetadata.KeyId)) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -209,7 +211,7 @@ 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(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -225,16 +227,16 @@ func resourceExternalKeyRead(ctx context.Context, d *schema.ResourceData, meta i return sdkdiag.AppendErrorf(diags, "reading KMS External Key (%s): %s", d.Id(), err) } - if keyManager := aws.StringValue(key.metadata.KeyManager); keyManager != kms.KeyManagerTypeCustomer { + if keyManager := key.metadata.KeyManager; keyManager != awstypes.KeyManagerTypeCustomer { return sdkdiag.AppendErrorf(diags, "KMS External Key (%s) has invalid KeyManager: %s", d.Id(), keyManager) } - if origin := aws.StringValue(key.metadata.Origin); origin != kms.OriginTypeExternal { + if origin := key.metadata.Origin; origin != awstypes.OriginTypeExternal { return sdkdiag.AppendErrorf(diags, "KMS External Key (%s) has invalid Origin: %s", d.Id(), origin) } - if aws.BoolValue(key.metadata.MultiRegion) && - aws.StringValue(key.metadata.MultiRegionConfiguration.MultiRegionKeyType) != kms.MultiRegionKeyTypePrimary { + if aws.ToBool(key.metadata.MultiRegion) && + key.metadata.MultiRegionConfiguration.MultiRegionKeyType != awstypes.MultiRegionKeyTypePrimary { return sdkdiag.AppendErrorf(diags, "KMS External Key (%s) is not a multi-Region primary key", d.Id()) } @@ -254,23 +256,23 @@ func resourceExternalKeyRead(ctx context.Context, d *schema.ResourceData, meta i d.Set("policy", policyToSet) if key.metadata.ValidTo != nil { - d.Set("valid_to", aws.TimeValue(key.metadata.ValidTo).Format(time.RFC3339)) + d.Set("valid_to", aws.ToTime(key.metadata.ValidTo).Format(time.RFC3339)) } else { d.Set("valid_to", nil) } - setTagsOut(ctx, key.tags) + setTagsOut(ctx, slices.Values(key.tags)) return diags } func resourceExternalKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) - if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && enabled && state != kms.KeyStatePendingImport { + if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && enabled && state != string(awstypes.KeyStatePendingImport) { // Enable before any attributes are modified. if err := updateKeyEnabled(ctx, conn, d.Id(), enabled); err != nil { return sdkdiag.AppendErrorf(diags, "updating KMS External Key (%s): %s", d.Id(), err) @@ -305,7 +307,7 @@ func resourceExternalKeyUpdate(ctx context.Context, d *schema.ResourceData, meta } } - if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && !enabled && state != kms.KeyStatePendingImport { + if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && !enabled && state != string(awstypes.KeyStatePendingImport) { // Only disable after all attributes have been modified because we cannot modify disabled keys. if err := updateKeyEnabled(ctx, conn, d.Id(), enabled); err != nil { return sdkdiag.AppendErrorf(diags, "updating KMS External Key (%s): %s", d.Id(), err) @@ -317,7 +319,7 @@ func resourceExternalKeyUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceExternalKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -326,17 +328,17 @@ func resourceExternalKeyDelete(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("deletion_window_in_days"); ok { - input.PendingWindowInDays = aws.Int64(int64(v.(int))) + input.PendingWindowInDays = aws.Int32(int32(v.(int))) } log.Printf("[DEBUG] Deleting KMS External Key: (%s)", d.Id()) - _, err := conn.ScheduleKeyDeletionWithContext(ctx, input) + _, err := conn.ScheduleKeyDeletion(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } - if tfawserr.ErrMessageContains(err, kms.ErrCodeInvalidStateException, "is pending deletion") { + if errs.IsAErrorMessageContains[*awstypes.KMSInvalidStateException](err, "is pending deletion") { return diags } @@ -351,15 +353,17 @@ func resourceExternalKeyDelete(ctx context.Context, d *schema.ResourceData, meta return diags } -func importExternalKeyMaterial(ctx context.Context, conn *kms.KMS, keyID, keyMaterialBase64, validTo string) error { +func importExternalKeyMaterial(ctx context.Context, conn *kms.Client, keyID, keyMaterialBase64, validTo string) error { // Wait for propagation since KMS is eventually consistent. + + var NotFoundException = &awstypes.NotFoundException{} outputRaw, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, PropagationTimeout, func() (interface{}, error) { - return conn.GetParametersForImportWithContext(ctx, &kms.GetParametersForImportInput{ + return conn.GetParametersForImport(ctx, &kms.GetParametersForImportInput{ KeyId: aws.String(keyID), - WrappingAlgorithm: aws.String(kms.AlgorithmSpecRsaesOaepSha256), - WrappingKeySpec: aws.String(kms.WrappingKeySpecRsa2048), + WrappingAlgorithm: awstypes.AlgorithmSpecRsaesOaepSha256, + WrappingKeySpec: awstypes.WrappingKeySpecRsa2048, }) - }, kms.ErrCodeNotFoundException) + }, NotFoundException.ErrorCode()) if err != nil { return fmt.Errorf("getting parameters for import: %w", err) @@ -384,7 +388,7 @@ func importExternalKeyMaterial(ctx context.Context, conn *kms.KMS, keyID, keyMat input := &kms.ImportKeyMaterialInput{ EncryptedKeyMaterial: encryptedKeyMaterial, - ExpirationModel: aws.String(kms.ExpirationModelTypeKeyMaterialDoesNotExpire), + ExpirationModel: awstypes.ExpirationModelTypeKeyMaterialDoesNotExpire, ImportToken: output.ImportToken, KeyId: aws.String(keyID), } @@ -395,14 +399,14 @@ func importExternalKeyMaterial(ctx context.Context, conn *kms.KMS, keyID, keyMat return err } - input.ExpirationModel = aws.String(kms.ExpirationModelTypeKeyMaterialExpires) + input.ExpirationModel = awstypes.ExpirationModelTypeKeyMaterialExpires input.ValidTo = aws.Time(t) } // Wait for propagation since KMS is eventually consistent. _, err = tfresource.RetryWhenAWSErrCodeEquals(ctx, PropagationTimeout, func() (interface{}, error) { - return conn.ImportKeyMaterialWithContext(ctx, input) - }, kms.ErrCodeNotFoundException) + return conn.ImportKeyMaterial(ctx, input) + }, NotFoundException.ErrorCode()) if err != nil { return fmt.Errorf("importing key material: %w", err) diff --git a/internal/service/kms/external_key_test.go b/internal/service/kms/external_key_test.go index 3d938d8fdfa..d4a593ce9fb 100644 --- a/internal/service/kms/external_key_test.go +++ b/internal/service/kms/external_key_test.go @@ -10,8 +10,8 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" awspolicy "github.com/hashicorp/awspolicyequivalence" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -25,7 +25,7 @@ import ( func TestAccKMSExternalKey_basic(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata resourceName := "aws_kms_external_key.test" resource.ParallelTest(t, resource.TestCase{ @@ -67,7 +67,7 @@ func TestAccKMSExternalKey_basic(t *testing.T) { func TestAccKMSExternalKey_disappears(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata resourceName := "aws_kms_external_key.test" resource.ParallelTest(t, resource.TestCase{ @@ -90,7 +90,7 @@ func TestAccKMSExternalKey_disappears(t *testing.T) { func TestAccKMSExternalKey_multiRegion(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" @@ -122,7 +122,7 @@ func TestAccKMSExternalKey_multiRegion(t *testing.T) { func TestAccKMSExternalKey_deletionWindowInDays(t *testing.T) { ctx := acctest.Context(t) - var key1, key2 kms.KeyMetadata + var key1, key2 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" @@ -162,7 +162,7 @@ func TestAccKMSExternalKey_deletionWindowInDays(t *testing.T) { func TestAccKMSExternalKey_description(t *testing.T) { ctx := acctest.Context(t) - var key1, key2 kms.KeyMetadata + var key1, key2 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" @@ -202,7 +202,7 @@ func TestAccKMSExternalKey_description(t *testing.T) { func TestAccKMSExternalKey_enabled(t *testing.T) { ctx := acctest.Context(t) - var key1, key2, key3 kms.KeyMetadata + var key1, key2, key3 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" @@ -251,7 +251,7 @@ func TestAccKMSExternalKey_enabled(t *testing.T) { func TestAccKMSExternalKey_keyMaterialBase64(t *testing.T) { ctx := acctest.Context(t) - var key1, key2 kms.KeyMetadata + var key1, key2 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" @@ -294,7 +294,7 @@ func TestAccKMSExternalKey_keyMaterialBase64(t *testing.T) { func TestAccKMSExternalKey_policy(t *testing.T) { ctx := acctest.Context(t) - var key1, key2 kms.KeyMetadata + var key1, key2 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) policy1 := `{"Id":"kms-tf-1","Statement":[{"Action":"kms:*","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*","Sid":"Enable IAM User Permissions 1"}],"Version":"2012-10-17"}` policy2 := `{"Id":"kms-tf-1","Statement":[{"Action":"kms:*","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*","Sid":"Enable IAM User Permissions 2"}],"Version":"2012-10-17"}` @@ -336,7 +336,7 @@ func TestAccKMSExternalKey_policy(t *testing.T) { func TestAccKMSExternalKey_policyBypass(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) policy := `{"Id":"kms-tf-1","Statement":[{"Action":"kms:*","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*","Sid":"Enable IAM User Permissions 1"}],"Version":"2012-10-17"}` resourceName := "aws_kms_external_key.test" @@ -370,7 +370,7 @@ func TestAccKMSExternalKey_policyBypass(t *testing.T) { func TestAccKMSExternalKey_tags(t *testing.T) { ctx := acctest.Context(t) - var key1, key2, key3 kms.KeyMetadata + var key1, key2, key3 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" @@ -439,7 +439,7 @@ func TestAccKMSExternalKey_tags(t *testing.T) { func TestAccKMSExternalKey_validTo(t *testing.T) { ctx := acctest.Context(t) - var key1, key2, key3, key4 kms.KeyMetadata + var key1, key2, key3, key4 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_external_key.test" validTo1 := time.Now().UTC().Add(1 * time.Hour).Format(time.RFC3339) @@ -511,7 +511,7 @@ func testAccCheckExternalKeyHasPolicy(ctx context.Context, name string, expected return fmt.Errorf("No KMS External Key ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) output, err := tfkms.FindKeyPolicyByKeyIDAndPolicyName(ctx, conn, rs.Primary.ID, tfkms.PolicyNameDefault) @@ -519,7 +519,7 @@ func testAccCheckExternalKeyHasPolicy(ctx context.Context, name string, expected return err } - actualPolicyText := aws.StringValue(output) + actualPolicyText := aws.ToString(output) equivalent, err := awspolicy.PoliciesAreEquivalent(actualPolicyText, expectedPolicyText) if err != nil { @@ -536,7 +536,7 @@ func testAccCheckExternalKeyHasPolicy(ctx context.Context, name string, expected func testAccCheckExternalKeyDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_kms_external_key" { @@ -560,7 +560,7 @@ func testAccCheckExternalKeyDestroy(ctx context.Context) resource.TestCheckFunc } } -func testAccCheckExternalKeyExists(ctx context.Context, name string, key *kms.KeyMetadata) resource.TestCheckFunc { +func testAccCheckExternalKeyExists(ctx context.Context, name string, key *awstypes.KeyMetadata) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -571,7 +571,7 @@ func testAccCheckExternalKeyExists(ctx context.Context, name string, key *kms.Ke return fmt.Errorf("No KMS External Key ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) outputRaw, err := tfresource.RetryWhenNotFound(ctx, tfkms.PropagationTimeout, func() (interface{}, error) { return tfkms.FindKeyByID(ctx, conn, rs.Primary.ID) @@ -581,15 +581,15 @@ func testAccCheckExternalKeyExists(ctx context.Context, name string, key *kms.Ke return err } - *key = *(outputRaw.(*kms.KeyMetadata)) + *key = *(outputRaw.(*awstypes.KeyMetadata)) return nil } } -func testAccCheckExternalKeyNotRecreated(i, j *kms.KeyMetadata) resource.TestCheckFunc { +func testAccCheckExternalKeyNotRecreated(i, j *awstypes.KeyMetadata) resource.TestCheckFunc { return func(s *terraform.State) error { - if !aws.TimeValue(i.CreationDate).Equal(aws.TimeValue(j.CreationDate)) { + if !aws.ToTime(i.CreationDate).Equal(aws.ToTime(j.CreationDate)) { return fmt.Errorf("KMS External Key recreated") } @@ -597,9 +597,9 @@ func testAccCheckExternalKeyNotRecreated(i, j *kms.KeyMetadata) resource.TestChe } } -func testAccCheckExternalKeyRecreated(i, j *kms.KeyMetadata) resource.TestCheckFunc { +func testAccCheckExternalKeyRecreated(i, j *awstypes.KeyMetadata) resource.TestCheckFunc { return func(s *terraform.State) error { - if aws.TimeValue(i.CreationDate).Equal(aws.TimeValue(j.CreationDate)) { + if aws.ToTime(i.CreationDate).Equal(aws.ToTime(j.CreationDate)) { return fmt.Errorf("KMS External Key not recreated") } diff --git a/internal/service/kms/find.go b/internal/service/kms/find.go index 1a88f277ec6..b8a801599c6 100644 --- a/internal/service/kms/find.go +++ b/internal/service/kms/find.go @@ -7,49 +7,39 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindAliasByName(ctx context.Context, conn *kms.KMS, name string) (*kms.AliasListEntry, error) { +func FindAliasByName(ctx context.Context, conn *kms.Client, name string) (*awstypes.AliasListEntry, error) { input := &kms.ListAliasesInput{} - var output *kms.AliasListEntry + pages := kms.NewListAliasesPaginator(conn, input) - err := conn.ListAliasesPagesWithContext(ctx, input, func(page *kms.ListAliasesOutput, lastPage bool) bool { - if page == nil { - return !lastPage + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + if err != nil { + return nil, err } for _, alias := range page.Aliases { - if aws.StringValue(alias.AliasName) == name { - output = alias - - return false + if aws.ToString(alias.AliasName) == name { + return &alias, nil } } - - return !lastPage - }) - - if err != nil { - return nil, err - } - - if output == nil { - return nil, &retry.NotFoundError{} } - return output, nil + return nil, &retry.NotFoundError{} } -func FindCustomKeyStoreByID(ctx context.Context, conn *kms.KMS, in *kms.DescribeCustomKeyStoresInput) (*kms.CustomKeyStoresListEntry, error) { - out, err := conn.DescribeCustomKeyStoresWithContext(ctx, in) +func FindCustomKeyStoreByID(ctx context.Context, conn *kms.Client, in *kms.DescribeCustomKeyStoresInput) (*awstypes.CustomKeyStoresListEntry, error) { + out, err := conn.DescribeCustomKeyStores(ctx, in) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeCustomKeyStoreNotFoundException) { + if errs.IsA[*awstypes.CustomKeyStoreNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: in, @@ -59,21 +49,21 @@ func FindCustomKeyStoreByID(ctx context.Context, conn *kms.KMS, in *kms.Describe return nil, err } - if out == nil || out.CustomKeyStores[0] == nil { + if out == nil || len(out.CustomKeyStores) == 0 { return nil, tfresource.NewEmptyResultError(in) } - return out.CustomKeyStores[0], nil + return &out.CustomKeyStores[0], nil } -func FindKeyByID(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMetadata, error) { +func FindKeyByID(ctx context.Context, conn *kms.Client, id string) (*awstypes.KeyMetadata, error) { input := &kms.DescribeKeyInput{ KeyId: aws.String(id), } - output, err := conn.DescribeKeyWithContext(ctx, input) + output, err := conn.DescribeKey(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -91,9 +81,9 @@ func FindKeyByID(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMetadat keyMetadata := output.KeyMetadata // Once the CMK is in the pending (replica) deletion state Terraform considers it logically deleted. - if state := aws.StringValue(keyMetadata.KeyState); state == kms.KeyStatePendingDeletion || state == kms.KeyStatePendingReplicaDeletion { + if state := keyMetadata.KeyState; state == awstypes.KeyStatePendingDeletion || state == awstypes.KeyStatePendingReplicaDeletion { return nil, &retry.NotFoundError{ - Message: state, + Message: string(state), LastRequest: input, } } @@ -109,18 +99,18 @@ func findDefaultKey(ctx context.Context, client *conns.AWSClient, service, regio return "", fmt.Errorf("finding default key: %s", err) } - return aws.StringValue(k.Arn), nil + return aws.ToString(k.Arn), nil } -func FindKeyPolicyByKeyIDAndPolicyName(ctx context.Context, conn *kms.KMS, keyID, policyName string) (*string, error) { +func FindKeyPolicyByKeyIDAndPolicyName(ctx context.Context, conn *kms.Client, keyID, policyName string) (*string, error) { input := &kms.GetKeyPolicyInput{ KeyId: aws.String(keyID), PolicyName: aws.String(policyName), } - output, err := conn.GetKeyPolicyWithContext(ctx, input) + output, err := conn.GetKeyPolicy(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -138,14 +128,14 @@ func FindKeyPolicyByKeyIDAndPolicyName(ctx context.Context, conn *kms.KMS, keyID return output.Policy, nil } -func FindKeyRotationEnabledByKeyID(ctx context.Context, conn *kms.KMS, keyID string) (*bool, error) { +func FindKeyRotationEnabledByKeyID(ctx context.Context, conn *kms.Client, keyID string) (*bool, error) { input := &kms.GetKeyRotationStatusInput{ KeyId: aws.String(keyID), } - output, err := conn.GetKeyRotationStatusWithContext(ctx, input) + output, err := conn.GetKeyRotationStatus(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -160,5 +150,5 @@ func FindKeyRotationEnabledByKeyID(ctx context.Context, conn *kms.KMS, keyID str return nil, tfresource.NewEmptyResultError(input) } - return output.KeyRotationEnabled, nil + return &output.KeyRotationEnabled, nil } diff --git a/internal/service/kms/generate.go b/internal/service/kms/generate.go index 9f3fb0d87fb..26cc1eb37f5 100644 --- a/internal/service/kms/generate.go +++ b/internal/service/kms/generate.go @@ -1,7 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -ListTags -ListTagsOp=ListResourceTags -ListTagsOpPaginated -ListTagsInIDElem=KeyId -ServiceTagsSlice -TagInIDElem=KeyId -TagTypeKeyElem=TagKey -TagTypeValElem=TagValue -UpdateTags -Wait -WaitContinuousOccurence 5 -WaitMinTimeout 1s -WaitTimeout 10m -ParentNotFoundErrCode=NotFoundException +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -KVTValues -ListTags -ListTagsOp=ListResourceTags -ListTagsOpPaginated -ListTagsInIDElem=KeyId -ServiceTagsSlice -TagInIDElem=KeyId -TagTypeKeyElem=TagKey -TagTypeValElem=TagValue -UpdateTags -Wait -WaitContinuousOccurence 5 -WaitMinTimeout 1s -WaitTimeout 10m -ParentNotFoundErrCode=NotFoundException //go:generate go run ../../generate/servicepackage/main.go // ONLY generate directives and package declaration! Do not add anything else to this file. diff --git a/internal/service/kms/grant.go b/internal/service/kms/grant.go index 91f24fc556d..07f5ca2ef9c 100644 --- a/internal/service/kms/grant.go +++ b/internal/service/kms/grant.go @@ -12,16 +12,18 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -114,8 +116,8 @@ func ResourceGrant() *schema.Resource { Required: true, ForceNew: true, Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.StringInSlice(kms.GrantOperation_Values(), false), + Type: schema.TypeString, + ValidateDiagFunc: enum.Validate[awstypes.GrantOperation](), }, }, "retire_on_delete": { @@ -139,13 +141,13 @@ func ResourceGrant() *schema.Resource { func resourceGrantCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID := d.Get("key_id").(string) input := &kms.CreateGrantInput{ GranteePrincipal: aws.String(d.Get("grantee_principal").(string)), KeyId: aws.String(keyID), - Operations: flex.ExpandStringSet(d.Get("operations").(*schema.Set)), + Operations: flex.ExpandStringyValueSet[awstypes.GrantOperation](d.Get("operations").(*schema.Set)), } if v, ok := d.GetOk("constraints"); ok && v.(*schema.Set).Len() > 0 { @@ -157,7 +159,7 @@ func resourceGrantCreate(ctx context.Context, d *schema.ResourceData, meta inter } if v, ok := d.GetOk("grant_creation_tokens"); ok && v.(*schema.Set).Len() > 0 { - input.GrantTokens = flex.ExpandStringSet(v.(*schema.Set)) + input.GrantTokens = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("name"); ok { @@ -171,16 +173,19 @@ func resourceGrantCreate(ctx context.Context, d *schema.ResourceData, meta inter // Error Codes: https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#KMS.CreateGrant // Under some circumstances a newly created IAM Role doesn't show up and causes // an InvalidArnException to be thrown. + var DependencyTimeoutException, InternalException, + InvalidARNException = &awstypes.DependencyTimeoutException{}, + &awstypes.KMSInternalException{}, &awstypes.InvalidArnException{} outputRaw, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, 3*time.Minute, func() (interface{}, error) { - return conn.CreateGrantWithContext(ctx, input) - }, kms.ErrCodeDependencyTimeoutException, kms.ErrCodeInternalException, kms.ErrCodeInvalidArnException) + return conn.CreateGrant(ctx, input) + }, DependencyTimeoutException.ErrorCode(), InternalException.ErrorCode(), InvalidARNException.ErrorCode()) if err != nil { return sdkdiag.AppendErrorf(diags, "creating KMS Grant for Key (%s): %s", keyID, err) } output := outputRaw.(*kms.CreateGrantOutput) - grantID := aws.StringValue(output.GrantId) + grantID := aws.ToString(output.GrantId) GrantCreateResourceID(keyID, grantID) d.SetId(GrantCreateResourceID(keyID, grantID)) d.Set("grant_token", output.GrantToken) @@ -193,7 +198,7 @@ func resourceGrantRead(ctx context.Context, d *schema.ResourceData, meta interfa timeout = 3 * time.Minute ) var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID, grantID, err := GrantParseResourceID(d.Id()) @@ -223,10 +228,10 @@ func resourceGrantRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("grantee_principal", grant.GranteePrincipal) } d.Set("key_id", keyID) - if aws.StringValue(grant.Name) != "" { + if aws.ToString(grant.Name) != "" { d.Set("name", grant.Name) } - d.Set("operations", aws.StringValueSlice(grant.Operations)) + d.Set("operations", flex.FlattenStringyValueList[awstypes.GrantOperation](grant.Operations)) if grant.RetiringPrincipal != nil { // nosemgrep:ci.helper-schema-ResourceData-Set-extraneous-nil-check d.Set("retiring_principal", grant.RetiringPrincipal) } @@ -236,7 +241,7 @@ func resourceGrantRead(ctx context.Context, d *schema.ResourceData, meta interfa func resourceGrantDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID, grantID, err := GrantParseResourceID(d.Id()) @@ -246,19 +251,19 @@ func resourceGrantDelete(ctx context.Context, d *schema.ResourceData, meta inter if d.Get("retire_on_delete").(bool) { log.Printf("[DEBUG] Retiring KMS Grant: %s", d.Id()) - _, err = conn.RetireGrantWithContext(ctx, &kms.RetireGrantInput{ + _, err = conn.RetireGrant(ctx, &kms.RetireGrantInput{ GrantId: aws.String(grantID), KeyId: aws.String(keyID), }) } else { log.Printf("[DEBUG] Revoking KMS Grant: %s", d.Id()) - _, err = conn.RevokeGrantWithContext(ctx, &kms.RevokeGrantInput{ + _, err = conn.RevokeGrant(ctx, &kms.RevokeGrantInput{ GrantId: aws.String(grantID), KeyId: aws.String(keyID), }) } - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } @@ -277,53 +282,32 @@ func resourceGrantDelete(ctx context.Context, d *schema.ResourceData, meta inter return diags } -func FindGrantByTwoPartKey(ctx context.Context, conn *kms.KMS, keyID, grantID string) (*kms.GrantListEntry, error) { +func FindGrantByTwoPartKey(ctx context.Context, conn *kms.Client, keyID, grantID string) (*awstypes.GrantListEntry, error) { input := &kms.ListGrantsInput{ KeyId: aws.String(keyID), - Limit: aws.Int64(100), + Limit: aws.Int32(100), } - var output *kms.GrantListEntry - err := conn.ListGrantsPagesWithContext(ctx, input, func(page *kms.ListGrantsResponse, lastPage bool) bool { - if page == nil { - return !lastPage + pages := kms.NewListGrantsPaginator(conn, input) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + if err != nil { + return nil, err } for _, v := range page.Grants { - if v == nil { - continue - } - - if aws.StringValue(v.GrantId) == grantID { - output = v - - return false + if aws.ToString(v.GrantId) == grantID { + return &v, nil } } - - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) } - return output, nil + return nil, tfresource.NewEmptyResultError(input) } -func findGrantByTwoPartKeyWithRetry(ctx context.Context, conn *kms.KMS, keyID, grantID string, timeout time.Duration) (*kms.GrantListEntry, error) { - var output *kms.GrantListEntry +func findGrantByTwoPartKeyWithRetry(ctx context.Context, conn *kms.Client, keyID, grantID string, timeout time.Duration) (*awstypes.GrantListEntry, error) { + var output *awstypes.GrantListEntry err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { grant, err := FindGrantByTwoPartKey(ctx, conn, keyID, grantID) @@ -336,13 +320,13 @@ func findGrantByTwoPartKeyWithRetry(ctx context.Context, conn *kms.KMS, keyID, g return retry.NonRetryableError(err) } - if principal := aws.StringValue(grant.GranteePrincipal); principal != "" { + if principal := aws.ToString(grant.GranteePrincipal); principal != "" { if !arn.IsARN(principal) && !verify.IsServicePrincipal(principal) { return retry.RetryableError(fmt.Errorf("grantee principal (%s) is invalid. Perhaps the principal has been deleted or recreated", principal)) } } - if principal := aws.StringValue(grant.RetiringPrincipal); principal != "" { + if principal := aws.ToString(grant.RetiringPrincipal); principal != "" { if !arn.IsARN(principal) && !verify.IsServicePrincipal(principal) { return retry.RetryableError(fmt.Errorf("retiring principal (%s) is invalid. Perhaps the principal has been deleted or recreated", principal)) } @@ -387,20 +371,20 @@ func grantConstraintsIsValid(constraints *schema.Set) bool { return constraintCount <= 1 } -func expandGrantConstraints(configured *schema.Set) *kms.GrantConstraints { +func expandGrantConstraints(configured *schema.Set) *awstypes.GrantConstraints { if len(configured.List()) < 1 { return nil } - var constraint kms.GrantConstraints + var constraint awstypes.GrantConstraints for _, raw := range configured.List() { data := raw.(map[string]interface{}) if contextEq, ok := data["encryption_context_equals"]; ok { - constraint.SetEncryptionContextEquals(flex.ExpandStringMap(contextEq.(map[string]interface{}))) + constraint.EncryptionContextEquals = flex.ExpandStringValueMap(contextEq.(map[string]interface{})) } if contextSub, ok := data["encryption_context_subset"]; ok { - constraint.SetEncryptionContextSubset(flex.ExpandStringMap(contextSub.(map[string]interface{}))) + constraint.EncryptionContextSubset = flex.ExpandStringValueMap(contextSub.(map[string]interface{})) } } @@ -452,7 +436,7 @@ func resourceGrantConstraintsHash(v interface{}) int { return create.StringHashcode(buf.String()) } -func flattenGrantConstraints(constraint *kms.GrantConstraints) *schema.Set { +func flattenGrantConstraints(constraint *awstypes.GrantConstraints) *schema.Set { constraints := schema.NewSet(resourceGrantConstraintsHash, []interface{}{}) if constraint == nil { return constraints @@ -461,12 +445,12 @@ func flattenGrantConstraints(constraint *kms.GrantConstraints) *schema.Set { m := make(map[string]interface{}) if constraint.EncryptionContextEquals != nil { if len(constraint.EncryptionContextEquals) > 0 { - m["encryption_context_equals"] = flex.FlattenStringMap(constraint.EncryptionContextEquals) + m["encryption_context_equals"] = constraint.EncryptionContextEquals } } if constraint.EncryptionContextSubset != nil { if len(constraint.EncryptionContextSubset) > 0 { - m["encryption_context_subset"] = flex.FlattenStringMap(constraint.EncryptionContextSubset) + m["encryption_context_subset"] = constraint.EncryptionContextSubset } } constraints.Add(m) diff --git a/internal/service/kms/grant_test.go b/internal/service/kms/grant_test.go index 017c43a5096..9211600d4eb 100644 --- a/internal/service/kms/grant_test.go +++ b/internal/service/kms/grant_test.go @@ -314,7 +314,7 @@ func TestAccKMSGrant_service(t *testing.T) { func testAccCheckGrantDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_kms_grant" { @@ -361,7 +361,7 @@ func testAccCheckGrantExists(ctx context.Context, n string) resource.TestCheckFu return err } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) _, err = tfkms.FindGrantByTwoPartKey(ctx, conn, keyID, grantID) diff --git a/internal/service/kms/key.go b/internal/service/kms/key.go index 648dc6bfaff..6797931defe 100644 --- a/internal/service/kms/key.go +++ b/internal/service/kms/key.go @@ -9,8 +9,9 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -19,8 +20,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/logging" + "github.com/hashicorp/terraform-provider-aws/internal/slices" 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" @@ -63,11 +67,11 @@ func ResourceKey() *schema.Resource { ValidateFunc: validation.StringLenBetween(1, 22), }, "customer_master_key_spec": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Default: kms.CustomerMasterKeySpecSymmetricDefault, - ValidateFunc: validation.StringInSlice(kms.CustomerMasterKeySpec_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: awstypes.CustomerMasterKeySpecSymmetricDefault, + ValidateDiagFunc: enum.Validate[awstypes.CustomerMasterKeySpec](), }, "deletion_window_in_days": { Type: schema.TypeInt, @@ -95,11 +99,11 @@ func ResourceKey() *schema.Resource { Computed: true, }, "key_usage": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Default: kms.KeyUsageTypeEncryptDecrypt, - ValidateFunc: validation.StringInSlice(kms.KeyUsageType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: awstypes.KeyUsageTypeEncryptDecrypt, + ValidateDiagFunc: enum.Validate[awstypes.KeyUsageType](), }, "multi_region": { Type: schema.TypeBool, @@ -134,12 +138,12 @@ func ResourceKey() *schema.Resource { func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) 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)), + BypassPolicyLockoutSafetyCheck: d.Get("bypass_policy_lockout_safety_check").(bool), + CustomerMasterKeySpec: awstypes.CustomerMasterKeySpec(d.Get("customer_master_key_spec").(string)), + KeyUsage: awstypes.KeyUsageType(d.Get("key_usage").(string)), Tags: getTagsIn(ctx), } @@ -161,12 +165,12 @@ func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interfa } if v, ok := d.GetOk("custom_key_store_id"); ok { - input.Origin = aws.String(kms.OriginTypeAwsCloudhsm) + input.Origin = awstypes.OriginTypeAwsCloudhsm input.CustomKeyStoreId = aws.String(v.(string)) } if v, ok := d.GetOk("xks_key_id"); ok { - input.Origin = aws.String(kms.OriginTypeExternalKeyStore) + input.Origin = awstypes.OriginTypeExternalKeyStore input.XksKeyId = aws.String(v.(string)) } @@ -175,14 +179,14 @@ func resourceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interfa // They acknowledge this here: // http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html output, err := WaitIAMPropagation(ctx, d.Timeout(schema.TimeoutCreate), func() (*kms.CreateKeyOutput, error) { - return conn.CreateKeyWithContext(ctx, input) + return conn.CreateKey(ctx, input) }) if err != nil { return sdkdiag.AppendErrorf(diags, "creating KMS Key: %s", err) } - d.SetId(aws.StringValue(output.KeyMetadata.KeyId)) + d.SetId(aws.ToString(output.KeyMetadata.KeyId)) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -216,7 +220,7 @@ 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(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -231,8 +235,8 @@ func resourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interface return sdkdiag.AppendErrorf(diags, "reading KMS Key (%s): %s", d.Id(), err) } - if aws.BoolValue(key.metadata.MultiRegion) && - aws.StringValue(key.metadata.MultiRegionConfiguration.MultiRegionKeyType) != kms.MultiRegionKeyTypePrimary { + if aws.ToBool(key.metadata.MultiRegion) && + key.metadata.MultiRegionConfiguration.MultiRegionKeyType != awstypes.MultiRegionKeyTypePrimary { return sdkdiag.AppendErrorf(diags, "KMS Key (%s) is not a multi-Region primary key", d.Id()) } @@ -259,14 +263,14 @@ func resourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interface d.Set("policy", policyToSet) - setTagsOut(ctx, key.tags) + setTagsOut(ctx, slices.Values(key.tags)) return diags } func resourceKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -307,7 +311,7 @@ func resourceKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interfa func resourceKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -316,17 +320,18 @@ func resourceKeyDelete(ctx context.Context, d *schema.ResourceData, meta interfa } if v, ok := d.GetOk("deletion_window_in_days"); ok { - input.PendingWindowInDays = aws.Int64(int64(v.(int))) + input.PendingWindowInDays = aws.Int32(int32(v.(int))) } log.Printf("[DEBUG] Deleting KMS Key: (%s)", d.Id()) - _, err := conn.ScheduleKeyDeletionWithContext(ctx, input) + _, err := conn.ScheduleKeyDeletion(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } - if tfawserr.ErrMessageContains(err, kms.ErrCodeInvalidStateException, "is pending deletion") { + var NotFoundException = awstypes.NotFoundException{} + if tfawserr.ErrMessageContains(err, NotFoundException.ErrorCode(), "is pending deletion") { return diags } @@ -342,13 +347,13 @@ func resourceKeyDelete(ctx context.Context, d *schema.ResourceData, meta interfa } type kmsKey struct { - metadata *kms.KeyMetadata + metadata *awstypes.KeyMetadata policy string rotation *bool - tags []*kms.Tag + tags []*awstypes.Tag } -func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource bool) (*kmsKey, error) { +func findKey(ctx context.Context, conn *kms.Client, keyID string, isNewResource bool) (*kmsKey, error) { // Wait for propagation since KMS is eventually consistent. outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, PropagationTimeout, func() (interface{}, error) { var err error @@ -366,13 +371,13 @@ func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource boo return nil, fmt.Errorf("reading KMS Key (%s) policy: %w", keyID, err) } - key.policy, err = structure.NormalizeJsonString(aws.StringValue(policy)) + key.policy, err = structure.NormalizeJsonString(aws.ToString(policy)) if err != nil { return nil, fmt.Errorf("policy contains invalid JSON: %w", err) } - if aws.StringValue(key.metadata.Origin) == kms.OriginTypeAwsKms { + if key.metadata.Origin == awstypes.OriginTypeAwsKms { key.rotation, err = FindKeyRotationEnabledByKeyID(ctx, conn, keyID) if err != nil { @@ -382,7 +387,7 @@ func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource boo tags, err := listTags(ctx, conn, keyID) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return nil, &retry.NotFoundError{LastError: err} } @@ -390,7 +395,7 @@ 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) + key.tags = slices.ToPointers(Tags(tags)) return &key, nil }, isNewResource) @@ -402,13 +407,13 @@ func findKey(ctx context.Context, conn *kms.KMS, keyID string, isNewResource boo return outputRaw.(*kmsKey), nil } -func updateKeyDescription(ctx context.Context, conn *kms.KMS, keyID string, description string) error { +func updateKeyDescription(ctx context.Context, conn *kms.Client, keyID string, description string) error { input := &kms.UpdateKeyDescriptionInput{ Description: aws.String(description), KeyId: aws.String(keyID), } - _, err := conn.UpdateKeyDescriptionWithContext(ctx, input) + _, err := conn.UpdateKeyDescription(ctx, input) if err != nil { return fmt.Errorf("updating description: %w", err) } @@ -422,7 +427,7 @@ func updateKeyDescription(ctx context.Context, conn *kms.KMS, keyID string, desc return nil } -func updateKeyEnabled(ctx context.Context, conn *kms.KMS, keyID string, enabled bool) error { +func updateKeyEnabled(ctx context.Context, conn *kms.Client, keyID string, enabled bool) error { var action string updateFunc := func() (interface{}, error) { @@ -431,13 +436,13 @@ func updateKeyEnabled(ctx context.Context, conn *kms.KMS, keyID string, enabled if enabled { log.Printf("[DEBUG] Enabling KMS Key (%s)", keyID) action = "enabling" - _, err = conn.EnableKeyWithContext(ctx, &kms.EnableKeyInput{ + _, err = conn.EnableKey(ctx, &kms.EnableKeyInput{ KeyId: aws.String(keyID), }) } else { log.Printf("[DEBUG] Disabling KMS Key (%s)", keyID) action = "disabling" - _, err = conn.DisableKeyWithContext(ctx, &kms.DisableKeyInput{ + _, err = conn.DisableKey(ctx, &kms.DisableKeyInput{ KeyId: aws.String(keyID), }) } @@ -445,7 +450,8 @@ func updateKeyEnabled(ctx context.Context, conn *kms.KMS, keyID string, enabled return nil, err } - _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, PropagationTimeout, updateFunc, kms.ErrCodeNotFoundException) + var NotFoundException = awstypes.NotFoundException{} + _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, PropagationTimeout, updateFunc, NotFoundException.ErrorCode()) if err != nil { return fmt.Errorf("%s KMS Key: %w", action, err) } @@ -460,7 +466,7 @@ func updateKeyEnabled(ctx context.Context, conn *kms.KMS, keyID string, enabled return nil } -func updateKeyPolicy(ctx context.Context, conn *kms.KMS, keyID string, policy string, bypassPolicyLockoutSafetyCheck bool) error { +func updateKeyPolicy(ctx context.Context, conn *kms.Client, keyID string, policy string, bypassPolicyLockoutSafetyCheck bool) error { policy, err := structure.NormalizeJsonString(policy) if err != nil { return fmt.Errorf("policy contains invalid JSON: %w", err) @@ -470,18 +476,19 @@ func updateKeyPolicy(ctx context.Context, conn *kms.KMS, keyID string, policy st var err error input := &kms.PutKeyPolicyInput{ - BypassPolicyLockoutSafetyCheck: aws.Bool(bypassPolicyLockoutSafetyCheck), + BypassPolicyLockoutSafetyCheck: bypassPolicyLockoutSafetyCheck, KeyId: aws.String(keyID), Policy: aws.String(policy), PolicyName: aws.String(PolicyNameDefault), } - _, err = conn.PutKeyPolicyWithContext(ctx, input) + _, err = conn.PutKeyPolicy(ctx, input) return nil, err } - _, err = tfresource.RetryWhenAWSErrCodeEquals(ctx, PropagationTimeout, updateFunc, kms.ErrCodeNotFoundException, kms.ErrCodeMalformedPolicyDocumentException) + var NotFoundException, MalformedPolicyDocumentException = awstypes.NotFoundException{}, awstypes.MalformedPolicyDocumentException{} + _, err = tfresource.RetryWhenAWSErrCodeEquals(ctx, PropagationTimeout, updateFunc, NotFoundException.ErrorCode(), MalformedPolicyDocumentException.ErrorCode()) if err != nil { return fmt.Errorf("updating policy: %w", err) } @@ -495,7 +502,7 @@ func updateKeyPolicy(ctx context.Context, conn *kms.KMS, keyID string, policy st return nil } -func updateKeyRotationEnabled(ctx context.Context, conn *kms.KMS, keyID string, enabled bool) error { +func updateKeyRotationEnabled(ctx context.Context, conn *kms.Client, keyID string, enabled bool) error { var action string updateFunc := func() (interface{}, error) { @@ -503,12 +510,12 @@ func updateKeyRotationEnabled(ctx context.Context, conn *kms.KMS, keyID string, if enabled { log.Printf("[DEBUG] Enabling KMS Key (%s) key rotation", keyID) - _, err = conn.EnableKeyRotationWithContext(ctx, &kms.EnableKeyRotationInput{ + _, err = conn.EnableKeyRotation(ctx, &kms.EnableKeyRotationInput{ KeyId: aws.String(keyID), }) } else { log.Printf("[DEBUG] Disabling KMS Key (%s) key rotation", keyID) - _, err = conn.DisableKeyRotationWithContext(ctx, &kms.DisableKeyRotationInput{ + _, err = conn.DisableKeyRotation(ctx, &kms.DisableKeyRotationInput{ KeyId: aws.String(keyID), }) } @@ -516,7 +523,8 @@ func updateKeyRotationEnabled(ctx context.Context, conn *kms.KMS, keyID string, return nil, err } - _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, KeyRotationUpdatedTimeout, updateFunc, kms.ErrCodeNotFoundException, kms.ErrCodeDisabledException) + var NotFoundException, DisabledException = awstypes.NotFoundException{}, awstypes.DisabledException{} + _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, KeyRotationUpdatedTimeout, updateFunc, NotFoundException.ErrorCode(), DisabledException.ErrorCode()) if err != nil { return fmt.Errorf("%s key rotation: %w", action, err) } diff --git a/internal/service/kms/key_data_source.go b/internal/service/kms/key_data_source.go index f538a51690e..69d1569f168 100644 --- a/internal/service/kms/key_data_source.go +++ b/internal/service/kms/key_data_source.go @@ -7,8 +7,9 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -165,7 +166,7 @@ func DataSourceKey() *schema.Resource { func dataSourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID := d.Get("key_id").(string) input := &kms.DescribeKeyInput{ @@ -173,25 +174,25 @@ func dataSourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interfa } if v, ok := d.GetOk("grant_tokens"); ok && len(v.([]interface{})) > 0 { - input.GrantTokens = flex.ExpandStringList(v.([]interface{})) + input.GrantTokens = flex.ExpandStringValueList(v.([]interface{})) } - output, err := conn.DescribeKeyWithContext(ctx, input) + output, err := conn.DescribeKey(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading KMS Key (%s): %s", keyID, err) } keyMetadata := output.KeyMetadata - d.SetId(aws.StringValue(keyMetadata.KeyId)) + d.SetId(aws.ToString(keyMetadata.KeyId)) d.Set("arn", keyMetadata.Arn) d.Set("aws_account_id", keyMetadata.AWSAccountId) d.Set("cloud_hsm_cluster_id", keyMetadata.CloudHsmClusterId) - d.Set("creation_date", aws.TimeValue(keyMetadata.CreationDate).Format(time.RFC3339)) - d.Set("customer_master_key_spec", keyMetadata.CustomerMasterKeySpec) + d.Set("creation_date", aws.ToTime(keyMetadata.CreationDate).Format(time.RFC3339)) + d.Set("customer_master_key_spec", keyMetadata.KeySpec) d.Set("custom_key_store_id", keyMetadata.CustomKeyStoreId) if keyMetadata.DeletionDate != nil { - d.Set("deletion_date", aws.TimeValue(keyMetadata.DeletionDate).Format(time.RFC3339)) + d.Set("deletion_date", aws.ToTime(keyMetadata.DeletionDate).Format(time.RFC3339)) } d.Set("description", keyMetadata.Description) d.Set("enabled", keyMetadata.Enabled) @@ -211,7 +212,7 @@ func dataSourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("origin", keyMetadata.Origin) d.Set("pending_deletion_window_in_days", keyMetadata.PendingDeletionWindowInDays) if keyMetadata.ValidTo != nil { - d.Set("valid_to", aws.TimeValue(keyMetadata.ValidTo).Format(time.RFC3339)) + d.Set("valid_to", aws.ToTime(keyMetadata.ValidTo).Format(time.RFC3339)) } if keyMetadata.XksKeyConfiguration != nil { if err := d.Set("xks_key_configuration", []interface{}{flattenXksKeyConfigurationType(keyMetadata.XksKeyConfiguration)}); err != nil { @@ -224,19 +225,16 @@ func dataSourceKeyRead(ctx context.Context, d *schema.ResourceData, meta interfa return diags } -func flattenMultiRegionConfiguration(apiObject *kms.MultiRegionConfiguration) map[string]interface{} { +func flattenMultiRegionConfiguration(apiObject *awstypes.MultiRegionConfiguration) map[string]interface{} { if apiObject == nil { return nil } tfMap := map[string]interface{}{} - - if v := apiObject.MultiRegionKeyType; v != nil { - tfMap["multi_region_key_type"] = aws.StringValue(v) - } + tfMap["multi_region_key_type"] = apiObject.MultiRegionKeyType if v := apiObject.PrimaryKey; v != nil { - tfMap["primary_key"] = []interface{}{flattenMultiRegionKey(v)} + tfMap["primary_key"] = []interface{}{flattenMultiRegionKey(*v)} } if v := apiObject.ReplicaKeys; v != nil { @@ -246,25 +244,21 @@ func flattenMultiRegionConfiguration(apiObject *kms.MultiRegionConfiguration) ma return tfMap } -func flattenMultiRegionKey(apiObject *kms.MultiRegionKey) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenMultiRegionKey(apiObject awstypes.MultiRegionKey) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.Arn; v != nil { - tfMap["arn"] = aws.StringValue(v) + tfMap["arn"] = aws.ToString(v) } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.StringValue(v) + tfMap["region"] = aws.ToString(v) } return tfMap } -func flattenMultiRegionKeys(apiObjects []*kms.MultiRegionKey) []interface{} { +func flattenMultiRegionKeys(apiObjects []awstypes.MultiRegionKey) []interface{} { if len(apiObjects) == 0 { return nil } @@ -272,17 +266,13 @@ func flattenMultiRegionKeys(apiObjects []*kms.MultiRegionKey) []interface{} { var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenMultiRegionKey(apiObject)) } return tfList } -func flattenXksKeyConfigurationType(apiObject *kms.XksKeyConfigurationType) map[string]interface{} { +func flattenXksKeyConfigurationType(apiObject *awstypes.XksKeyConfigurationType) map[string]interface{} { if apiObject == nil { return nil } @@ -290,7 +280,7 @@ func flattenXksKeyConfigurationType(apiObject *kms.XksKeyConfigurationType) map[ tfMap := map[string]interface{}{} if v := apiObject.Id; v != nil { - tfMap["id"] = aws.StringValue(v) + tfMap["id"] = aws.ToString(v) } return tfMap diff --git a/internal/service/kms/key_policy.go b/internal/service/kms/key_policy.go index d6ecefa65cf..3d3e46fe763 100644 --- a/internal/service/kms/key_policy.go +++ b/internal/service/kms/key_policy.go @@ -57,7 +57,7 @@ func ResourceKeyPolicy() *schema.Resource { func resourceKeyPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyID := d.Get("key_id").(string) @@ -72,7 +72,7 @@ func resourceKeyPolicyCreate(ctx context.Context, d *schema.ResourceData, meta i func resourceKeyPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) key, err := findKey(ctx, conn, d.Id(), d.IsNewResource()) @@ -99,7 +99,7 @@ func resourceKeyPolicyRead(ctx context.Context, d *schema.ResourceData, meta int func resourceKeyPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) if d.HasChange("policy") { if err := updateKeyPolicy(ctx, conn, d.Id(), d.Get("policy").(string), d.Get("bypass_policy_lockout_safety_check").(bool)); err != nil { @@ -112,7 +112,7 @@ func resourceKeyPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta i func resourceKeyPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) if !d.Get("bypass_policy_lockout_safety_check").(bool) { if err := updateKeyPolicy(ctx, conn, d.Get("key_id").(string), meta.(*conns.AWSClient).DefaultKMSKeyPolicy(ctx), d.Get("bypass_policy_lockout_safety_check").(bool)); err != nil { diff --git a/internal/service/kms/key_policy_test.go b/internal/service/kms/key_policy_test.go index b5a8a5e746f..13d472193c6 100644 --- a/internal/service/kms/key_policy_test.go +++ b/internal/service/kms/key_policy_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -18,7 +18,7 @@ import ( func TestAccKMSKeyPolicy_basic(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" attachmentResourceName := "aws_kms_key_policy.test" @@ -55,7 +55,7 @@ func TestAccKMSKeyPolicy_basic(t *testing.T) { func TestAccKMSKeyPolicy_disappears(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) attachmentResourceName := "aws_kms_key_policy.test" resource.ParallelTest(t, resource.TestCase{ @@ -78,7 +78,7 @@ func TestAccKMSKeyPolicy_disappears(t *testing.T) { func TestAccKMSKeyPolicy_bypass(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" attachmentResourceName := "aws_kms_key_policy.test" @@ -112,7 +112,7 @@ func TestAccKMSKeyPolicy_bypass(t *testing.T) { func TestAccKMSKeyPolicy_bypassUpdate(t *testing.T) { ctx := acctest.Context(t) - var before, after kms.KeyMetadata + var before, after awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" attachmentResourceName := "aws_kms_key_policy.test" @@ -143,7 +143,7 @@ func TestAccKMSKeyPolicy_bypassUpdate(t *testing.T) { func TestAccKMSKeyPolicy_keyIsEnabled(t *testing.T) { ctx := acctest.Context(t) - var before, after kms.KeyMetadata + var before, after awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" @@ -171,7 +171,7 @@ func TestAccKMSKeyPolicy_keyIsEnabled(t *testing.T) { func TestAccKMSKeyPolicy_iamRole(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" @@ -199,7 +199,7 @@ func TestAccKMSKeyPolicy_iamRole(t *testing.T) { func TestAccKMSKeyPolicy_iamRoleUpdate(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" @@ -228,7 +228,7 @@ func TestAccKMSKeyPolicy_iamRoleUpdate(t *testing.T) { // // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/11801 func TestAccKMSKeyPolicy_iamRoleOrder(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" @@ -272,7 +272,7 @@ func TestAccKMSKeyPolicy_iamRoleOrder(t *testing.T) { // // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/7646 func TestAccKMSKeyPolicy_iamServiceLinkedRole(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" @@ -300,7 +300,7 @@ func TestAccKMSKeyPolicy_iamServiceLinkedRole(t *testing.T) { func TestAccKMSKeyPolicy_booleanCondition(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) keyResourceName := "aws_kms_key.test" diff --git a/internal/service/kms/key_test.go b/internal/service/kms/key_test.go index b6a15c24b20..56c1aac9d4c 100644 --- a/internal/service/kms/key_test.go +++ b/internal/service/kms/key_test.go @@ -9,8 +9,9 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" awspolicy "github.com/hashicorp/awspolicyequivalence" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -24,7 +25,7 @@ import ( func TestAccKMSKey_basic(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata resourceName := "aws_kms_key.test" resource.ParallelTest(t, resource.TestCase{ @@ -62,7 +63,7 @@ func TestAccKMSKey_basic(t *testing.T) { func TestAccKMSKey_disappears(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -86,7 +87,7 @@ func TestAccKMSKey_disappears(t *testing.T) { func TestAccKMSKey_multiRegion(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -115,7 +116,7 @@ func TestAccKMSKey_multiRegion(t *testing.T) { func TestAccKMSKey_asymmetricKey(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -139,7 +140,7 @@ func TestAccKMSKey_asymmetricKey(t *testing.T) { func TestAccKMSKey_hmacKey(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -163,7 +164,7 @@ func TestAccKMSKey_hmacKey(t *testing.T) { func TestAccKMSKey_Policy_basic(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" expectedPolicyText := fmt.Sprintf(`{"Version":"2012-10-17","Id":%[1]q,"Statement":[{"Sid":"Enable IAM User Permissions","Effect":"Allow","Principal":{"AWS":"*"},"Action":"kms:*","Resource":"*"}]}`, rName) @@ -199,7 +200,7 @@ func TestAccKMSKey_Policy_basic(t *testing.T) { func TestAccKMSKey_Policy_bypass(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -232,7 +233,7 @@ func TestAccKMSKey_Policy_bypass(t *testing.T) { func TestAccKMSKey_Policy_bypassUpdate(t *testing.T) { ctx := acctest.Context(t) - var before, after kms.KeyMetadata + var before, after awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -262,7 +263,7 @@ func TestAccKMSKey_Policy_bypassUpdate(t *testing.T) { func TestAccKMSKey_Policy_iamRole(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -290,7 +291,7 @@ func TestAccKMSKey_Policy_iamRole(t *testing.T) { func TestAccKMSKey_Policy_iamRoleUpdate(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -319,7 +320,7 @@ func TestAccKMSKey_Policy_iamRoleUpdate(t *testing.T) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/11801 func TestAccKMSKey_Policy_iamRoleOrder(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -363,7 +364,7 @@ func TestAccKMSKey_Policy_iamRoleOrder(t *testing.T) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/7646 func TestAccKMSKey_Policy_iamServiceLinkedRole(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -391,7 +392,7 @@ func TestAccKMSKey_Policy_iamServiceLinkedRole(t *testing.T) { func TestAccKMSKey_Policy_booleanCondition(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -413,7 +414,7 @@ func TestAccKMSKey_Policy_booleanCondition(t *testing.T) { func TestAccKMSKey_isEnabled(t *testing.T) { ctx := acctest.Context(t) - var key1, key2, key3 kms.KeyMetadata + var key1, key2, key3 awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -459,7 +460,7 @@ func TestAccKMSKey_isEnabled(t *testing.T) { func TestAccKMSKey_tags(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -520,7 +521,7 @@ func TestAccKMSKey_tags(t *testing.T) { // https://github.com/hashicorp/terraform-provider-aws/issues/26174. func TestAccKMSKey_ignoreTags(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -562,7 +563,7 @@ func TestAccKMSKey_ignoreTags(t *testing.T) { // https://github.com/hashicorp/terraform-provider-aws/issues/33219. func TestAccKMSKey_updateTagsEmptyValue(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_key.test" @@ -605,9 +606,9 @@ func testAccCheckKeyHasPolicy(ctx context.Context, name string, expectedPolicyTe return fmt.Errorf("No KMS Key ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) - out, err := conn.GetKeyPolicyWithContext(ctx, &kms.GetKeyPolicyInput{ + out, err := conn.GetKeyPolicy(ctx, &kms.GetKeyPolicyInput{ KeyId: aws.String(rs.Primary.ID), PolicyName: aws.String("default"), }) @@ -615,7 +616,7 @@ func testAccCheckKeyHasPolicy(ctx context.Context, name string, expectedPolicyTe return err } - actualPolicyText := aws.StringValue(out.Policy) + actualPolicyText := aws.ToString(out.Policy) equivalent, err := awspolicy.PoliciesAreEquivalent(actualPolicyText, expectedPolicyText) if err != nil { @@ -632,7 +633,7 @@ func testAccCheckKeyHasPolicy(ctx context.Context, name string, expectedPolicyTe func testAccCheckKeyDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_kms_key" { @@ -656,7 +657,7 @@ func testAccCheckKeyDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckKeyExists(ctx context.Context, name string, key *kms.KeyMetadata) resource.TestCheckFunc { +func testAccCheckKeyExists(ctx context.Context, name string, key *awstypes.KeyMetadata) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -667,7 +668,7 @@ func testAccCheckKeyExists(ctx context.Context, name string, key *kms.KeyMetadat return fmt.Errorf("No KMS Key ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) outputRaw, err := tfresource.RetryWhenNotFound(ctx, tfkms.PropagationTimeout, func() (interface{}, error) { return tfkms.FindKeyByID(ctx, conn, rs.Primary.ID) @@ -677,25 +678,25 @@ func testAccCheckKeyExists(ctx context.Context, name string, key *kms.KeyMetadat return err } - *key = *(outputRaw.(*kms.KeyMetadata)) + *key = *(outputRaw.(*awstypes.KeyMetadata)) return nil } } -func testAccCheckKeyAddTag(ctx context.Context, key *kms.KeyMetadata, tagKey, tagValue string) resource.TestCheckFunc { +func testAccCheckKeyAddTag(ctx context.Context, key *awstypes.KeyMetadata, tagKey, tagValue string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) input := &kms.TagResourceInput{ KeyId: key.KeyId, - Tags: []*kms.Tag{{ + Tags: []awstypes.Tag{{ TagKey: aws.String(tagKey), TagValue: aws.String(tagValue), }}, } - _, err := conn.TagResourceWithContext(ctx, input) + _, err := conn.TagResource(ctx, input) return err } diff --git a/internal/service/kms/public_key_data_source.go b/internal/service/kms/public_key_data_source.go index 17cd5c8feb9..946f1e78e78 100644 --- a/internal/service/kms/public_key_data_source.go +++ b/internal/service/kms/public_key_data_source.go @@ -7,8 +7,8 @@ import ( "context" "encoding/pem" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -68,7 +68,7 @@ func DataSourcePublicKey() *schema.Resource { func dataSourcePublicKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyId := d.Get("key_id").(string) input := &kms.GetPublicKeyInput{ @@ -76,16 +76,16 @@ func dataSourcePublicKeyRead(ctx context.Context, d *schema.ResourceData, meta i } if v, ok := d.GetOk("grant_tokens"); ok { - input.GrantTokens = aws.StringSlice(v.([]string)) + input.GrantTokens = v.([]string) } - output, err := conn.GetPublicKeyWithContext(ctx, input) + output, err := conn.GetPublicKey(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "while describing KMS public key (%s): %s", keyId, err) } - d.SetId(aws.StringValue(output.KeyId)) + d.SetId(aws.ToString(output.KeyId)) d.Set("arn", output.KeyId) d.Set("customer_master_key_spec", output.CustomerMasterKeySpec) @@ -96,11 +96,11 @@ func dataSourcePublicKeyRead(ctx context.Context, d *schema.ResourceData, meta i Bytes: output.PublicKey, }))) - if err := d.Set("encryption_algorithms", flex.FlattenStringList(output.EncryptionAlgorithms)); err != nil { + if err := d.Set("encryption_algorithms", flex.FlattenStringyValueList(output.EncryptionAlgorithms)); err != nil { return sdkdiag.AppendErrorf(diags, "setting encryption_algorithms: %s", err) } - if err := d.Set("signing_algorithms", flex.FlattenStringList(output.SigningAlgorithms)); err != nil { + if err := d.Set("signing_algorithms", flex.FlattenStringyValueList(output.SigningAlgorithms)); err != nil { return sdkdiag.AppendErrorf(diags, "setting signing_algorithms: %s", err) } diff --git a/internal/service/kms/replica_external_key.go b/internal/service/kms/replica_external_key.go index 527fa282595..df2505d55d5 100644 --- a/internal/service/kms/replica_external_key.go +++ b/internal/service/kms/replica_external_key.go @@ -9,17 +9,20 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/kms" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/logging" + "github.com/hashicorp/terraform-provider-aws/internal/slices" 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" @@ -115,7 +118,7 @@ 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(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) // e.g. arn:aws:kms:us-east-2:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab primaryKeyARN, err := arn.Parse(d.Get("primary_key_arn").(string)) @@ -131,7 +134,7 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat } if v, ok := d.GetOk("bypass_policy_lockout_safety_check"); ok { - input.BypassPolicyLockoutSafetyCheck = aws.Bool(v.(bool)) + input.BypassPolicyLockoutSafetyCheck = v.(bool) } if v, ok := d.GetOk("description"); ok { @@ -146,14 +149,14 @@ func resourceReplicaExternalKeyCreate(ctx context.Context, d *schema.ResourceDat replicateConn := meta.(*conns.AWSClient).KMSConnForRegion(ctx, primaryKeyARN.Region) output, err := WaitIAMPropagation(ctx, propagationTimeout, func() (*kms.ReplicateKeyOutput, error) { - return replicateConn.ReplicateKeyWithContext(ctx, input) + return replicateConn.ReplicateKey(ctx, input) }) if err != nil { return sdkdiag.AppendErrorf(diags, "creating KMS Replica External Key: %s", err) } - d.SetId(aws.StringValue(output.ReplicaKeyMetadata.KeyId)) + d.SetId(aws.ToString(output.ReplicaKeyMetadata.KeyId)) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -203,7 +206,7 @@ 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(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -218,16 +221,16 @@ func resourceReplicaExternalKeyRead(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "reading KMS External Replica Key (%s): %s", d.Id(), err) } - if keyManager := aws.StringValue(key.metadata.KeyManager); keyManager != kms.KeyManagerTypeCustomer { + if keyManager := key.metadata.KeyManager; keyManager != awstypes.KeyManagerTypeCustomer { return sdkdiag.AppendErrorf(diags, "KMS External Replica Key (%s) has invalid KeyManager: %s", d.Id(), keyManager) } - if origin := aws.StringValue(key.metadata.Origin); origin != kms.OriginTypeExternal { + if origin := key.metadata.Origin; origin != awstypes.OriginTypeExternal { return sdkdiag.AppendErrorf(diags, "KMS External Replica Key (%s) has invalid Origin: %s", d.Id(), origin) } - if !aws.BoolValue(key.metadata.MultiRegion) || - aws.StringValue(key.metadata.MultiRegionConfiguration.MultiRegionKeyType) != kms.MultiRegionKeyTypeReplica { + if !aws.ToBool(key.metadata.MultiRegion) || + key.metadata.MultiRegionConfiguration.MultiRegionKeyType != awstypes.MultiRegionKeyTypeReplica { return sdkdiag.AppendErrorf(diags, "KMS External Replica Key (%s) is not a multi-Region replica key", d.Id()) } @@ -249,23 +252,23 @@ func resourceReplicaExternalKeyRead(ctx context.Context, d *schema.ResourceData, d.Set("primary_key_arn", key.metadata.MultiRegionConfiguration.PrimaryKey.Arn) if key.metadata.ValidTo != nil { - d.Set("valid_to", aws.TimeValue(key.metadata.ValidTo).Format(time.RFC3339)) + d.Set("valid_to", aws.ToTime(key.metadata.ValidTo).Format(time.RFC3339)) } else { d.Set("valid_to", nil) } - setTagsOut(ctx, key.tags) + setTagsOut(ctx, slices.Values(key.tags)) return diags } func resourceReplicaExternalKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) - if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && enabled && state != kms.KeyStatePendingImport { + if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && enabled && awstypes.KeyState(state) != awstypes.KeyStatePendingImport { // Enable before any attributes are modified. if err := updateKeyEnabled(ctx, conn, d.Id(), enabled); err != nil { return sdkdiag.AppendErrorf(diags, "updating KMS Replica External Key (%s): %s", d.Id(), err) @@ -300,7 +303,7 @@ func resourceReplicaExternalKeyUpdate(ctx context.Context, d *schema.ResourceDat } } - if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && !enabled && state != kms.KeyStatePendingImport { + if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && !enabled && awstypes.KeyState(state) != awstypes.KeyStatePendingImport { // Only disable after all attributes have been modified because we cannot modify disabled keys. if err := updateKeyEnabled(ctx, conn, d.Id(), enabled); err != nil { return sdkdiag.AppendErrorf(diags, "updating KMS Replica External Key (%s): %s", d.Id(), err) @@ -312,7 +315,7 @@ func resourceReplicaExternalKeyUpdate(ctx context.Context, d *schema.ResourceDat func resourceReplicaExternalKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -321,17 +324,18 @@ func resourceReplicaExternalKeyDelete(ctx context.Context, d *schema.ResourceDat } if v, ok := d.GetOk("deletion_window_in_days"); ok { - input.PendingWindowInDays = aws.Int64(int64(v.(int))) + input.PendingWindowInDays = aws.Int32(int32(v.(int))) } log.Printf("[DEBUG] Deleting KMS Replica External Key: (%s)", d.Id()) - _, err := conn.ScheduleKeyDeletionWithContext(ctx, input) + _, err := conn.ScheduleKeyDeletion(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } - if tfawserr.ErrMessageContains(err, kms.ErrCodeInvalidStateException, "is pending deletion") { + var InvalidStateException = awstypes.KMSInvalidStateException{} + if tfawserr.ErrMessageContains(err, InvalidStateException.ErrorCode(), "is pending deletion") { return diags } diff --git a/internal/service/kms/replica_external_key_test.go b/internal/service/kms/replica_external_key_test.go index 34b9dfe9930..45b5cd6466a 100644 --- a/internal/service/kms/replica_external_key_test.go +++ b/internal/service/kms/replica_external_key_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -17,7 +17,7 @@ import ( func TestAccKMSReplicaExternalKey_basic(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) primaryKeyResourceName := "aws_kms_external_key.test" resourceName := "aws_kms_replica_external_key.test" @@ -66,7 +66,7 @@ func TestAccKMSReplicaExternalKey_basic(t *testing.T) { func TestAccKMSReplicaExternalKey_descriptionAndEnabled(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rName3 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -122,7 +122,7 @@ func TestAccKMSReplicaExternalKey_descriptionAndEnabled(t *testing.T) { func TestAccKMSReplicaExternalKey_policy(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_replica_external_key.test" policy1 := `{"Id":"kms-tf-1","Statement":[{"Action":"kms:*","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*","Sid":"Enable IAM User Permissions 1"}],"Version":"2012-10-17"}` @@ -169,7 +169,7 @@ func TestAccKMSReplicaExternalKey_policy(t *testing.T) { func TestAccKMSReplicaExternalKey_tags(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_replica_external_key.test" diff --git a/internal/service/kms/replica_key.go b/internal/service/kms/replica_key.go index ccd71f4f940..2c72e74d380 100644 --- a/internal/service/kms/replica_key.go +++ b/internal/service/kms/replica_key.go @@ -8,17 +8,20 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/kms" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/logging" + "github.com/hashicorp/terraform-provider-aws/internal/slices" 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" @@ -103,7 +106,7 @@ func ResourceReplicaKey() *schema.Resource { func resourceReplicaKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) // e.g. arn:aws:kms:us-east-2:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab primaryKeyARN, err := arn.Parse(d.Get("primary_key_arn").(string)) @@ -119,7 +122,7 @@ func resourceReplicaKeyCreate(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("bypass_policy_lockout_safety_check"); ok { - input.BypassPolicyLockoutSafetyCheck = aws.Bool(v.(bool)) + input.BypassPolicyLockoutSafetyCheck = v.(bool) } if v, ok := d.GetOk("description"); ok { @@ -134,14 +137,14 @@ func resourceReplicaKeyCreate(ctx context.Context, d *schema.ResourceData, meta replicateConn := meta.(*conns.AWSClient).KMSConnForRegion(ctx, primaryKeyARN.Region) output, err := WaitIAMPropagation(ctx, propagationTimeout, func() (*kms.ReplicateKeyOutput, error) { - return replicateConn.ReplicateKeyWithContext(ctx, input) + return replicateConn.ReplicateKey(ctx, input) }) if err != nil { return sdkdiag.AppendErrorf(diags, "creating KMS Replica Key: %s", err) } - d.SetId(aws.StringValue(output.ReplicaKeyMetadata.KeyId)) + d.SetId(aws.ToString(output.ReplicaKeyMetadata.KeyId)) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -175,7 +178,7 @@ func resourceReplicaKeyCreate(ctx context.Context, d *schema.ResourceData, meta func resourceReplicaKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -190,16 +193,16 @@ func resourceReplicaKeyRead(ctx context.Context, d *schema.ResourceData, meta in return sdkdiag.AppendErrorf(diags, "reading KMS Replica Key (%s): %s", d.Id(), err) } - if keyManager := aws.StringValue(key.metadata.KeyManager); keyManager != kms.KeyManagerTypeCustomer { + if keyManager := key.metadata.KeyManager; keyManager != awstypes.KeyManagerTypeCustomer { return sdkdiag.AppendErrorf(diags, "KMS Replica Key (%s) has invalid KeyManager: %s", d.Id(), keyManager) } - if origin := aws.StringValue(key.metadata.Origin); origin != kms.OriginTypeAwsKms { + if origin := key.metadata.Origin; origin != awstypes.OriginTypeAwsKms { return sdkdiag.AppendErrorf(diags, "KMS Replica Key (%s) has invalid Origin: %s", d.Id(), origin) } - if !aws.BoolValue(key.metadata.MultiRegion) || - aws.StringValue(key.metadata.MultiRegionConfiguration.MultiRegionKeyType) != kms.MultiRegionKeyTypeReplica { + if !aws.ToBool(key.metadata.MultiRegion) || + key.metadata.MultiRegionConfiguration.MultiRegionKeyType != awstypes.MultiRegionKeyTypeReplica { return sdkdiag.AppendErrorf(diags, "KMS Replica Key (%s) is not a multi-Region replica key", d.Id()) } @@ -220,14 +223,14 @@ func resourceReplicaKeyRead(ctx context.Context, d *schema.ResourceData, meta in d.Set("policy", policyToSet) d.Set("primary_key_arn", key.metadata.MultiRegionConfiguration.PrimaryKey.Arn) - setTagsOut(ctx, key.tags) + setTagsOut(ctx, slices.Values(key.tags)) return diags } func resourceReplicaKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -262,7 +265,7 @@ func resourceReplicaKeyUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceReplicaKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -271,17 +274,17 @@ func resourceReplicaKeyDelete(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("deletion_window_in_days"); ok { - input.PendingWindowInDays = aws.Int64(int64(v.(int))) + input.PendingWindowInDays = aws.Int32(int32(v.(int))) } log.Printf("[DEBUG] Deleting KMS Replica Key: (%s)", d.Id()) - _, err := conn.ScheduleKeyDeletionWithContext(ctx, input) + _, err := conn.ScheduleKeyDeletion(ctx, input) - if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { + if errs.IsA[*awstypes.NotFoundException](err) { return diags } - - if tfawserr.ErrMessageContains(err, kms.ErrCodeInvalidStateException, "is pending deletion") { + var InvalidStateException = awstypes.KMSInvalidStateException{} + if tfawserr.ErrMessageContains(err, InvalidStateException.ErrorCode(), "is pending deletion") { return diags } diff --git a/internal/service/kms/replica_key_test.go b/internal/service/kms/replica_key_test.go index 9f15391cb82..62c48bb4c72 100644 --- a/internal/service/kms/replica_key_test.go +++ b/internal/service/kms/replica_key_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -18,7 +18,7 @@ import ( func TestAccKMSReplicaKey_basic(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) primaryKeyResourceName := "aws_kms_key.test" resourceName := "aws_kms_replica_key.test" @@ -60,7 +60,7 @@ func TestAccKMSReplicaKey_basic(t *testing.T) { func TestAccKMSReplicaKey_disappears(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_replica_key.test" @@ -87,7 +87,7 @@ func TestAccKMSReplicaKey_disappears(t *testing.T) { func TestAccKMSReplicaKey_descriptionAndEnabled(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rName3 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -139,7 +139,7 @@ func TestAccKMSReplicaKey_descriptionAndEnabled(t *testing.T) { func TestAccKMSReplicaKey_policy(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_replica_key.test" policy1 := `{"Id":"kms-tf-1","Statement":[{"Action":"kms:*","Effect":"Allow","Principal":{"AWS":"*"},"Resource":"*","Sid":"Enable IAM User Permissions 1"}],"Version":"2012-10-17"}` @@ -182,7 +182,7 @@ func TestAccKMSReplicaKey_policy(t *testing.T) { func TestAccKMSReplicaKey_tags(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_replica_key.test" @@ -251,7 +251,7 @@ func TestAccKMSReplicaKey_tags(t *testing.T) { func TestAccKMSReplicaKey_twoReplicas(t *testing.T) { ctx := acctest.Context(t) - var key kms.KeyMetadata + var key awstypes.KeyMetadata rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_kms_replica_key.test1" diff --git a/internal/service/kms/secrets_data_source.go b/internal/service/kms/secrets_data_source.go index 50e2052bdc1..8677d08ddad 100644 --- a/internal/service/kms/secrets_data_source.go +++ b/internal/service/kms/secrets_data_source.go @@ -6,12 +6,13 @@ package kms import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" itypes "github.com/hashicorp/terraform-provider-aws/internal/types" @@ -34,9 +35,9 @@ func DataSourceSecrets() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "encryption_algorithm": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice(kms.EncryptionAlgorithmSpec_Values(), false), + Type: schema.TypeString, + Optional: true, + ValidateDiagFunc: enum.Validate[awstypes.EncryptionAlgorithmSpec](), }, "grant_tokens": { Type: schema.TypeList, @@ -71,7 +72,7 @@ func DataSourceSecrets() *schema.Resource { func dataSourceSecretsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) secrets := d.Get("secret").(*schema.Set).List() plaintext := make(map[string]string, len(secrets)) @@ -92,15 +93,15 @@ func dataSourceSecretsRead(ctx context.Context, d *schema.ResourceData, meta int } if v, ok := secret["context"].(map[string]interface{}); ok && len(v) > 0 { - input.EncryptionContext = flex.ExpandStringMap(v) + input.EncryptionContext = flex.ExpandStringValueMap(v) } if v, ok := secret["encryption_algorithm"].(string); ok && v != "" { - input.EncryptionAlgorithm = aws.String(v) + input.EncryptionAlgorithm = awstypes.EncryptionAlgorithmSpec(v) } if v, ok := secret["grant_tokens"].([]interface{}); ok && len(v) > 0 { - input.GrantTokens = flex.ExpandStringList(v) + input.GrantTokens = flex.ExpandStringValueList(v) } if v, ok := secret["key_id"].(string); ok && v != "" { @@ -108,7 +109,7 @@ func dataSourceSecretsRead(ctx context.Context, d *schema.ResourceData, meta int } // decrypt - output, err := conn.DecryptWithContext(ctx, input) + output, err := conn.Decrypt(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "decrypting secret (%s): %s", name, err) diff --git a/internal/service/kms/secrets_data_source_test.go b/internal/service/kms/secrets_data_source_test.go index e65f3185efd..9b268a41e0e 100644 --- a/internal/service/kms/secrets_data_source_test.go +++ b/internal/service/kms/secrets_data_source_test.go @@ -9,8 +9,8 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -21,7 +21,7 @@ import ( func TestAccKMSSecretsDataSource_basic(t *testing.T) { ctx := acctest.Context(t) var encryptedPayload string - var key kms.KeyMetadata + var key awstypes.KeyMetadata plaintext := "my-plaintext-string" resourceName := "aws_kms_key.test" @@ -48,7 +48,7 @@ func TestAccKMSSecretsDataSource_basic(t *testing.T) { func TestAccKMSSecretsDataSource_asymmetric(t *testing.T) { ctx := acctest.Context(t) var encryptedPayload string - var key kms.KeyMetadata + var key awstypes.KeyMetadata plaintext := "my-plaintext-string" resourceName := "aws_kms_key.test" @@ -72,19 +72,19 @@ func TestAccKMSSecretsDataSource_asymmetric(t *testing.T) { }) } -func testAccSecretsEncryptDataSource(ctx context.Context, key *kms.KeyMetadata, plaintext string, encryptedPayload *string) resource.TestCheckFunc { +func testAccSecretsEncryptDataSource(ctx context.Context, key *awstypes.KeyMetadata, plaintext string, encryptedPayload *string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) input := &kms.EncryptInput{ KeyId: key.Arn, Plaintext: []byte(plaintext), - EncryptionContext: map[string]*string{ - "name": aws.String("value"), + EncryptionContext: map[string]string{ + "name": "value", }, } - output, err := conn.EncryptWithContext(ctx, input) + output, err := conn.Encrypt(ctx, input) if err != nil { return err @@ -96,17 +96,17 @@ func testAccSecretsEncryptDataSource(ctx context.Context, key *kms.KeyMetadata, } } -func testAccSecretsEncryptDataSourceAsymmetric(ctx context.Context, key *kms.KeyMetadata, plaintext string, encryptedPayload *string) resource.TestCheckFunc { +func testAccSecretsEncryptDataSourceAsymmetric(ctx context.Context, key *awstypes.KeyMetadata, plaintext string, encryptedPayload *string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).KMSConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).KMSClient(ctx) input := &kms.EncryptInput{ KeyId: key.Arn, Plaintext: []byte(plaintext), - EncryptionAlgorithm: aws.String("RSAES_OAEP_SHA_1"), + EncryptionAlgorithm: awstypes.EncryptionAlgorithmSpec("RSAES_OAEP_SHA_1"), } - output, err := conn.EncryptWithContext(ctx, input) + output, err := conn.Encrypt(ctx, input) if err != nil { return err @@ -141,7 +141,7 @@ func testAccSecretsDecryptDataSource(ctx context.Context, t *testing.T, plaintex } } -func testAccSecretsDecryptDataSourceAsym(ctx context.Context, t *testing.T, key *kms.KeyMetadata, plaintext string, encryptedPayload *string) resource.TestCheckFunc { +func testAccSecretsDecryptDataSourceAsym(ctx context.Context, t *testing.T, key *awstypes.KeyMetadata, plaintext string, encryptedPayload *string) resource.TestCheckFunc { return func(s *terraform.State) error { dataSourceName := "data.aws_kms_secrets.test" keyid := key.Arn diff --git a/internal/service/kms/service_endpoints_gen_test.go b/internal/service/kms/service_endpoints_gen_test.go index 269676b3b99..92a8b1680d8 100644 --- a/internal/service/kms/service_endpoints_gen_test.go +++ b/internal/service/kms/service_endpoints_gen_test.go @@ -4,17 +4,17 @@ package kms_test import ( "context" + "errors" "fmt" "maps" - "net/url" "os" "path/filepath" "reflect" "strings" "testing" - "github.com/aws/aws-sdk-go/aws/endpoints" - kms_sdkv1 "github.com/aws/aws-sdk-go/service/kms" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + kms_sdkv2 "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/google/go-cmp/cmp" @@ -212,32 +212,42 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S } func defaultEndpoint(region string) string { - r := endpoints.DefaultResolver() + r := kms_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(kms_sdkv1.EndpointsID, region) + ep, err := r.ResolveEndpoint(context.Background(), kms_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + }) if err != nil { return err.Error() } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return url.String() + return ep.URI.String() } func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { t.Helper() - client := meta.KMSConn(ctx) - - req, _ := client.ListKeysRequest(&kms_sdkv1.ListKeysInput{}) + var endpoint string - req.HTTPRequest.URL.Path = "/" + client := meta.KMSClient(ctx) - endpoint := req.HTTPRequest.URL.String() + _, err := client.ListKeys(ctx, &kms_sdkv2.ListKeysInput{}, + func(opts *kms_sdkv2.Options) { + opts.APIOptions = append(opts.APIOptions, + addRetrieveEndpointURLMiddleware(t, &endpoint), + addCancelRequestMiddleware(), + ) + }, + ) + if err == nil { + t.Fatal("Expected an error, got none") + } else if !errors.Is(err, errCancelOperation) { + t.Fatalf("Unexpected error: %s", err) + } return endpoint } diff --git a/internal/service/kms/service_package_gen.go b/internal/service/kms/service_package_gen.go index 1f126fed777..254cf6e36d9 100644 --- a/internal/service/kms/service_package_gen.go +++ b/internal/service/kms/service_package_gen.go @@ -5,9 +5,8 @@ package kms import ( "context" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - kms_sdkv1 "github.com/aws/aws-sdk-go/service/kms" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + kms_sdkv2 "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" "github.com/hashicorp/terraform-provider-aws/names" @@ -117,11 +116,15 @@ func (p *servicePackage) ServicePackageName() string { return names.KMS } -// NewConn returns a new AWS SDK for Go v1 client for this service package's AWS API. -func (p *servicePackage) NewConn(ctx context.Context, config map[string]any) (*kms_sdkv1.KMS, error) { - sess := config["session"].(*session_sdkv1.Session) +// NewClient returns a new AWS SDK for Go v2 client for this service package's AWS API. +func (p *servicePackage) NewClient(ctx context.Context, config map[string]any) (*kms_sdkv2.Client, error) { + cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) - return kms_sdkv1.New(sess.Copy(&aws_sdkv1.Config{Endpoint: aws_sdkv1.String(config["endpoint"].(string))})), nil + return kms_sdkv2.NewFromConfig(cfg, func(o *kms_sdkv2.Options) { + if endpoint := config["endpoint"].(string); endpoint != "" { + o.BaseEndpoint = aws_sdkv2.String(endpoint) + } + }), nil } func ServicePackage(ctx context.Context) conns.ServicePackage { diff --git a/internal/service/kms/status.go b/internal/service/kms/status.go index de6fe0cac44..4b5dac40694 100644 --- a/internal/service/kms/status.go +++ b/internal/service/kms/status.go @@ -6,13 +6,12 @@ package kms import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func StatusKeyState(ctx context.Context, conn *kms.KMS, id string) retry.StateRefreshFunc { +func StatusKeyState(ctx context.Context, conn *kms.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { output, err := FindKeyByID(ctx, conn, id) @@ -24,6 +23,6 @@ func StatusKeyState(ctx context.Context, conn *kms.KMS, id string) retry.StateRe return nil, "", err } - return output, aws.StringValue(output.KeyState), nil + return output, string(output.KeyState), nil } } diff --git a/internal/service/kms/sweep.go b/internal/service/kms/sweep.go index 0a1145e8460..19149a95569 100644 --- a/internal/service/kms/sweep.go +++ b/internal/service/kms/sweep.go @@ -7,8 +7,9 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -32,19 +33,21 @@ func sweepKeys(region string) error { return fmt.Errorf("error getting client: %w", err) } input := &kms.ListKeysInput{ - Limit: aws.Int64(1000), + Limit: aws.Int32(1000), } - conn := client.KMSConn(ctx) + conn := client.KMSClient(ctx) var sweeperErrs *multierror.Error sweepResources := make([]sweep.Sweepable, 0) - err = conn.ListKeysPagesWithContext(ctx, input, func(page *kms.ListKeysOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := kms.NewListKeysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + if err != nil { + return err } for _, v := range page.Keys { - keyID := aws.StringValue(v.KeyId) + keyID := aws.ToString(v.KeyId) key, err := FindKeyByID(ctx, conn, keyID) if tfresource.NotFound(err) { @@ -60,11 +63,11 @@ func sweepKeys(region string) error { continue } - if aws.StringValue(key.KeyManager) == kms.KeyManagerTypeAws { + if key.KeyManager == awstypes.KeyManagerTypeAws { log.Printf("[DEBUG] Skipping KMS Key (%s): managed by AWS", keyID) continue } - if aws.StringValue(key.KeyState) == kms.KeyStatePendingDeletion { + if key.KeyState == awstypes.KeyStatePendingDeletion { log.Printf("[DEBUG] Skipping KMS Key (%s): pending deletion", keyID) continue } @@ -77,9 +80,7 @@ func sweepKeys(region string) error { sweepResources = append(sweepResources, sdk.NewSweepResource(r, d, client)) } - - return !lastPage - }) + } if awsv1.SkipSweepError(err) { log.Printf("[WARN] Skipping KMS Key sweep for %s: %s", region, err) diff --git a/internal/service/kms/tags_gen.go b/internal/service/kms/tags_gen.go index ccf4e8243e9..73b64516c75 100644 --- a/internal/service/kms/tags_gen.go +++ b/internal/service/kms/tags_gen.go @@ -6,10 +6,10 @@ import ( "fmt" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/aws/aws-sdk-go/service/kms/kmsiface" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -23,35 +23,30 @@ import ( // listTags lists kms service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. -func listTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string) (tftags.KeyValueTags, error) { +func listTags(ctx context.Context, conn *kms.Client, identifier string, optFns ...func(*kms.Options)) (tftags.KeyValueTags, error) { input := &kms.ListResourceTagsInput{ KeyId: aws.String(identifier), } - var output []*kms.Tag + var output []awstypes.Tag - err := conn.ListResourceTagsPagesWithContext(ctx, input, func(page *kms.ListResourceTagsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := kms.NewListResourceTagsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx, optFns...) - for _, v := range page.Tags { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, "NotFoundException") { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, "NotFoundException") { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return tftags.New(ctx, nil), err } - } - if err != nil { - return tftags.New(ctx, nil), err + for _, v := range page.Tags { + output = append(output, v) + } } return KeyValueTags(ctx, output), nil @@ -60,7 +55,7 @@ func listTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string) (tft // ListTags lists kms service tags and set them in Context. // It is called from outside this package. func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier string) error { - tags, err := listTags(ctx, meta.(*conns.AWSClient).KMSConn(ctx), identifier) + tags, err := listTags(ctx, meta.(*conns.AWSClient).KMSClient(ctx), identifier) if err != nil { return err @@ -76,11 +71,11 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri // []*SERVICE.Tag handling // Tags returns kms service tags. -func Tags(tags tftags.KeyValueTags) []*kms.Tag { - result := make([]*kms.Tag, 0, len(tags)) +func Tags(tags tftags.KeyValueTags) []awstypes.Tag { + result := make([]awstypes.Tag, 0, len(tags)) for k, v := range tags.Map() { - tag := &kms.Tag{ + tag := awstypes.Tag{ TagKey: aws.String(k), TagValue: aws.String(v), } @@ -92,11 +87,11 @@ func Tags(tags tftags.KeyValueTags) []*kms.Tag { } // KeyValueTags creates tftags.KeyValueTags from kms service tags. -func KeyValueTags(ctx context.Context, tags []*kms.Tag) tftags.KeyValueTags { +func KeyValueTags(ctx context.Context, tags []awstypes.Tag) tftags.KeyValueTags { m := make(map[string]*string, len(tags)) for _, tag := range tags { - m[aws.StringValue(tag.TagKey)] = tag.TagValue + m[aws.ToString(tag.TagKey)] = tag.TagValue } return tftags.New(ctx, m) @@ -104,7 +99,7 @@ func KeyValueTags(ctx context.Context, tags []*kms.Tag) tftags.KeyValueTags { // getTagsIn returns kms service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) []*kms.Tag { +func getTagsIn(ctx context.Context) []awstypes.Tag { if inContext, ok := tftags.FromContext(ctx); ok { if tags := Tags(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { return tags @@ -115,7 +110,7 @@ func getTagsIn(ctx context.Context) []*kms.Tag { } // setTagsOut sets kms service tags in Context. -func setTagsOut(ctx context.Context, tags []*kms.Tag) { +func setTagsOut(ctx context.Context, tags []awstypes.Tag) { if inContext, ok := tftags.FromContext(ctx); ok { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } @@ -124,7 +119,7 @@ func setTagsOut(ctx context.Context, tags []*kms.Tag) { // updateTags updates kms service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. -func updateTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string, oldTagsMap, newTagsMap any) error { +func updateTags(ctx context.Context, conn *kms.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*kms.Options)) error { oldTags := tftags.New(ctx, oldTagsMap) newTags := tftags.New(ctx, newTagsMap) @@ -135,10 +130,10 @@ func updateTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string, ol if len(removedTags) > 0 { input := &kms.UntagResourceInput{ KeyId: aws.String(identifier), - TagKeys: aws.StringSlice(removedTags.Keys()), + TagKeys: removedTags.Keys(), } - _, err := conn.UntagResourceWithContext(ctx, input) + _, err := conn.UntagResource(ctx, input, optFns...) if err != nil { return fmt.Errorf("untagging resource (%s): %w", identifier, err) @@ -153,7 +148,7 @@ func updateTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string, ol Tags: Tags(updatedTags), } - _, err := conn.TagResourceWithContext(ctx, input) + _, err := conn.TagResource(ctx, input, optFns...) if err != nil { return fmt.Errorf("tagging resource (%s): %w", identifier, err) @@ -161,7 +156,7 @@ func updateTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string, ol } if len(removedTags) > 0 || len(updatedTags) > 0 { - if err := waitTagsPropagated(ctx, conn, identifier, newTags); err != nil { + if err := waitTagsPropagated(ctx, conn, identifier, newTags, optFns...); err != nil { return fmt.Errorf("waiting for resource (%s) tag propagation: %w", identifier, err) } } @@ -172,19 +167,19 @@ func updateTags(ctx context.Context, conn kmsiface.KMSAPI, identifier string, ol // UpdateTags updates kms service tags. // It is called from outside this package. func (p *servicePackage) UpdateTags(ctx context.Context, meta any, identifier string, oldTags, newTags any) error { - return updateTags(ctx, meta.(*conns.AWSClient).KMSConn(ctx), identifier, oldTags, newTags) + return updateTags(ctx, meta.(*conns.AWSClient).KMSClient(ctx), identifier, oldTags, newTags) } // waitTagsPropagated waits for kms service tags to be propagated. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. -func waitTagsPropagated(ctx context.Context, conn kmsiface.KMSAPI, id string, tags tftags.KeyValueTags) error { +func waitTagsPropagated(ctx context.Context, conn *kms.Client, id string, tags tftags.KeyValueTags, optFns ...func(*kms.Options)) error { tflog.Debug(ctx, "Waiting for tag propagation", map[string]any{ "tags": tags, }) checkFunc := func() (bool, error) { - output, err := listTags(ctx, conn, id) + output, err := listTags(ctx, conn, id, optFns...) if tfresource.NotFound(err) { return false, nil diff --git a/internal/service/kms/wait.go b/internal/service/kms/wait.go index 7e83547b795..f3b6f0cd997 100644 --- a/internal/service/kms/wait.go +++ b/internal/service/kms/wait.go @@ -7,10 +7,12 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/kms" + awstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" awspolicy "github.com/hashicorp/awspolicyequivalence" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -36,10 +38,11 @@ const ( // WaitIAMPropagation retries the specified function if the returned error indicates an IAM eventual consistency issue. // If the retries time out the specified function is called one last time. func WaitIAMPropagation[T any](ctx context.Context, timeout time.Duration, f func() (T, error)) (T, error) { + var MalformedPolicyDocumentException = awstypes.MalformedPolicyDocumentException{} outputRaw, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, timeout, func() (interface{}, error) { return f() }, - kms.ErrCodeMalformedPolicyDocumentException) + MalformedPolicyDocumentException.ErrorCode()) if err != nil { var zero T @@ -49,9 +52,9 @@ func WaitIAMPropagation[T any](ctx context.Context, timeout time.Duration, f fun return outputRaw.(T), nil } -func WaitKeyDeleted(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMetadata, error) { +func WaitKeyDeleted(ctx context.Context, conn *kms.Client, id string) (*awstypes.KeyMetadata, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{kms.KeyStateDisabled, kms.KeyStateEnabled}, + Pending: enum.Slice(awstypes.KeyStateDisabled, awstypes.KeyStateEnabled), Target: []string{}, Refresh: StatusKeyState(ctx, conn, id), Timeout: KeyDeletedTimeout, @@ -59,14 +62,14 @@ func WaitKeyDeleted(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMeta outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*kms.KeyMetadata); ok { + if output, ok := outputRaw.(*awstypes.KeyMetadata); ok { return output, err } return nil, err } -func WaitKeyDescriptionPropagated(ctx context.Context, conn *kms.KMS, id string, description string) error { +func WaitKeyDescriptionPropagated(ctx context.Context, conn *kms.Client, id string, description string) error { checkFunc := func() (bool, error) { output, err := FindKeyByID(ctx, conn, id) @@ -78,7 +81,7 @@ func WaitKeyDescriptionPropagated(ctx context.Context, conn *kms.KMS, id string, return false, err } - return aws.StringValue(output.Description) == description, nil + return aws.ToString(output.Description) == description, nil } opts := tfresource.WaitOpts{ ContinuousTargetOccurence: 5, @@ -88,24 +91,24 @@ func WaitKeyDescriptionPropagated(ctx context.Context, conn *kms.KMS, id string, return tfresource.WaitUntil(ctx, KeyDescriptionPropagationTimeout, checkFunc, opts) } -func WaitKeyMaterialImported(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMetadata, error) { +func WaitKeyMaterialImported(ctx context.Context, conn *kms.Client, id string) (*awstypes.KeyMetadata, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{kms.KeyStatePendingImport}, - Target: []string{kms.KeyStateDisabled, kms.KeyStateEnabled}, + Pending: enum.Slice(awstypes.KeyStatePendingImport), + Target: enum.Slice(awstypes.KeyStateDisabled, awstypes.KeyStateEnabled), Refresh: StatusKeyState(ctx, conn, id), Timeout: KeyMaterialImportedTimeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*kms.KeyMetadata); ok { + if output, ok := outputRaw.(*awstypes.KeyMetadata); ok { return output, err } return nil, err } -func WaitKeyPolicyPropagated(ctx context.Context, conn *kms.KMS, id, policy string) error { +func WaitKeyPolicyPropagated(ctx context.Context, conn *kms.Client, id, policy string) error { checkFunc := func() (bool, error) { output, err := FindKeyPolicyByKeyIDAndPolicyName(ctx, conn, id, PolicyNameDefault) @@ -117,7 +120,7 @@ func WaitKeyPolicyPropagated(ctx context.Context, conn *kms.KMS, id, policy stri return false, err } - equivalent, err := awspolicy.PoliciesAreEquivalent(aws.StringValue(output), policy) + equivalent, err := awspolicy.PoliciesAreEquivalent(aws.ToString(output), policy) if err != nil { return false, err @@ -133,7 +136,7 @@ func WaitKeyPolicyPropagated(ctx context.Context, conn *kms.KMS, id, policy stri return tfresource.WaitUntil(ctx, KeyPolicyPropagationTimeout, checkFunc, opts) } -func WaitKeyRotationEnabledPropagated(ctx context.Context, conn *kms.KMS, id string, enabled bool) error { +func WaitKeyRotationEnabledPropagated(ctx context.Context, conn *kms.Client, id string, enabled bool) error { checkFunc := func() (bool, error) { output, err := FindKeyRotationEnabledByKeyID(ctx, conn, id) @@ -145,7 +148,7 @@ func WaitKeyRotationEnabledPropagated(ctx context.Context, conn *kms.KMS, id str return false, err } - return aws.BoolValue(output) == enabled, nil + return aws.ToBool(output) == enabled, nil } opts := tfresource.WaitOpts{ ContinuousTargetOccurence: 5, @@ -155,7 +158,7 @@ func WaitKeyRotationEnabledPropagated(ctx context.Context, conn *kms.KMS, id str return tfresource.WaitUntil(ctx, KeyRotationUpdatedTimeout, checkFunc, opts) } -func WaitKeyStatePropagated(ctx context.Context, conn *kms.KMS, id string, enabled bool) error { +func WaitKeyStatePropagated(ctx context.Context, conn *kms.Client, id string, enabled bool) error { checkFunc := func() (bool, error) { output, err := FindKeyByID(ctx, conn, id) @@ -167,7 +170,7 @@ func WaitKeyStatePropagated(ctx context.Context, conn *kms.KMS, id string, enabl return false, err } - return aws.BoolValue(output.Enabled) == enabled, nil + return output.Enabled == enabled, nil } opts := tfresource.WaitOpts{ ContinuousTargetOccurence: 15, @@ -177,7 +180,7 @@ func WaitKeyStatePropagated(ctx context.Context, conn *kms.KMS, id string, enabl return tfresource.WaitUntil(ctx, KeyStatePropagationTimeout, checkFunc, opts) } -func WaitKeyValidToPropagated(ctx context.Context, conn *kms.KMS, id string, validTo string) error { +func WaitKeyValidToPropagated(ctx context.Context, conn *kms.Client, id string, validTo string) error { checkFunc := func() (bool, error) { output, err := FindKeyByID(ctx, conn, id) @@ -190,7 +193,7 @@ func WaitKeyValidToPropagated(ctx context.Context, conn *kms.KMS, id string, val } if output.ValidTo != nil { - return aws.TimeValue(output.ValidTo).Format(time.RFC3339) == validTo, nil + return aws.ToTime(output.ValidTo).Format(time.RFC3339) == validTo, nil } return validTo == "", nil @@ -203,34 +206,34 @@ func WaitKeyValidToPropagated(ctx context.Context, conn *kms.KMS, id string, val return tfresource.WaitUntil(ctx, KeyValidToPropagationTimeout, checkFunc, opts) } -func WaitReplicaExternalKeyCreated(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMetadata, error) { +func WaitReplicaExternalKeyCreated(ctx context.Context, conn *kms.Client, id string) (*awstypes.KeyMetadata, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{kms.KeyStateCreating}, - Target: []string{kms.KeyStatePendingImport}, + Pending: enum.Slice(awstypes.KeyStateCreating), + Target: enum.Slice(awstypes.KeyStatePendingImport), Refresh: StatusKeyState(ctx, conn, id), Timeout: ReplicaExternalKeyCreatedTimeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*kms.KeyMetadata); ok { + if output, ok := outputRaw.(*awstypes.KeyMetadata); ok { return output, err } return nil, err } -func WaitReplicaKeyCreated(ctx context.Context, conn *kms.KMS, id string) (*kms.KeyMetadata, error) { +func WaitReplicaKeyCreated(ctx context.Context, conn *kms.Client, id string) (*awstypes.KeyMetadata, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{kms.KeyStateCreating}, - Target: []string{kms.KeyStateEnabled}, + Pending: enum.Slice(awstypes.KeyStateCreating), + Target: enum.Slice(awstypes.KeyStateEnabled), Refresh: StatusKeyState(ctx, conn, id), Timeout: ReplicaKeyCreatedTimeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*kms.KeyMetadata); ok { + if output, ok := outputRaw.(*awstypes.KeyMetadata); ok { return output, err } diff --git a/internal/service/s3/bucket_object.go b/internal/service/s3/bucket_object.go index 853f7f1780d..04ee722c3a5 100644 --- a/internal/service/s3/bucket_object.go +++ b/internal/service/s3/bucket_object.go @@ -507,7 +507,7 @@ func resourceBucketObjectSetKMS(ctx context.Context, d *schema.ResourceData, met // Only set non-default KMS key ID (one that doesn't match default) if sseKMSKeyId != nil { // retrieve S3 KMS Default Master Key - conn := meta.(*conns.AWSClient).KMSConn(ctx) + conn := meta.(*conns.AWSClient).KMSClient(ctx) keyMetadata, err := kms.FindKeyByID(ctx, conn, defaultKMSKeyAlias) if err != nil { return fmt.Errorf("Failed to describe default S3 KMS key (%s): %s", defaultKMSKeyAlias, err) diff --git a/internal/service/s3/object.go b/internal/service/s3/object.go index 03088937417..e630bf5ee68 100644 --- a/internal/service/s3/object.go +++ b/internal/service/s3/object.go @@ -601,7 +601,7 @@ func setObjectKMSKeyID(ctx context.Context, meta interface{}, d *schema.Resource // Only set non-default KMS key ID (one that doesn't match default). if sseKMSKeyID != "" { // Read S3 KMS default master key. - keyMetadata, err := kms.FindKeyByID(ctx, meta.(*conns.AWSClient).KMSConn(ctx), defaultKMSKeyAlias) + keyMetadata, err := kms.FindKeyByID(ctx, meta.(*conns.AWSClient).KMSClient(ctx), defaultKMSKeyAlias) if err != nil { return fmt.Errorf("reading default S3 KMS key (%s): %s", defaultKMSKeyAlias, err) diff --git a/names/data/names_data.csv b/names/data/names_data.csv index a3efdbe3344..4993147ffd8 100644 --- a/names/data/names_data.csv +++ b/names/data/names_data.csv @@ -216,7 +216,7 @@ kinesisvideo,kinesisvideo,kinesisvideo,kinesisvideo,,kinesisvideo,,,KinesisVideo kinesis-video-archived-media,kinesisvideoarchivedmedia,kinesisvideoarchivedmedia,kinesisvideoarchivedmedia,,kinesisvideoarchivedmedia,,,KinesisVideoArchivedMedia,KinesisVideoArchivedMedia,,1,,,aws_kinesisvideoarchivedmedia_,,kinesisvideoarchivedmedia_,Kinesis Video Archived Media,Amazon,,x,,,,,Kinesis Video Archived Media,,, kinesis-video-media,kinesisvideomedia,kinesisvideomedia,kinesisvideomedia,,kinesisvideomedia,,,KinesisVideoMedia,KinesisVideoMedia,,1,,,aws_kinesisvideomedia_,,kinesisvideomedia_,Kinesis Video Media,Amazon,,x,,,,,Kinesis Video Media,,, kinesis-video-signaling,kinesisvideosignaling,kinesisvideosignalingchannels,kinesisvideosignaling,,kinesisvideosignaling,,kinesisvideosignalingchannels,KinesisVideoSignaling,KinesisVideoSignalingChannels,,1,,,aws_kinesisvideosignaling_,,kinesisvideosignaling_,Kinesis Video Signaling,Amazon,,x,,,,,Kinesis Video Signaling,,, -kms,kms,kms,kms,,kms,,,KMS,KMS,,1,,,aws_kms_,,kms_,KMS (Key Management),AWS,,,,,,,KMS,ListKeys,, +kms,kms,kms,kms,,kms,,,KMS,KMS,,,2,,aws_kms_,,kms_,KMS (Key Management),AWS,,,,,,,KMS,ListKeys,, lakeformation,lakeformation,lakeformation,lakeformation,,lakeformation,,,LakeFormation,LakeFormation,,,2,,aws_lakeformation_,,lakeformation_,Lake Formation,AWS,,,,,,,LakeFormation,ListResources,, lambda,lambda,lambda,lambda,,lambda,,,Lambda,Lambda,,1,2,,aws_lambda_,,lambda_,Lambda,AWS,,,,,,,Lambda,ListFunctions,, launch-wizard,launchwizard,launchwizard,launchwizard,,launchwizard,,,LaunchWizard,LaunchWizard,,,2,,aws_launchwizard_,,launchwizard_,Launch Wizard,AWS,,,,,,,Launch Wizard,ListWorkloads,, diff --git a/names/names.go b/names/names.go index f332204633a..c7c645c87ea 100644 --- a/names/names.go +++ b/names/names.go @@ -61,6 +61,7 @@ const ( Inspector2EndpointID = "inspector2" IVSChatEndpointID = "ivschat" KendraEndpointID = "kendra" + KMSEndpointID = "kms" LexV2ModelsEndpointID = "models-v2-lex" M2EndpointID = "m2" MediaConvertEndpointID = "mediaconvert"