From d1e450be00d61f095669d84b3e69cd269338a5db Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 19:42:33 +0100 Subject: [PATCH 01/22] guardduty: Migrate to AWS SDK v2 --- internal/conns/awsclient_gen.go | 5 ----- names/data/names_data.hcl | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index fb94dc454c0..17f267af71a 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -219,7 +219,6 @@ import ( fsx_sdkv1 "github.com/aws/aws-sdk-go/service/fsx" gamelift_sdkv1 "github.com/aws/aws-sdk-go/service/gamelift" glue_sdkv1 "github.com/aws/aws-sdk-go/service/glue" - guardduty_sdkv1 "github.com/aws/aws-sdk-go/service/guardduty" imagebuilder_sdkv1 "github.com/aws/aws-sdk-go/service/imagebuilder" inspector_sdkv1 "github.com/aws/aws-sdk-go/service/inspector" ivs_sdkv1 "github.com/aws/aws-sdk-go/service/ivs" @@ -715,10 +714,6 @@ func (c *AWSClient) GroundStationClient(ctx context.Context) *groundstation_sdkv return errs.Must(client[*groundstation_sdkv2.Client](ctx, c, names.GroundStation, make(map[string]any))) } -func (c *AWSClient) GuardDutyConn(ctx context.Context) *guardduty_sdkv1.GuardDuty { - return errs.Must(conn[*guardduty_sdkv1.GuardDuty](ctx, c, names.GuardDuty, make(map[string]any))) -} - func (c *AWSClient) GuardDutyClient(ctx context.Context) *guardduty_sdkv2.Client { return errs.Must(client[*guardduty_sdkv2.Client](ctx, c, names.GuardDuty, make(map[string]any))) } diff --git a/names/data/names_data.hcl b/names/data/names_data.hcl index 87260d2c923..365f0c1f90d 100644 --- a/names/data/names_data.hcl +++ b/names/data/names_data.hcl @@ -4293,7 +4293,7 @@ service "guardduty" { sdk { id = "GuardDuty" - client_version = [1, 2] + client_version = [2] } names { From 4396c5604159ee9de96de16125de363a2dcf0c88 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 20:27:12 +0100 Subject: [PATCH 02/22] make gen --- internal/service/guardduty/generate.go | 3 +- .../guardduty/malware_protection_plan.go | 2 +- .../service_endpoint_resolver_gen.go | 64 ----------- .../guardduty/service_endpoints_gen_test.go | 43 ++------ .../service/guardduty/service_package_gen.go | 22 ---- internal/service/guardduty/tags_gen.go | 101 ++---------------- internal/service/guardduty/tagsv2_gen.go | 40 ------- 7 files changed, 15 insertions(+), 260 deletions(-) delete mode 100644 internal/service/guardduty/tagsv2_gen.go diff --git a/internal/service/guardduty/generate.go b/internal/service/guardduty/generate.go index 1da552f2cf6..fe4dadcf8f4 100644 --- a/internal/service/guardduty/generate.go +++ b/internal/service/guardduty/generate.go @@ -1,8 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -ListTags -ServiceTagsMap -UpdateTags -//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -TagsFunc=TagsV2 -KeyValueTagsFunc=keyValueTagsV2 -GetTagsInFunc=getTagsInV2 -SetTagsOutFunc=setTagsOutV2 -ServiceTagsMap -KVTValues -SkipTypesImp -SkipAWSServiceImp -SkipAWSImp -- tagsv2_gen.go +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ServiceTagsMap -KVTValues -SkipTypesImp -SkipAWSServiceImp -SkipAWSImp //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/guardduty/malware_protection_plan.go b/internal/service/guardduty/malware_protection_plan.go index efe2773748f..540f3a58f5e 100644 --- a/internal/service/guardduty/malware_protection_plan.go +++ b/internal/service/guardduty/malware_protection_plan.go @@ -147,7 +147,7 @@ func (r *resourceMalwareProtectionPlan) Create(ctx context.Context, req resource return } - input.Tags = getTagsInV2(ctx) + input.Tags = getTagsIn(ctx) var out *guardduty.CreateMalwareProtectionPlanOutput diff --git a/internal/service/guardduty/service_endpoint_resolver_gen.go b/internal/service/guardduty/service_endpoint_resolver_gen.go index 450e4f42eb5..776011ae2e1 100644 --- a/internal/service/guardduty/service_endpoint_resolver_gen.go +++ b/internal/service/guardduty/service_endpoint_resolver_gen.go @@ -6,78 +6,14 @@ import ( "context" "fmt" "net" - "net/url" aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" guardduty_sdkv2 "github.com/aws/aws-sdk-go-v2/service/guardduty" - endpoints_sdkv1 "github.com/aws/aws-sdk-go/aws/endpoints" smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) -var _ endpoints_sdkv1.Resolver = resolverSDKv1{} - -type resolverSDKv1 struct { - ctx context.Context -} - -func newEndpointResolverSDKv1(ctx context.Context) resolverSDKv1 { - return resolverSDKv1{ - ctx: ctx, - } -} - -func (r resolverSDKv1) EndpointFor(service, region string, opts ...func(*endpoints_sdkv1.Options)) (endpoint endpoints_sdkv1.ResolvedEndpoint, err error) { - ctx := r.ctx - - var opt endpoints_sdkv1.Options - opt.Set(opts...) - - useFIPS := opt.UseFIPSEndpoint == endpoints_sdkv1.FIPSEndpointStateEnabled - - defaultResolver := endpoints_sdkv1.DefaultResolver() - - if useFIPS { - ctx = tflog.SetField(ctx, "tf_aws.use_fips", useFIPS) - - endpoint, err = defaultResolver.EndpointFor(service, region, opts...) - if err != nil { - return endpoint, err - } - - tflog.Debug(ctx, "endpoint resolved", map[string]any{ - "tf_aws.endpoint": endpoint.URL, - }) - - var endpointURL *url.URL - endpointURL, err = url.Parse(endpoint.URL) - if err != nil { - return endpoint, err - } - - hostname := endpointURL.Hostname() - _, err = net.LookupHost(hostname) - if err != nil { - if dnsErr, ok := errs.As[*net.DNSError](err); ok && dnsErr.IsNotFound { - tflog.Debug(ctx, "default endpoint host not found, disabling FIPS", map[string]any{ - "tf_aws.hostname": hostname, - }) - opts = append(opts, func(o *endpoints_sdkv1.Options) { - o.UseFIPSEndpoint = endpoints_sdkv1.FIPSEndpointStateDisabled - }) - } else { - err = fmt.Errorf("looking up accessanalyzer endpoint %q: %s", hostname, err) - return - } - } else { - return endpoint, err - } - } - - return defaultResolver.EndpointFor(service, region, opts...) -} - var _ guardduty_sdkv2.EndpointResolverV2 = resolverSDKv2{} type resolverSDKv2 struct { diff --git a/internal/service/guardduty/service_endpoints_gen_test.go b/internal/service/guardduty/service_endpoints_gen_test.go index 5e96c6bccd7..ff6541b3606 100644 --- a/internal/service/guardduty/service_endpoints_gen_test.go +++ b/internal/service/guardduty/service_endpoints_gen_test.go @@ -18,8 +18,6 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" guardduty_sdkv2 "github.com/aws/aws-sdk-go-v2/service/guardduty" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - guardduty_sdkv1 "github.com/aws/aws-sdk-go/service/guardduty" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/google/go-cmp/cmp" @@ -236,25 +234,13 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S }, } - t.Run("v1", func(t *testing.T) { - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase + for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv + testcase := testcase - t.Run(name, func(t *testing.T) { - testEndpointCase(t, providerRegion, testcase, callServiceV1) - }) - } - }) - - t.Run("v2", func(t *testing.T) { - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase - - t.Run(name, func(t *testing.T) { - testEndpointCase(t, providerRegion, testcase, callServiceV2) - }) - } - }) + t.Run(name, func(t *testing.T) { + testEndpointCase(t, providerRegion, testcase, callService) + }) + } } func defaultEndpoint(region string) (url.URL, error) { @@ -292,7 +278,7 @@ func defaultFIPSEndpoint(region string) (url.URL, error) { return ep.URI, nil } -func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { +func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { t.Helper() client := meta.GuardDutyClient(ctx) @@ -317,21 +303,6 @@ func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) api return result } -func callServiceV1(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { - t.Helper() - - client := meta.GuardDutyConn(ctx) - - req, _ := client.ListDetectorsRequest(&guardduty_sdkv1.ListDetectorsInput{}) - - req.HTTPRequest.URL.Path = "/" - - return apiCallParams{ - endpoint: req.HTTPRequest.URL.String(), - region: aws_sdkv1.StringValue(client.Config.Region), - } -} - func withNoConfig(_ *caseSetup) { // no-op } diff --git a/internal/service/guardduty/service_package_gen.go b/internal/service/guardduty/service_package_gen.go index ebdc4535ff1..57dedfef8b6 100644 --- a/internal/service/guardduty/service_package_gen.go +++ b/internal/service/guardduty/service_package_gen.go @@ -7,10 +7,6 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" guardduty_sdkv2 "github.com/aws/aws-sdk-go-v2/service/guardduty" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - guardduty_sdkv1 "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" "github.com/hashicorp/terraform-provider-aws/names" @@ -120,24 +116,6 @@ func (p *servicePackage) ServicePackageName() string { return names.GuardDuty } -// 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) (*guardduty_sdkv1.GuardDuty, error) { - sess := config[names.AttrSession].(*session_sdkv1.Session) - - cfg := aws_sdkv1.Config{} - - if endpoint := config[names.AttrEndpoint].(string); endpoint != "" { - tflog.Debug(ctx, "setting endpoint", map[string]any{ - "tf_aws.endpoint": endpoint, - }) - cfg.Endpoint = aws_sdkv1.String(endpoint) - } else { - cfg.EndpointResolver = newEndpointResolverSDKv1(ctx) - } - - return guardduty_sdkv1.New(sess.Copy(&cfg)), nil -} - // 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) (*guardduty_sdkv2.Client, error) { cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) diff --git a/internal/service/guardduty/tags_gen.go b/internal/service/guardduty/tags_gen.go index 004e9628cde..e112e228925 100644 --- a/internal/service/guardduty/tags_gen.go +++ b/internal/service/guardduty/tags_gen.go @@ -3,67 +3,26 @@ package guardduty import ( "context" - "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/aws/aws-sdk-go/service/guardduty/guarddutyiface" - "github.com/hashicorp/terraform-plugin-log/tflog" - "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/logging" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/types/option" - "github.com/hashicorp/terraform-provider-aws/names" ) -// listTags lists guardduty 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 guarddutyiface.GuardDutyAPI, identifier string) (tftags.KeyValueTags, error) { - input := &guardduty.ListTagsForResourceInput{ - ResourceArn: aws.String(identifier), - } - - output, err := conn.ListTagsForResourceWithContext(ctx, input) - - if err != nil { - return tftags.New(ctx, nil), err - } - - return KeyValueTags(ctx, output.Tags), nil -} - -// ListTags lists guardduty 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).GuardDutyConn(ctx), identifier) - - if err != nil { - return err - } - - if inContext, ok := tftags.FromContext(ctx); ok { - inContext.TagsOut = option.Some(tags) - } - - return nil -} - -// map[string]*string handling +// map[string]string handling // Tags returns guardduty service tags. -func Tags(tags tftags.KeyValueTags) map[string]*string { - return aws.StringMap(tags.Map()) +func Tags(tags tftags.KeyValueTags) map[string]string { + return tags.Map() } // KeyValueTags creates tftags.KeyValueTags from guardduty service tags. -func KeyValueTags(ctx context.Context, tags map[string]*string) tftags.KeyValueTags { +func KeyValueTags(ctx context.Context, tags map[string]string) tftags.KeyValueTags { return tftags.New(ctx, tags) } // getTagsIn returns guardduty service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) map[string]*string { +func getTagsIn(ctx context.Context) map[string]string { if inContext, ok := tftags.FromContext(ctx); ok { if tags := Tags(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { return tags @@ -74,56 +33,8 @@ func getTagsIn(ctx context.Context) map[string]*string { } // setTagsOut sets guardduty service tags in Context. -func setTagsOut(ctx context.Context, tags map[string]*string) { +func setTagsOut(ctx context.Context, tags map[string]string) { if inContext, ok := tftags.FromContext(ctx); ok { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } } - -// updateTags updates guardduty 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 guarddutyiface.GuardDutyAPI, identifier string, oldTagsMap, newTagsMap any) error { - oldTags := tftags.New(ctx, oldTagsMap) - newTags := tftags.New(ctx, newTagsMap) - - ctx = tflog.SetField(ctx, logging.KeyResourceId, identifier) - - removedTags := oldTags.Removed(newTags) - removedTags = removedTags.IgnoreSystem(names.GuardDuty) - if len(removedTags) > 0 { - input := &guardduty.UntagResourceInput{ - ResourceArn: aws.String(identifier), - TagKeys: aws.StringSlice(removedTags.Keys()), - } - - _, err := conn.UntagResourceWithContext(ctx, input) - - if err != nil { - return fmt.Errorf("untagging resource (%s): %w", identifier, err) - } - } - - updatedTags := oldTags.Updated(newTags) - updatedTags = updatedTags.IgnoreSystem(names.GuardDuty) - if len(updatedTags) > 0 { - input := &guardduty.TagResourceInput{ - ResourceArn: aws.String(identifier), - Tags: Tags(updatedTags), - } - - _, err := conn.TagResourceWithContext(ctx, input) - - if err != nil { - return fmt.Errorf("tagging resource (%s): %w", identifier, err) - } - } - - return nil -} - -// UpdateTags updates guardduty 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).GuardDutyConn(ctx), identifier, oldTags, newTags) -} diff --git a/internal/service/guardduty/tagsv2_gen.go b/internal/service/guardduty/tagsv2_gen.go deleted file mode 100644 index b44768da286..00000000000 --- a/internal/service/guardduty/tagsv2_gen.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by internal/generate/tags/main.go; DO NOT EDIT. -package guardduty - -import ( - "context" - - tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" - "github.com/hashicorp/terraform-provider-aws/internal/types/option" -) - -// map[string]string handling - -// TagsV2 returns guardduty service tags. -func TagsV2(tags tftags.KeyValueTags) map[string]string { - return tags.Map() -} - -// keyValueTagsV2 creates tftags.KeyValueTags from guardduty service tags. -func keyValueTagsV2(ctx context.Context, tags map[string]string) tftags.KeyValueTags { - return tftags.New(ctx, tags) -} - -// getTagsInV2 returns guardduty service tags from Context. -// nil is returned if there are no input tags. -func getTagsInV2(ctx context.Context) map[string]string { - if inContext, ok := tftags.FromContext(ctx); ok { - if tags := TagsV2(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { - return tags - } - } - - return nil -} - -// setTagsOutV2 sets guardduty service tags in Context. -func setTagsOutV2(ctx context.Context, tags map[string]string) { - if inContext, ok := tftags.FromContext(ctx); ok { - inContext.TagsOut = option.Some(keyValueTagsV2(ctx, tags)) - } -} From ae411c3e23f7059f568ae4e3ef51250d77b3baf5 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 20:55:26 +0100 Subject: [PATCH 03/22] d/guardduty_detector,r/guardduty_detector: Migrate to AWS SDK v2 --- internal/service/guardduty/detector.go | 117 ++++++++---------- .../service/guardduty/detector_data_source.go | 6 +- internal/service/guardduty/detector_test.go | 4 +- 3 files changed, 60 insertions(+), 67 deletions(-) diff --git a/internal/service/guardduty/detector.go b/internal/service/guardduty/detector.go index f461990dbe2..df87cd5887a 100644 --- a/internal/service/guardduty/detector.go +++ b/internal/service/guardduty/detector.go @@ -8,14 +8,15 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "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-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -146,7 +147,7 @@ func ResourceDetector() *schema.Resource { func resourceDetectorCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) input := &guardduty.CreateDetectorInput{ Enable: aws.Bool(d.Get("enable").(bool)), @@ -158,23 +159,23 @@ func resourceDetectorCreate(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := d.GetOk("finding_publishing_frequency"); ok { - input.FindingPublishingFrequency = aws.String(v.(string)) + input.FindingPublishingFrequency = awstypes.FindingPublishingFrequency(v.(string)) } - output, err := conn.CreateDetectorWithContext(ctx, input) + output, err := conn.CreateDetector(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating GuardDuty Detector: %s", err) } - d.SetId(aws.StringValue(output.DetectorId)) + d.SetId(aws.ToString(output.DetectorId)) return append(diags, resourceDetectorRead(ctx, d, meta)...) } func resourceDetectorRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) gdo, err := FindDetectorByID(ctx, conn, d.Id()) @@ -205,7 +206,7 @@ func resourceDetectorRead(ctx context.Context, d *schema.ResourceData, meta inte } else { d.Set("datasources", nil) } - d.Set("enable", aws.StringValue(gdo.Status) == guardduty.DetectorStatusEnabled) + d.Set("enable", gdo.Status == awstypes.DetectorStatusEnabled) d.Set("finding_publishing_frequency", gdo.FindingPublishingFrequency) setTagsOut(ctx, gdo.Tags) @@ -215,20 +216,20 @@ func resourceDetectorRead(ctx context.Context, d *schema.ResourceData, meta inte func resourceDetectorUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) { input := &guardduty.UpdateDetectorInput{ DetectorId: aws.String(d.Id()), Enable: aws.Bool(d.Get("enable").(bool)), - FindingPublishingFrequency: aws.String(d.Get("finding_publishing_frequency").(string)), + FindingPublishingFrequency: awstypes.FindingPublishingFrequency(d.Get("finding_publishing_frequency").(string)), } if d.HasChange("datasources") { input.DataSources = expandDataSourceConfigurations(d.Get("datasources").([]interface{})[0].(map[string]interface{})) } - _, err := conn.UpdateDetectorWithContext(ctx, input) + _, err := conn.UpdateDetector(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Detector (%s): %s", d.Id(), err) @@ -240,16 +241,16 @@ func resourceDetectorUpdate(ctx context.Context, d *schema.ResourceData, meta in func resourceDetectorDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) log.Printf("[DEBUG] Deleting GuardDuty Detector: %s", d.Id()) - _, err := tfresource.RetryWhenAWSErrMessageContains(ctx, membershipPropagationTimeout, func() (interface{}, error) { - return conn.DeleteDetectorWithContext(ctx, &guardduty.DeleteDetectorInput{ + _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.BadRequestException](ctx, membershipPropagationTimeout, func() (interface{}, error) { + return conn.DeleteDetector(ctx, &guardduty.DeleteDetectorInput{ DetectorId: aws.String(d.Id()), }) - }, guardduty.ErrCodeBadRequestException, "cannot delete detector while it has invited or associated members") + }, "cannot delete detector while it has invited or associated members") - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return diags } @@ -260,12 +261,12 @@ func resourceDetectorDelete(ctx context.Context, d *schema.ResourceData, meta in return diags } -func expandDataSourceConfigurations(tfMap map[string]interface{}) *guardduty.DataSourceConfigurations { +func expandDataSourceConfigurations(tfMap map[string]interface{}) *awstypes.DataSourceConfigurations { if tfMap == nil { return nil } - apiObject := &guardduty.DataSourceConfigurations{} + apiObject := &awstypes.DataSourceConfigurations{} if v, ok := tfMap["kubernetes"].([]interface{}); ok && len(v) > 0 { apiObject.Kubernetes = expandKubernetesConfiguration(v[0].(map[string]interface{})) @@ -282,7 +283,7 @@ func expandDataSourceConfigurations(tfMap map[string]interface{}) *guardduty.Dat return apiObject } -func expandKubernetesConfiguration(tfMap map[string]interface{}) *guardduty.KubernetesConfiguration { +func expandKubernetesConfiguration(tfMap map[string]interface{}) *awstypes.KubernetesConfiguration { if tfMap == nil { return nil } @@ -297,17 +298,17 @@ func expandKubernetesConfiguration(tfMap map[string]interface{}) *guardduty.Kube return nil } - return &guardduty.KubernetesConfiguration{ + return &awstypes.KubernetesConfiguration{ AuditLogs: expandKubernetesAuditLogsConfiguration(m), } } -func expandKubernetesAuditLogsConfiguration(tfMap map[string]interface{}) *guardduty.KubernetesAuditLogsConfiguration { +func expandKubernetesAuditLogsConfiguration(tfMap map[string]interface{}) *awstypes.KubernetesAuditLogsConfiguration { if tfMap == nil { return nil } - apiObject := &guardduty.KubernetesAuditLogsConfiguration{} + apiObject := &awstypes.KubernetesAuditLogsConfiguration{} if v, ok := tfMap["enable"].(bool); ok { apiObject.Enable = aws.Bool(v) @@ -316,7 +317,7 @@ func expandKubernetesAuditLogsConfiguration(tfMap map[string]interface{}) *guard return apiObject } -func expandMalwareProtectionConfiguration(tfMap map[string]interface{}) *guardduty.MalwareProtectionConfiguration { +func expandMalwareProtectionConfiguration(tfMap map[string]interface{}) *awstypes.MalwareProtectionConfiguration { if tfMap == nil { return nil } @@ -331,12 +332,12 @@ func expandMalwareProtectionConfiguration(tfMap map[string]interface{}) *guarddu return nil } - return &guardduty.MalwareProtectionConfiguration{ + return &awstypes.MalwareProtectionConfiguration{ ScanEc2InstanceWithFindings: expandScanEc2InstanceWithFindings(m), } } -func expandScanEc2InstanceWithFindings(tfMap map[string]interface{}) *guardduty.ScanEc2InstanceWithFindings { // nosemgrep:ci.caps3-in-func-name +func expandScanEc2InstanceWithFindings(tfMap map[string]interface{}) *awstypes.ScanEc2InstanceWithFindings { // nosemgrep:ci.caps3-in-func-name if tfMap == nil { return nil } @@ -351,7 +352,7 @@ func expandScanEc2InstanceWithFindings(tfMap map[string]interface{}) *guardduty. return nil } - apiObject := &guardduty.ScanEc2InstanceWithFindings{ + apiObject := &awstypes.ScanEc2InstanceWithFindings{ EbsVolumes: expandMalwareProtectionEBSVolumesConfiguration(m), } @@ -372,12 +373,12 @@ func expandMalwareProtectionEBSVolumesConfiguration(tfMap map[string]interface{} return apiObject } -func expandS3LogsConfiguration(tfMap map[string]interface{}) *guardduty.S3LogsConfiguration { +func expandS3LogsConfiguration(tfMap map[string]interface{}) *awstypes.S3LogsConfiguration { if tfMap == nil { return nil } - apiObject := &guardduty.S3LogsConfiguration{} + apiObject := &awstypes.S3LogsConfiguration{} if v, ok := tfMap["enable"].(bool); ok { apiObject.Enable = aws.Bool(v) @@ -386,7 +387,7 @@ func expandS3LogsConfiguration(tfMap map[string]interface{}) *guardduty.S3LogsCo return apiObject } -func flattenDataSourceConfigurationsResult(apiObject *guardduty.DataSourceConfigurationsResult) map[string]interface{} { +func flattenDataSourceConfigurationsResult(apiObject *awstypes.DataSourceConfigurationsResult) map[string]interface{} { if apiObject == nil { return nil } @@ -408,7 +409,7 @@ func flattenDataSourceConfigurationsResult(apiObject *guardduty.DataSourceConfig return tfMap } -func flattenKubernetesConfiguration(apiObject *guardduty.KubernetesConfigurationResult) map[string]interface{} { +func flattenKubernetesConfiguration(apiObject *awstypes.KubernetesConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } @@ -422,21 +423,19 @@ func flattenKubernetesConfiguration(apiObject *guardduty.KubernetesConfiguration return tfMap } -func flattenKubernetesAuditLogsConfiguration(apiObject *guardduty.KubernetesAuditLogsConfigurationResult) map[string]interface{} { +func flattenKubernetesAuditLogsConfiguration(apiObject *awstypes.KubernetesAuditLogsConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } tfMap := map[string]interface{}{} - if v := apiObject.Status; v != nil { - tfMap["enable"] = aws.StringValue(v) == guardduty.DataSourceStatusEnabled - } + tfMap["enable"] = apiObject.Status == awstypes.DataSourceStatusEnabled return tfMap } -func flattenMalwareProtectionConfiguration(apiObject *guardduty.MalwareProtectionConfigurationResult) map[string]interface{} { +func flattenMalwareProtectionConfiguration(apiObject *awstypes.MalwareProtectionConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } @@ -450,7 +449,7 @@ func flattenMalwareProtectionConfiguration(apiObject *guardduty.MalwareProtectio return tfMap } -func flattenScanEc2InstanceWithFindingsResult(apiObject *guardduty.ScanEc2InstanceWithFindingsResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name +func flattenScanEc2InstanceWithFindingsResult(apiObject *awstypes.ScanEc2InstanceWithFindingsResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name if apiObject == nil { return nil } @@ -464,42 +463,38 @@ func flattenScanEc2InstanceWithFindingsResult(apiObject *guardduty.ScanEc2Instan return tfMap } -func flattenEbsVolumesResult(apiObject *guardduty.EbsVolumesResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name +func flattenEbsVolumesResult(apiObject *awstypes.EbsVolumesResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name if apiObject == nil { return nil } tfMap := map[string]interface{}{} - if v := apiObject.Status; v != nil { - tfMap["enable"] = aws.StringValue(v) == guardduty.DataSourceStatusEnabled - } + tfMap["enable"] = apiObject.Status == awstypes.DataSourceStatusEnabled return tfMap } -func flattenS3LogsConfigurationResult(apiObject *guardduty.S3LogsConfigurationResult) map[string]interface{} { +func flattenS3LogsConfigurationResult(apiObject *awstypes.S3LogsConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } tfMap := map[string]interface{}{} - if v := apiObject.Status; v != nil { - tfMap["enable"] = aws.StringValue(v) == guardduty.DataSourceStatusEnabled - } + tfMap["enable"] = apiObject.Status == awstypes.DataSourceStatusEnabled return tfMap } -func FindDetectorByID(ctx context.Context, conn *guardduty.GuardDuty, id string) (*guardduty.GetDetectorOutput, error) { +func FindDetectorByID(ctx context.Context, conn *guardduty.Client, id string) (*guardduty.GetDetectorOutput, error) { input := &guardduty.GetDetectorInput{ DetectorId: aws.String(id), } - output, err := conn.GetDetectorWithContext(ctx, input) + output, err := conn.GetDetector(ctx, input) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -518,32 +513,30 @@ func FindDetectorByID(ctx context.Context, conn *guardduty.GuardDuty, id string) } // FindDetector returns the ID of the current account's active GuardDuty detector. -func FindDetector(ctx context.Context, conn *guardduty.GuardDuty) (*string, error) { +func FindDetector(ctx context.Context, conn *guardduty.Client) (*string, error) { output, err := findDetectors(ctx, conn) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func findDetectors(ctx context.Context, conn *guardduty.GuardDuty) ([]*string, error) { +func findDetectors(ctx context.Context, conn *guardduty.Client) ([]string, error) { input := &guardduty.ListDetectorsInput{} - var output []*string + var output []string - err := conn.ListDetectorsPagesWithContext(ctx, input, func(page *guardduty.ListDetectorsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := guardduty.NewListDetectorsPaginator(conn, input) - output = append(output, page.DetectorIds...) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - return !lastPage - }) + if err != nil { + return nil, err + } - if err != nil { - return nil, err + output = append(output, page.DetectorIds...) } return output, nil diff --git a/internal/service/guardduty/detector_data_source.go b/internal/service/guardduty/detector_data_source.go index be0e5be96ab..7dd59e4391a 100644 --- a/internal/service/guardduty/detector_data_source.go +++ b/internal/service/guardduty/detector_data_source.go @@ -6,7 +6,7 @@ package guardduty 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" @@ -75,7 +75,7 @@ func DataSourceDetector() *schema.Resource { func dataSourceDetectorRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get(names.AttrID).(string) @@ -86,7 +86,7 @@ func dataSourceDetectorRead(ctx context.Context, d *schema.ResourceData, meta in return sdkdiag.AppendErrorf(diags, "reading this account's single GuardDuty Detector: %s", err) } - detectorID = aws.StringValue(output) + detectorID = aws.ToString(output) } gdo, err := FindDetectorByID(ctx, conn, detectorID) diff --git a/internal/service/guardduty/detector_test.go b/internal/service/guardduty/detector_test.go index 2204a10e088..a73fbcc849e 100644 --- a/internal/service/guardduty/detector_test.go +++ b/internal/service/guardduty/detector_test.go @@ -321,7 +321,7 @@ func testAccDetector_datasources_all(t *testing.T) { func testAccCheckDetectorDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_detector" { @@ -352,7 +352,7 @@ func testAccCheckDetectorExists(ctx context.Context, n string) resource.TestChec return fmt.Errorf("Not found: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) _, err := tfguardduty.FindDetectorByID(ctx, conn, rs.Primary.ID) From f813cd2a9c6545573eaf964d9d11d015730b7d97 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 20:55:48 +0100 Subject: [PATCH 04/22] r/guardduty_detector_feature.go: Migrate to AWS SDK v2 --- .../service/guardduty/detector_feature.go | 117 +++++++----------- .../guardduty/detector_feature_test.go | 2 +- 2 files changed, 43 insertions(+), 76 deletions(-) diff --git a/internal/service/guardduty/detector_feature.go b/internal/service/guardduty/detector_feature.go index eb56faab330..c605cdda898 100644 --- a/internal/service/guardduty/detector_feature.go +++ b/internal/service/guardduty/detector_feature.go @@ -9,12 +9,13 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -37,15 +38,15 @@ func ResourceDetectorFeature() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ names.AttrName: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(guardduty.FeatureAdditionalConfiguration_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.FeatureAdditionalConfiguration](), }, names.AttrStatus: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(guardduty.FeatureStatus_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.FeatureStatus](), }, }, }, @@ -56,15 +57,15 @@ func ResourceDetectorFeature() *schema.Resource { ForceNew: true, }, names.AttrName: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(guardduty.DetectorFeature_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.DetectorFeature](), }, names.AttrStatus: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(guardduty.FeatureStatus_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.FeatureStatus](), }, }, } @@ -72,12 +73,12 @@ func ResourceDetectorFeature() *schema.Resource { func resourceDetectorFeaturePut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID, name := d.Get("detector_id").(string), d.Get(names.AttrName).(string) - feature := &guardduty.DetectorFeatureConfiguration{ - Name: aws.String(name), - Status: aws.String(d.Get(names.AttrStatus).(string)), + feature := awstypes.DetectorFeatureConfiguration{ + Name: awstypes.DetectorFeature(name), + Status: awstypes.FeatureStatus(d.Get(names.AttrStatus).(string)), } if v, ok := d.GetOk("additional_configuration"); ok && len(v.([]interface{})) > 0 { @@ -86,10 +87,10 @@ func resourceDetectorFeaturePut(ctx context.Context, d *schema.ResourceData, met input := &guardduty.UpdateDetectorInput{ DetectorId: aws.String(detectorID), - Features: []*guardduty.DetectorFeatureConfiguration{feature}, + Features: []awstypes.DetectorFeatureConfiguration{feature}, } - _, err := conn.UpdateDetectorWithContext(ctx, input) + _, err := conn.UpdateDetector(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Detector (%s) Feature (%s): %s", detectorID, name, err) @@ -104,7 +105,7 @@ func resourceDetectorFeaturePut(ctx context.Context, d *schema.ResourceData, met func resourceDetectorFeatureRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID, name, err := detectorFeatureParseResourceID(d.Id()) if err != nil { @@ -152,42 +153,38 @@ func detectorFeatureParseResourceID(id string) (string, string, error) { return "", "", fmt.Errorf("unexpected format for ID (%[1]s), expected DETECTORID%[2]sFEATURENAME", id, detectorFeatureResourceIDSeparator) } -func FindDetectorFeatureByTwoPartKey(ctx context.Context, conn *guardduty.GuardDuty, detectorID, name string) (*guardduty.DetectorFeatureConfigurationResult, error) { +func FindDetectorFeatureByTwoPartKey(ctx context.Context, conn *guardduty.Client, detectorID, name string) (*awstypes.DetectorFeatureConfigurationResult, error) { output, err := FindDetectorByID(ctx, conn, detectorID) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(tfslices.Filter(output.Features, func(v *guardduty.DetectorFeatureConfigurationResult) bool { - return aws.StringValue(v.Name) == name + return tfresource.AssertSingleValueResult(tfslices.Filter(output.Features, func(v awstypes.DetectorFeatureConfigurationResult) bool { + return string(v.Name) == name })) } -func expandDetectorAdditionalConfiguration(tfMap map[string]interface{}) *guardduty.DetectorAdditionalConfiguration { - if tfMap == nil { - return nil - } - - apiObject := &guardduty.DetectorAdditionalConfiguration{} +func expandDetectorAdditionalConfiguration(tfMap map[string]interface{}) awstypes.DetectorAdditionalConfiguration { + apiObject := awstypes.DetectorAdditionalConfiguration{} if v, ok := tfMap[names.AttrName].(string); ok && v != "" { - apiObject.Name = aws.String(v) + apiObject.Name = awstypes.FeatureAdditionalConfiguration(v) } if v, ok := tfMap[names.AttrStatus].(string); ok && v != "" { - apiObject.Status = aws.String(v) + apiObject.Status = awstypes.FeatureStatus(v) } return apiObject } -func expandDetectorAdditionalConfigurations(tfList []interface{}) []*guardduty.DetectorAdditionalConfiguration { +func expandDetectorAdditionalConfigurations(tfList []interface{}) []awstypes.DetectorAdditionalConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*guardduty.DetectorAdditionalConfiguration + var apiObjects []awstypes.DetectorAdditionalConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -198,39 +195,26 @@ func expandDetectorAdditionalConfigurations(tfList []interface{}) []*guardduty.D apiObject := expandDetectorAdditionalConfiguration(tfMap) - if apiObject == nil { - continue - } - apiObjects = append(apiObjects, apiObject) } return apiObjects } -func flattenDetectorFeatureConfigurationResult(apiObject *guardduty.DetectorFeatureConfigurationResult) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenDetectorFeatureConfigurationResult(apiObject awstypes.DetectorFeatureConfigurationResult) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.AdditionalConfiguration; v != nil { tfMap["additional_configuration"] = flattenDetectorAdditionalConfigurationResults(v) } - if v := apiObject.Name; v != nil { - tfMap[names.AttrName] = aws.StringValue(v) - } - - if v := apiObject.Status; v != nil { - tfMap[names.AttrStatus] = aws.StringValue(v) - } + tfMap[names.AttrName] = string(apiObject.Name) + tfMap[names.AttrStatus] = string(apiObject.Status) return tfMap } -func flattenDetectorFeatureConfigurationResults(apiObjects []*guardduty.DetectorFeatureConfigurationResult) []interface{} { +func flattenDetectorFeatureConfigurationResults(apiObjects []awstypes.DetectorFeatureConfigurationResult) []interface{} { if len(apiObjects) == 0 { return nil } @@ -238,35 +222,22 @@ func flattenDetectorFeatureConfigurationResults(apiObjects []*guardduty.Detector var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenDetectorFeatureConfigurationResult(apiObject)) } return tfList } -func flattenDetectorAdditionalConfigurationResult(apiObject *guardduty.DetectorAdditionalConfigurationResult) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenDetectorAdditionalConfigurationResult(apiObject awstypes.DetectorAdditionalConfigurationResult) map[string]interface{} { tfMap := map[string]interface{}{} - if v := apiObject.Name; v != nil { - tfMap[names.AttrName] = aws.StringValue(v) - } - - if v := apiObject.Status; v != nil { - tfMap[names.AttrStatus] = aws.StringValue(v) - } + tfMap[names.AttrName] = string(apiObject.Name) + tfMap[names.AttrStatus] = string(apiObject.Status) return tfMap } -func flattenDetectorAdditionalConfigurationResults(apiObjects []*guardduty.DetectorAdditionalConfigurationResult) []interface{} { +func flattenDetectorAdditionalConfigurationResults(apiObjects []awstypes.DetectorAdditionalConfigurationResult) []interface{} { if len(apiObjects) == 0 { return nil } @@ -274,10 +245,6 @@ func flattenDetectorAdditionalConfigurationResults(apiObjects []*guardduty.Detec var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenDetectorAdditionalConfigurationResult(apiObject)) } diff --git a/internal/service/guardduty/detector_feature_test.go b/internal/service/guardduty/detector_feature_test.go index c8fe60a0010..08c825bdc38 100644 --- a/internal/service/guardduty/detector_feature_test.go +++ b/internal/service/guardduty/detector_feature_test.go @@ -170,7 +170,7 @@ func testAccCheckDetectorFeatureExists(ctx context.Context, n string) resource.T return fmt.Errorf("Not found: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) _, err := tfguardduty.FindDetectorFeatureByTwoPartKey(ctx, conn, rs.Primary.Attributes["detector_id"], rs.Primary.Attributes[names.AttrName]) From 0f24685ef99ba28e95677b0766e5d2fae13b4a04 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 21:18:45 +0100 Subject: [PATCH 05/22] r/guardduty_filter: Migrate to AWS SDK v2 --- internal/service/guardduty/filter.go | 84 ++++++++++++----------- internal/service/guardduty/filter_test.go | 18 ++--- 2 files changed, 52 insertions(+), 50 deletions(-) diff --git a/internal/service/guardduty/filter.go b/internal/service/guardduty/filter.go index 9e5aadb28a7..f73005ed0f8 100644 --- a/internal/service/guardduty/filter.go +++ b/internal/service/guardduty/filter.go @@ -12,14 +12,16 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -41,9 +43,9 @@ func ResourceFilter() *schema.Resource { Schema: map[string]*schema.Schema{ names.AttrAction: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(guardduty.FilterAction_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.FilterAction](), }, names.AttrARN: { Type: schema.TypeString, @@ -137,14 +139,14 @@ func ResourceFilter() *schema.Resource { func resourceFilterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) input := guardduty.CreateFilterInput{ - Action: aws.String(d.Get(names.AttrAction).(string)), + Action: awstypes.FilterAction(d.Get(names.AttrAction).(string)), Description: aws.String(d.Get(names.AttrDescription).(string)), DetectorId: aws.String(d.Get("detector_id").(string)), Name: aws.String(d.Get(names.AttrName).(string)), - Rank: aws.Int64(int64(d.Get("rank").(int))), + Rank: aws.Int32(int32(d.Get("rank").(int))), Tags: getTagsIn(ctx), } @@ -154,20 +156,20 @@ func resourceFilterCreate(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "creating GuardDuty Filter: %s", err) } - log.Printf("[DEBUG] Creating GuardDuty Filter: %s", input) - output, err := conn.CreateFilterWithContext(ctx, &input) + log.Printf("[DEBUG] Creating GuardDuty Filter: %+v", input) + output, err := conn.CreateFilter(ctx, &input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating GuardDuty Filter: %s", err) } - d.SetId(filterCreateID(d.Get("detector_id").(string), aws.StringValue(output.Name))) + d.SetId(filterCreateID(d.Get("detector_id").(string), aws.ToString(output.Name))) return append(diags, resourceFilterRead(ctx, d, meta)...) } func resourceFilterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) var detectorID, name string var err error @@ -188,11 +190,11 @@ func resourceFilterRead(ctx context.Context, d *schema.ResourceData, meta interf FilterName: aws.String(name), } - log.Printf("[DEBUG] Reading GuardDuty Filter: %s", input) - filter, err := conn.GetFilterWithContext(ctx, &input) + log.Printf("[DEBUG] Reading GuardDuty Filter: %+v", input) + filter, err := conn.GetFilter(ctx, &input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected since no such resource found.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected since no such resource found.") { log.Printf("[WARN] GuardDuty detector %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -229,15 +231,15 @@ func resourceFilterRead(ctx context.Context, d *schema.ResourceData, meta interf func resourceFilterUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) if d.HasChanges(names.AttrAction, names.AttrDescription, "finding_criteria", "rank") { input := guardduty.UpdateFilterInput{ - Action: aws.String(d.Get(names.AttrAction).(string)), + Action: awstypes.FilterAction(d.Get(names.AttrAction).(string)), Description: aws.String(d.Get(names.AttrDescription).(string)), DetectorId: aws.String(d.Get("detector_id").(string)), FilterName: aws.String(d.Get(names.AttrName).(string)), - Rank: aws.Int64(int64(d.Get("rank").(int))), + Rank: aws.Int32(int32(d.Get("rank").(int))), } var err error @@ -246,7 +248,7 @@ func resourceFilterUpdate(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "updating GuardDuty Filter %s: %s", d.Id(), err) } - _, err = conn.UpdateFilterWithContext(ctx, &input) + _, err = conn.UpdateFilter(ctx, &input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Filter %s: %s", d.Id(), err) } @@ -257,7 +259,7 @@ func resourceFilterUpdate(ctx context.Context, d *schema.ResourceData, meta inte func resourceFilterDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorId := d.Get("detector_id").(string) name := d.Get(names.AttrName).(string) @@ -267,10 +269,10 @@ func resourceFilterDelete(ctx context.Context, d *schema.ResourceData, meta inte DetectorId: aws.String(detectorId), } - log.Printf("[DEBUG] Delete GuardDuty Filter: %s", input) + log.Printf("[DEBUG] Delete GuardDuty Filter: %+v", input) - _, err := conn.DeleteFilterWithContext(ctx, &input) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected since no such resource found.") { + _, err := conn.DeleteFilter(ctx, &input) + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected since no such resource found.") { return diags } if err != nil { @@ -293,32 +295,32 @@ func FilterParseID(importedId string) (string, string, error) { return parts[0], parts[1], nil } -func expandFindingCriteria(raw []interface{}) (*guardduty.FindingCriteria, error) { +func expandFindingCriteria(raw []interface{}) (*awstypes.FindingCriteria, error) { findingCriteria := raw[0].(map[string]interface{}) inputFindingCriteria := findingCriteria["criterion"].(*schema.Set).List() - criteria := map[string]*guardduty.Condition{} + criteria := map[string]awstypes.Condition{} for _, criterion := range inputFindingCriteria { typedCriterion := criterion.(map[string]interface{}) field := typedCriterion[names.AttrField].(string) - condition := guardduty.Condition{} + condition := awstypes.Condition{} if x, ok := typedCriterion["equals"]; ok { if v, ok := x.([]interface{}); ok && len(v) > 0 { - foo := make([]*string, len(v)) + foo := make([]string, len(v)) for i := range v { s := v[i].(string) - foo[i] = &s + foo[i] = s } condition.Equals = foo } } if x, ok := typedCriterion["not_equals"]; ok { if v, ok := x.([]interface{}); ok && len(v) > 0 { - foo := make([]*string, len(v)) + foo := make([]string, len(v)) for i := range v { s := v[i].(string) - foo[i] = &s + foo[i] = s } condition.NotEquals = foo } @@ -359,10 +361,10 @@ func expandFindingCriteria(raw []interface{}) (*guardduty.FindingCriteria, error condition.LessThanOrEqual = aws.Int64(i) } } - criteria[field] = &condition + criteria[field] = condition } - return &guardduty.FindingCriteria{Criterion: criteria}, nil + return &awstypes.FindingCriteria{Criterion: criteria}, nil } func expandConditionIntField(field, v string) (int64, error) { @@ -377,7 +379,7 @@ func expandConditionIntField(field, v string) (int64, error) { return strconv.ParseInt(v, 10, 64) } -func flattenFindingCriteria(findingCriteriaRemote *guardduty.FindingCriteria) []interface{} { +func flattenFindingCriteria(findingCriteriaRemote *awstypes.FindingCriteria) []interface{} { var flatCriteria []interface{} for field, conditions := range findingCriteriaRemote.Criterion { @@ -385,21 +387,21 @@ func flattenFindingCriteria(findingCriteriaRemote *guardduty.FindingCriteria) [] names.AttrField: field, } if len(conditions.Equals) > 0 { - criterion["equals"] = aws.StringValueSlice(conditions.Equals) + criterion["equals"] = conditions.Equals } if len(conditions.NotEquals) > 0 { - criterion["not_equals"] = aws.StringValueSlice(conditions.NotEquals) + criterion["not_equals"] = conditions.NotEquals } - if v := aws.Int64Value(conditions.GreaterThan); v > 0 { + if v := aws.ToInt64(conditions.GreaterThan); v > 0 { criterion["greater_than"] = flattenConditionIntField(field, v) } - if v := aws.Int64Value(conditions.GreaterThanOrEqual); v > 0 { + if v := aws.ToInt64(conditions.GreaterThanOrEqual); v > 0 { criterion["greater_than_or_equal"] = flattenConditionIntField(field, v) } - if v := aws.Int64Value(conditions.LessThan); v > 0 { + if v := aws.ToInt64(conditions.LessThan); v > 0 { criterion["less_than"] = flattenConditionIntField(field, v) } - if v := aws.Int64Value(conditions.LessThanOrEqual); v > 0 { + if v := aws.ToInt64(conditions.LessThanOrEqual); v > 0 { criterion["less_than_or_equal"] = flattenConditionIntField(field, v) } flatCriteria = append(flatCriteria, criterion) diff --git a/internal/service/guardduty/filter_test.go b/internal/service/guardduty/filter_test.go index d8537f631c5..d737cfae642 100644 --- a/internal/service/guardduty/filter_test.go +++ b/internal/service/guardduty/filter_test.go @@ -9,11 +9,11 @@ import ( "testing" "github.com/YakDriver/regexache" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/acmpca" acmpca_types "github.com/aws/aws-sdk-go-v2/service/acmpca/types" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -218,7 +218,7 @@ func testAccFilter_disappears(t *testing.T) { func testAccCheckFilterDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_filter" { @@ -235,9 +235,9 @@ func testAccCheckFilterDestroy(ctx context.Context) resource.TestCheckFunc { FilterName: aws.String(filterName), } - _, err = conn.GetFilterWithContext(ctx, input) + _, err = conn.GetFilter(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil } return err @@ -266,12 +266,12 @@ func testAccCheckFilterExists(ctx context.Context, name string, filter *guarddut return err } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) input := guardduty.GetFilterInput{ DetectorId: aws.String(detectorID), FilterName: aws.String(name), } - filter, err = conn.GetFilterWithContext(ctx, &input) + filter, err = conn.GetFilter(ctx, &input) return err } @@ -456,7 +456,7 @@ func testAccCheckACMPCACertificateAuthorityDestroy(ctx context.Context) resource return err } - if output != nil && output.CertificateAuthority != nil && aws.StringValue(output.CertificateAuthority.Arn) == rs.Primary.ID && output.CertificateAuthority.Status != acmpca_types.CertificateAuthorityStatusDeleted { + if output != nil && output.CertificateAuthority != nil && aws.ToString(output.CertificateAuthority.Arn) == rs.Primary.ID && output.CertificateAuthority.Status != acmpca_types.CertificateAuthorityStatusDeleted { return fmt.Errorf("ACM PCA Certificate Authority %q still exists in non-DELETED state: %s", rs.Primary.ID, string(output.CertificateAuthority.Status)) } } From bddcca60574d7d0c7f419016cc2a5e984b2c2bf9 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 21:22:36 +0100 Subject: [PATCH 06/22] d/guardduty_finding_ids: Migrate to AWS SDK v2 --- .../guardduty/finding_ids_data_source.go | 42 +++++++++++-------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/internal/service/guardduty/finding_ids_data_source.go b/internal/service/guardduty/finding_ids_data_source.go index 55f1de1cde3..1739b2139b4 100644 --- a/internal/service/guardduty/finding_ids_data_source.go +++ b/internal/service/guardduty/finding_ids_data_source.go @@ -6,14 +6,15 @@ package guardduty import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/framework" "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" "github.com/hashicorp/terraform-provider-aws/names" @@ -55,7 +56,7 @@ func (d *dataSourceFindingIds) Schema(ctx context.Context, req datasource.Schema } func (d *dataSourceFindingIds) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - conn := d.Meta().GuardDutyConn(ctx) + conn := d.Meta().GuardDutyClient(ctx) var data dataSourceFindingIdsData resp.Diagnostics.Append(req.Config.Get(ctx, &data)...) @@ -73,32 +74,37 @@ func (d *dataSourceFindingIds) Read(ctx context.Context, req datasource.ReadRequ } data.ID = types.StringValue(data.DetectorID.ValueString()) - data.FindingIDs = flex.FlattenFrameworkStringList(ctx, out) + data.FindingIDs = flex.FlattenFrameworkStringValueList(ctx, out) data.HasFindings = types.BoolValue((len(out) > 0)) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) } -func findFindingIds(ctx context.Context, conn *guardduty.GuardDuty, id string) ([]*string, error) { +func findFindingIds(ctx context.Context, conn *guardduty.Client, id string) ([]string, error) { in := &guardduty.ListFindingsInput{ DetectorId: aws.String(id), } - var findingIds []*string - err := conn.ListFindingsPagesWithContext(ctx, in, func(page *guardduty.ListFindingsOutput, lastPage bool) bool { - findingIds = append(findingIds, page.FindingIds...) - return !lastPage - }) + var findingIds []string + + pages := guardduty.NewListFindingsPaginator(conn, in) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: in, + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: in, + } } - } - if err != nil { - return nil, err + if err != nil { + return nil, err + } + + findingIds = append(findingIds, page.FindingIds...) + } return findingIds, nil From 4e900cbec789f523b34c3b662e8e73f5e9cc9b81 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 21:34:34 +0100 Subject: [PATCH 07/22] r/guardduty_invite_accepter: Migrate to AWS SDK v2 --- internal/service/guardduty/invite_accepter.go | 82 ++++++++++--------- .../service/guardduty/invite_accepter_test.go | 23 +++--- 2 files changed, 56 insertions(+), 49 deletions(-) diff --git a/internal/service/guardduty/invite_accepter.go b/internal/service/guardduty/invite_accepter.go index e34966ad1ac..463a4ca94af 100644 --- a/internal/service/guardduty/invite_accepter.go +++ b/internal/service/guardduty/invite_accepter.go @@ -9,13 +9,14 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "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-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/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -53,7 +54,7 @@ func ResourceInviteAccepter() *schema.Resource { func resourceInviteAccepterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get("detector_id").(string) invitationID := "" @@ -62,42 +63,47 @@ func resourceInviteAccepterCreate(ctx context.Context, d *schema.ResourceData, m listInvitationsInput := &guardduty.ListInvitationsInput{} err := retry.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *retry.RetryError { - log.Printf("[DEBUG] Listing GuardDuty Invitations: %s", listInvitationsInput) - err := conn.ListInvitationsPagesWithContext(ctx, listInvitationsInput, func(page *guardduty.ListInvitationsOutput, lastPage bool) bool { - for _, invitation := range page.Invitations { - if aws.StringValue(invitation.AccountId) == masterAccountID { - invitationID = aws.StringValue(invitation.InvitationId) - return false - } + log.Printf("[DEBUG] Listing GuardDuty Invitations: %+v", listInvitationsInput) + pages := guardduty.NewListInvitationsPaginator(conn, listInvitationsInput) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return retry.NonRetryableError(err) } - return !lastPage - }) - if err != nil { - return retry.NonRetryableError(err) - } + if invitationID == "" { + return retry.RetryableError(fmt.Errorf("unable to find pending GuardDuty Invitation for detector ID (%s) from master account ID (%s)", detectorID, masterAccountID)) + } - if invitationID == "" { - return retry.RetryableError(fmt.Errorf("unable to find pending GuardDuty Invitation for detector ID (%s) from master account ID (%s)", detectorID, masterAccountID)) + for _, invitation := range page.Invitations { + if aws.ToString(invitation.AccountId) == masterAccountID { + invitationID = aws.ToString(invitation.InvitationId) + break + } + } } return nil }) if tfresource.TimedOut(err) { - err = conn.ListInvitationsPagesWithContext(ctx, listInvitationsInput, func(page *guardduty.ListInvitationsOutput, lastPage bool) bool { + pages := guardduty.NewListInvitationsPaginator(conn, listInvitationsInput) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return sdkdiag.AppendErrorf(diags, "listing GuardDuty Invitations: %s", err) + } + for _, invitation := range page.Invitations { - if aws.StringValue(invitation.AccountId) == masterAccountID { - invitationID = aws.StringValue(invitation.InvitationId) - return false + if aws.ToString(invitation.AccountId) == masterAccountID { + invitationID = aws.ToString(invitation.InvitationId) + break } } - return !lastPage - }) - } - - if err != nil { - return sdkdiag.AppendErrorf(diags, "listing GuardDuty Invitations: %s", err) + } } acceptInvitationInput := &guardduty.AcceptInvitationInput{ @@ -106,8 +112,8 @@ func resourceInviteAccepterCreate(ctx context.Context, d *schema.ResourceData, m MasterId: aws.String(masterAccountID), } - log.Printf("[DEBUG] Accepting GuardDuty Invitation: %s", acceptInvitationInput) - _, err = conn.AcceptInvitationWithContext(ctx, acceptInvitationInput) + log.Printf("[DEBUG] Accepting GuardDuty Invitation: %+v", acceptInvitationInput) + _, err = conn.AcceptInvitation(ctx, acceptInvitationInput) if err != nil { return sdkdiag.AppendErrorf(diags, "accepting GuardDuty Invitation (%s): %s", invitationID, err) @@ -120,16 +126,16 @@ func resourceInviteAccepterCreate(ctx context.Context, d *schema.ResourceData, m func resourceInviteAccepterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) input := &guardduty.GetMasterAccountInput{ DetectorId: aws.String(d.Id()), } - log.Printf("[DEBUG] Reading GuardDuty Master Account: %s", input) - output, err := conn.GetMasterAccountWithContext(ctx, input) + log.Printf("[DEBUG] Reading GuardDuty Master Account: %+v", input) + output, err := conn.GetMasterAccount(ctx, input) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { log.Printf("[WARN] GuardDuty Detector %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -151,16 +157,16 @@ func resourceInviteAccepterRead(ctx context.Context, d *schema.ResourceData, met func resourceInviteAccepterDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) input := &guardduty.DisassociateFromMasterAccountInput{ DetectorId: aws.String(d.Id()), } - log.Printf("[DEBUG] Disassociating GuardDuty Detector (%s) from GuardDuty Master Account: %s", d.Id(), input) - _, err := conn.DisassociateFromMasterAccountWithContext(ctx, input) + log.Printf("[DEBUG] Disassociating GuardDuty Detector (%s) from GuardDuty Master Account: %+v", d.Id(), input) + _, err := conn.DisassociateFromMasterAccount(ctx, input) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return diags } diff --git a/internal/service/guardduty/invite_accepter_test.go b/internal/service/guardduty/invite_accepter_test.go index 3e3c0521a8b..efebf84277d 100644 --- a/internal/service/guardduty/invite_accepter_test.go +++ b/internal/service/guardduty/invite_accepter_test.go @@ -8,13 +8,14 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -55,7 +56,7 @@ func testAccInviteAccepter_basic(t *testing.T) { func testAccCheckInviteAccepterDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_invite_accepter" { @@ -66,9 +67,9 @@ func testAccCheckInviteAccepterDestroy(ctx context.Context) resource.TestCheckFu DetectorId: aws.String(rs.Primary.ID), } - output, err := conn.GetMasterAccountWithContext(ctx, input) + output, err := conn.GetMasterAccount(ctx, input) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil } @@ -76,11 +77,11 @@ func testAccCheckInviteAccepterDestroy(ctx context.Context) resource.TestCheckFu return err } - if output == nil || output.Master == nil || aws.StringValue(output.Master.AccountId) != rs.Primary.Attributes["master_account_id"] { + if output == nil || output.Master == nil || aws.ToString(output.Master.AccountId) != rs.Primary.Attributes["master_account_id"] { continue } - return fmt.Errorf("GuardDuty Detector (%s) still has GuardDuty Master Account ID (%s)", rs.Primary.ID, aws.StringValue(output.Master.AccountId)) + return fmt.Errorf("GuardDuty Detector (%s) still has GuardDuty Master Account ID (%s)", rs.Primary.ID, aws.ToString(output.Master.AccountId)) } return nil @@ -98,19 +99,19 @@ func testAccCheckInviteAccepterExists(ctx context.Context, resourceName string) return fmt.Errorf("Resource (%s) has empty ID", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) input := &guardduty.GetMasterAccountInput{ DetectorId: aws.String(rs.Primary.ID), } - output, err := conn.GetMasterAccountWithContext(ctx, input) + output, err := conn.GetMasterAccount(ctx, input) if err != nil { return err } - if output == nil || output.Master == nil || aws.StringValue(output.Master.AccountId) == "" { + if output == nil || output.Master == nil || aws.ToString(output.Master.AccountId) == "" { return fmt.Errorf("no master account found for: %s", resourceName) } From 87d327e35f13fb7ce80fad48e1419a15ed6640f4 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 21:40:43 +0100 Subject: [PATCH 08/22] r/guardduty_ipset: Migrate to AWS SDK v2 --- internal/service/guardduty/ipset.go | 67 ++++++++++++------------ internal/service/guardduty/ipset_test.go | 19 +++---- 2 files changed, 44 insertions(+), 42 deletions(-) diff --git a/internal/service/guardduty/ipset.go b/internal/service/guardduty/ipset.go index a0414162b3b..11e89d476f4 100644 --- a/internal/service/guardduty/ipset.go +++ b/internal/service/guardduty/ipset.go @@ -10,15 +10,16 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "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/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -53,10 +54,10 @@ func ResourceIPSet() *schema.Resource { Required: true, }, names.AttrFormat: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(guardduty.IpSetFormat_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.IpSetFormat](), }, names.AttrLocation: { Type: schema.TypeString, @@ -76,26 +77,26 @@ func ResourceIPSet() *schema.Resource { func resourceIPSetCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get("detector_id").(string) input := &guardduty.CreateIPSetInput{ DetectorId: aws.String(detectorID), Name: aws.String(d.Get(names.AttrName).(string)), - Format: aws.String(d.Get(names.AttrFormat).(string)), + Format: awstypes.IpSetFormat(d.Get(names.AttrFormat).(string)), Location: aws.String(d.Get(names.AttrLocation).(string)), Activate: aws.Bool(d.Get("activate").(bool)), Tags: getTagsIn(ctx), } - resp, err := conn.CreateIPSetWithContext(ctx, input) + resp, err := conn.CreateIPSet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating GuardDuty IPSet (%s): %s", d.Get(names.AttrName).(string), err) } stateConf := &retry.StateChangeConf{ - Pending: []string{guardduty.IpSetStatusActivating, guardduty.IpSetStatusDeactivating}, - Target: []string{guardduty.IpSetStatusActive, guardduty.IpSetStatusInactive}, + Pending: enum.Slice(awstypes.IpSetStatusActivating, awstypes.IpSetStatusDeactivating), + Target: enum.Slice(awstypes.IpSetStatusActive, awstypes.IpSetStatusInactive), Refresh: ipsetRefreshStatusFunc(ctx, conn, *resp.IpSetId, detectorID), Timeout: 5 * time.Minute, MinTimeout: 3 * time.Second, @@ -113,7 +114,7 @@ func resourceIPSetCreate(ctx context.Context, d *schema.ResourceData, meta inter func resourceIPSetRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) ipSetId, detectorId, err := DecodeIPSetID(d.Id()) if err != nil { @@ -124,9 +125,9 @@ func resourceIPSetRead(ctx context.Context, d *schema.ResourceData, meta interfa IpSetId: aws.String(ipSetId), } - resp, err := conn.GetIPSetWithContext(ctx, input) + resp, err := conn.GetIPSet(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { log.Printf("[WARN] GuardDuty IPSet (%s) not found, removing from state", ipSetId) d.SetId("") return diags @@ -147,7 +148,7 @@ func resourceIPSetRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set(names.AttrFormat, resp.Format) d.Set(names.AttrLocation, resp.Location) d.Set(names.AttrName, resp.Name) - d.Set("activate", aws.StringValue(resp.Status) == guardduty.IpSetStatusActive) + d.Set("activate", resp.Status == awstypes.IpSetStatusActive) setTagsOut(ctx, resp.Tags) @@ -156,7 +157,7 @@ func resourceIPSetRead(ctx context.Context, d *schema.ResourceData, meta interfa func resourceIPSetUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) ipSetId, detectorId, err := DecodeIPSetID(d.Id()) if err != nil { @@ -179,7 +180,7 @@ func resourceIPSetUpdate(ctx context.Context, d *schema.ResourceData, meta inter input.Activate = aws.Bool(d.Get("activate").(bool)) } - _, err = conn.UpdateIPSetWithContext(ctx, input) + _, err = conn.UpdateIPSet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty IPSet (%s): %s", d.Id(), err) } @@ -190,7 +191,7 @@ func resourceIPSetUpdate(ctx context.Context, d *schema.ResourceData, meta inter func resourceIPSetDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) ipSetId, detectorId, err := DecodeIPSetID(d.Id()) if err != nil { @@ -201,20 +202,20 @@ func resourceIPSetDelete(ctx context.Context, d *schema.ResourceData, meta inter IpSetId: aws.String(ipSetId), } - _, err = conn.DeleteIPSetWithContext(ctx, input) + _, err = conn.DeleteIPSet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "deleting GuardDuty IPSet (%s): %s", d.Id(), err) } stateConf := &retry.StateChangeConf{ - Pending: []string{ - guardduty.IpSetStatusActive, - guardduty.IpSetStatusActivating, - guardduty.IpSetStatusInactive, - guardduty.IpSetStatusDeactivating, - guardduty.IpSetStatusDeletePending, - }, - Target: []string{guardduty.IpSetStatusDeleted}, + Pending: enum.Slice( + awstypes.IpSetStatusActive, + awstypes.IpSetStatusActivating, + awstypes.IpSetStatusInactive, + awstypes.IpSetStatusDeactivating, + awstypes.IpSetStatusDeletePending, + ), + Target: enum.Slice(awstypes.IpSetStatusDeleted), Refresh: ipsetRefreshStatusFunc(ctx, conn, ipSetId, detectorId), Timeout: 5 * time.Minute, MinTimeout: 3 * time.Second, @@ -228,17 +229,17 @@ func resourceIPSetDelete(ctx context.Context, d *schema.ResourceData, meta inter return diags } -func ipsetRefreshStatusFunc(ctx context.Context, conn *guardduty.GuardDuty, ipSetID, detectorID string) retry.StateRefreshFunc { +func ipsetRefreshStatusFunc(ctx context.Context, conn *guardduty.Client, ipSetID, detectorID string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &guardduty.GetIPSetInput{ DetectorId: aws.String(detectorID), IpSetId: aws.String(ipSetID), } - resp, err := conn.GetIPSetWithContext(ctx, input) + resp, err := conn.GetIPSet(ctx, input) if err != nil { return nil, "failed", err } - return resp, *resp.Status, nil + return resp, string(resp.Status), nil } } diff --git a/internal/service/guardduty/ipset_test.go b/internal/service/guardduty/ipset_test.go index 57097d820f9..02a1db189a8 100644 --- a/internal/service/guardduty/ipset_test.go +++ b/internal/service/guardduty/ipset_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfguardduty "github.com/hashicorp/terraform-provider-aws/internal/service/guardduty" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -118,7 +119,7 @@ func testAccIPSet_tags(t *testing.T) { func testAccCheckIPSetDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_ipset" { @@ -134,15 +135,15 @@ func testAccCheckIPSetDestroy(ctx context.Context) resource.TestCheckFunc { DetectorId: aws.String(detectorId), } - resp, err := conn.GetIPSetWithContext(ctx, input) + resp, err := conn.GetIPSet(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil } return err } - if *resp.Status == guardduty.IpSetStatusDeletePending || *resp.Status == guardduty.IpSetStatusDeleted { + if resp.Status == awstypes.IpSetStatusDeletePending || resp.Status == awstypes.IpSetStatusDeleted { return nil } @@ -170,8 +171,8 @@ func testAccCheckIPSetExists(ctx context.Context, name string) resource.TestChec IpSetId: aws.String(ipSetId), } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) - _, err = conn.GetIPSetWithContext(ctx, input) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) + _, err = conn.GetIPSet(ctx, input) return err } } From 5a5fb9aadcbd9c654c546fcb2a22c09dd66ffc92 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 21:47:12 +0100 Subject: [PATCH 09/22] r/guardduty_member: Migrate to AWS SDK v2 --- internal/service/guardduty/member.go | 69 ++++++++++++----------- internal/service/guardduty/member_test.go | 21 +++---- 2 files changed, 46 insertions(+), 44 deletions(-) diff --git a/internal/service/guardduty/member.go b/internal/service/guardduty/member.go index bf9bb797ea6..bd53ee4eba2 100644 --- a/internal/service/guardduty/member.go +++ b/internal/service/guardduty/member.go @@ -10,13 +10,14 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "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-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/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -80,20 +81,20 @@ func ResourceMember() *schema.Resource { func resourceMemberCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) accountID := d.Get(names.AttrAccountID).(string) detectorID := d.Get("detector_id").(string) input := guardduty.CreateMembersInput{ - AccountDetails: []*guardduty.AccountDetail{{ + AccountDetails: []awstypes.AccountDetail{{ AccountId: aws.String(accountID), Email: aws.String(d.Get(names.AttrEmail).(string)), }}, DetectorId: aws.String(detectorID), } - log.Printf("[DEBUG] Creating GuardDuty Member: %s", input) - _, err := conn.CreateMembersWithContext(ctx, &input) + log.Printf("[DEBUG] Creating GuardDuty Member: %+v", input) + _, err := conn.CreateMembers(ctx, &input) if err != nil { return sdkdiag.AppendErrorf(diags, "Creating GuardDuty Member failed: %s", err) } @@ -106,13 +107,13 @@ func resourceMemberCreate(ctx context.Context, d *schema.ResourceData, meta inte imi := &guardduty.InviteMembersInput{ DetectorId: aws.String(detectorID), - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DisableEmailNotification: aws.Bool(d.Get("disable_email_notification").(bool)), Message: aws.String(d.Get("invitation_message").(string)), } - log.Printf("[INFO] Inviting GuardDuty Member: %s", input) - _, err = conn.InviteMembersWithContext(ctx, imi) + log.Printf("[INFO] Inviting GuardDuty Member: %+v", input) + _, err = conn.InviteMembers(ctx, imi) if err != nil { return sdkdiag.AppendErrorf(diags, "inviting GuardDuty Member %q: %s", d.Id(), err) } @@ -127,7 +128,7 @@ func resourceMemberCreate(ctx context.Context, d *schema.ResourceData, meta inte func resourceMemberRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) accountID, detectorID, err := DecodeMemberID(d.Id()) if err != nil { @@ -135,14 +136,14 @@ func resourceMemberRead(ctx context.Context, d *schema.ResourceData, meta interf } input := guardduty.GetMembersInput{ - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DetectorId: aws.String(detectorID), } - log.Printf("[DEBUG] Reading GuardDuty Member: %s", input) - gmo, err := conn.GetMembersWithContext(ctx, &input) + log.Printf("[DEBUG] Reading GuardDuty Member: %+v", input) + gmo, err := conn.GetMembers(ctx, &input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { log.Printf("[WARN] GuardDuty detector %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -161,7 +162,7 @@ func resourceMemberRead(ctx context.Context, d *schema.ResourceData, meta interf d.Set("detector_id", detectorID) d.Set(names.AttrEmail, member.Email) - status := aws.StringValue(member.RelationshipStatus) + status := aws.ToString(member.RelationshipStatus) d.Set("relationship_status", status) // https://docs.aws.amazon.com/guardduty/latest/ug/list-members.html @@ -175,7 +176,7 @@ func resourceMemberRead(ctx context.Context, d *schema.ResourceData, meta interf func resourceMemberUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) accountID, detectorID, err := DecodeMemberID(d.Id()) if err != nil { @@ -186,20 +187,20 @@ func resourceMemberUpdate(ctx context.Context, d *schema.ResourceData, meta inte if d.Get("invite").(bool) { input := &guardduty.InviteMembersInput{ DetectorId: aws.String(detectorID), - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DisableEmailNotification: aws.Bool(d.Get("disable_email_notification").(bool)), Message: aws.String(d.Get("invitation_message").(string)), } - log.Printf("[INFO] Inviting GuardDuty Member: %s", input) - output, err := conn.InviteMembersWithContext(ctx, input) + log.Printf("[INFO] Inviting GuardDuty Member: %+v", input) + output, err := conn.InviteMembers(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "inviting GuardDuty Member %q: %s", d.Id(), err) } // {"unprocessedAccounts":[{"result":"The request is rejected because the current account has already invited or is already the GuardDuty master of the given member account ID.","accountId":"067819342479"}]} if len(output.UnprocessedAccounts) > 0 { - return sdkdiag.AppendErrorf(diags, "inviting GuardDuty Member %q: %s", d.Id(), aws.StringValue(output.UnprocessedAccounts[0].Result)) + return sdkdiag.AppendErrorf(diags, "inviting GuardDuty Member %q: %s", d.Id(), aws.ToString(output.UnprocessedAccounts[0].Result)) } err = inviteMemberWaiter(ctx, accountID, detectorID, d.Timeout(schema.TimeoutUpdate), conn) @@ -208,11 +209,11 @@ func resourceMemberUpdate(ctx context.Context, d *schema.ResourceData, meta inte } } else { input := &guardduty.DisassociateMembersInput{ - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DetectorId: aws.String(detectorID), } - log.Printf("[INFO] Disassociating GuardDuty Member: %s", input) - _, err := conn.DisassociateMembersWithContext(ctx, input) + log.Printf("[INFO] Disassociating GuardDuty Member: %+v", input) + _, err := conn.DisassociateMembers(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "disassociating GuardDuty Member %q: %s", d.Id(), err) } @@ -224,7 +225,7 @@ func resourceMemberUpdate(ctx context.Context, d *schema.ResourceData, meta inte func resourceMemberDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) accountID, detectorID, err := DecodeMemberID(d.Id()) if err != nil { @@ -232,30 +233,30 @@ func resourceMemberDelete(ctx context.Context, d *schema.ResourceData, meta inte } input := guardduty.DeleteMembersInput{ - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DetectorId: aws.String(detectorID), } - log.Printf("[DEBUG] Delete GuardDuty Member: %s", input) - _, err = conn.DeleteMembersWithContext(ctx, &input) + log.Printf("[DEBUG] Delete GuardDuty Member: %+v", input) + _, err = conn.DeleteMembers(ctx, &input) if err != nil { return sdkdiag.AppendErrorf(diags, "deleting GuardDuty Member (%s): %s", d.Id(), err) } return diags } -func inviteMemberWaiter(ctx context.Context, accountID, detectorID string, timeout time.Duration, conn *guardduty.GuardDuty) error { +func inviteMemberWaiter(ctx context.Context, accountID, detectorID string, timeout time.Duration, conn *guardduty.Client) error { input := guardduty.GetMembersInput{ DetectorId: aws.String(detectorID), - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, } // wait until e-mail verification finishes var out *guardduty.GetMembersOutput err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { - log.Printf("[DEBUG] Reading GuardDuty Member: %s", input) + log.Printf("[DEBUG] Reading GuardDuty Member: %+v", input) var err error - out, err = conn.GetMembersWithContext(ctx, &input) + out, err = conn.GetMembers(ctx, &input) if err != nil { return retry.NonRetryableError(fmt.Errorf("reading GuardDuty Member %q: %s", accountID, err)) @@ -272,7 +273,7 @@ func inviteMemberWaiter(ctx context.Context, accountID, detectorID string, timeo return nil }) if tfresource.TimedOut(err) { - out, err = conn.GetMembersWithContext(ctx, &input) + out, err = conn.GetMembers(ctx, &input) if err != nil { return fmt.Errorf("reading GuardDuty member: %w", err) @@ -292,7 +293,7 @@ func memberInvited(out *guardduty.GetMembersOutput, accountID string) (bool, err } member := out.Members[0] - status := aws.StringValue(member.RelationshipStatus) + status := aws.ToString(member.RelationshipStatus) if status == "Disabled" || status == "Enabled" || status == "Invited" { return false, nil diff --git a/internal/service/guardduty/member_test.go b/internal/service/guardduty/member_test.go index c56ad90fd17..f2047a1a5eb 100644 --- a/internal/service/guardduty/member_test.go +++ b/internal/service/guardduty/member_test.go @@ -8,13 +8,14 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfguardduty "github.com/hashicorp/terraform-provider-aws/internal/service/guardduty" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -181,7 +182,7 @@ func testAccMember_invitationMessage(t *testing.T) { func testAccCheckMemberDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_member" { @@ -194,13 +195,13 @@ func testAccCheckMemberDestroy(ctx context.Context) resource.TestCheckFunc { } input := &guardduty.GetMembersInput{ - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DetectorId: aws.String(detectorID), } - gmo, err := conn.GetMembersWithContext(ctx, input) + gmo, err := conn.GetMembers(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil } return err @@ -230,12 +231,12 @@ func testAccCheckMemberExists(ctx context.Context, name string) resource.TestChe } input := &guardduty.GetMembersInput{ - AccountIds: []*string{aws.String(accountID)}, + AccountIds: []string{accountID}, DetectorId: aws.String(detectorID), } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) - gmo, err := conn.GetMembersWithContext(ctx, input) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) + gmo, err := conn.GetMembers(ctx, input) if err != nil { return err } From 5f08f827a573a392b57fe053a3b1210b52d2c8eb Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 21:58:39 +0100 Subject: [PATCH 10/22] r/guardduty_organization_admin_account: Migrate to AWS SDK v2 --- .../guardduty/organization_admin_account.go | 44 +++++++++---------- .../organization_admin_account_test.go | 10 ++--- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/internal/service/guardduty/organization_admin_account.go b/internal/service/guardduty/organization_admin_account.go index c24899ec64f..656cda7f9cb 100644 --- a/internal/service/guardduty/organization_admin_account.go +++ b/internal/service/guardduty/organization_admin_account.go @@ -7,8 +7,9 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" @@ -40,7 +41,7 @@ func ResourceOrganizationAdminAccount() *schema.Resource { func resourceOrganizationAdminAccountCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) adminAccountID := d.Get("admin_account_id").(string) @@ -48,7 +49,7 @@ func resourceOrganizationAdminAccountCreate(ctx context.Context, d *schema.Resou AdminAccountId: aws.String(adminAccountID), } - _, err := conn.EnableOrganizationAdminAccountWithContext(ctx, input) + _, err := conn.EnableOrganizationAdminAccount(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "enabling GuardDuty Organization Admin Account (%s): %s", adminAccountID, err) @@ -65,7 +66,7 @@ func resourceOrganizationAdminAccountCreate(ctx context.Context, d *schema.Resou func resourceOrganizationAdminAccountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) adminAccount, err := GetOrganizationAdminAccount(ctx, conn, d.Id()) @@ -86,13 +87,13 @@ func resourceOrganizationAdminAccountRead(ctx context.Context, d *schema.Resourc func resourceOrganizationAdminAccountDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) input := &guardduty.DisableOrganizationAdminAccountInput{ AdminAccountId: aws.String(d.Id()), } - _, err := conn.DisableOrganizationAdminAccountWithContext(ctx, input) + _, err := conn.DisableOrganizationAdminAccount(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "disabling GuardDuty Organization Admin Account (%s): %s", d.Id(), err) @@ -105,28 +106,25 @@ func resourceOrganizationAdminAccountDelete(ctx context.Context, d *schema.Resou return diags } -func GetOrganizationAdminAccount(ctx context.Context, conn *guardduty.GuardDuty, adminAccountID string) (*guardduty.AdminAccount, error) { +func GetOrganizationAdminAccount(ctx context.Context, conn *guardduty.Client, adminAccountID string) (*awstypes.AdminAccount, error) { input := &guardduty.ListOrganizationAdminAccountsInput{} - var result *guardduty.AdminAccount + result := awstypes.AdminAccount{} - err := conn.ListOrganizationAdminAccountsPagesWithContext(ctx, input, func(page *guardduty.ListOrganizationAdminAccountsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := guardduty.NewListOrganizationAdminAccountsPaginator(conn, input) - for _, adminAccount := range page.AdminAccounts { - if adminAccount == nil { - continue - } + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - if aws.StringValue(adminAccount.AdminAccountId) == adminAccountID { + if err != nil { + return &result, err + } + for _, adminAccount := range page.AdminAccounts { + if aws.ToString(adminAccount.AdminAccountId) == adminAccountID { result = adminAccount - return false + break } } + } - return !lastPage - }) - - return result, err + return &result, nil } diff --git a/internal/service/guardduty/organization_admin_account_test.go b/internal/service/guardduty/organization_admin_account_test.go index ae5f56b6ae6..71205e9f663 100644 --- a/internal/service/guardduty/organization_admin_account_test.go +++ b/internal/service/guardduty/organization_admin_account_test.go @@ -8,12 +8,12 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfguardduty "github.com/hashicorp/terraform-provider-aws/internal/service/guardduty" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -50,7 +50,7 @@ func testAccOrganizationAdminAccount_basic(t *testing.T) { func testAccCheckOrganizationAdminAccountDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_organization_admin_account" { @@ -59,7 +59,7 @@ func testAccCheckOrganizationAdminAccountDestroy(ctx context.Context) resource.T adminAccount, err := tfguardduty.GetOrganizationAdminAccount(ctx, conn, rs.Primary.ID) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "organization is not in use") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "organization is not in use") { continue } @@ -85,7 +85,7 @@ func testAccCheckOrganizationAdminAccountExists(ctx context.Context, resourceNam return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) adminAccount, err := tfguardduty.GetOrganizationAdminAccount(ctx, conn, rs.Primary.ID) From e2a1fd71d6864d0feb36ff8a53ae636766547384 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 22:08:42 +0100 Subject: [PATCH 11/22] r/guardduty_organization_configuration_feature: Migrate to AWS SDK v2 --- .../organization_configuration_feature.go | 95 ++++++++----------- ...organization_configuration_feature_test.go | 2 +- 2 files changed, 39 insertions(+), 58 deletions(-) diff --git a/internal/service/guardduty/organization_configuration_feature.go b/internal/service/guardduty/organization_configuration_feature.go index 5eb8e573885..3dc2d788255 100644 --- a/internal/service/guardduty/organization_configuration_feature.go +++ b/internal/service/guardduty/organization_configuration_feature.go @@ -9,12 +9,13 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -37,23 +38,23 @@ func ResourceOrganizationConfigurationFeature() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "auto_enable": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(guardduty.OrgFeatureStatus_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.OrgFeatureStatus](), }, names.AttrName: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(guardduty.OrgFeatureAdditionalConfiguration_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.OrgFeatureAdditionalConfiguration](), }, }, }, }, "auto_enable": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(guardduty.OrgFeatureStatus_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.OrgFeatureStatus](), }, "detector_id": { Type: schema.TypeString, @@ -61,10 +62,10 @@ func ResourceOrganizationConfigurationFeature() *schema.Resource { ForceNew: true, }, names.AttrName: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(guardduty.OrgFeature_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.OrgFeature](), }, }, } @@ -72,7 +73,7 @@ func ResourceOrganizationConfigurationFeature() *schema.Resource { func resourceOrganizationConfigurationFeaturePut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get("detector_id").(string) @@ -88,9 +89,9 @@ func resourceOrganizationConfigurationFeaturePut(ctx context.Context, d *schema. } name := d.Get(names.AttrName).(string) - feature := &guardduty.OrganizationFeatureConfiguration{ - AutoEnable: aws.String(d.Get("auto_enable").(string)), - Name: aws.String(name), + feature := awstypes.OrganizationFeatureConfiguration{ + AutoEnable: awstypes.OrgFeatureStatus(d.Get("auto_enable").(string)), + Name: awstypes.OrgFeature(name), } if v, ok := d.GetOk("additional_configuration"); ok && len(v.([]interface{})) > 0 { @@ -100,10 +101,10 @@ func resourceOrganizationConfigurationFeaturePut(ctx context.Context, d *schema. input := &guardduty.UpdateOrganizationConfigurationInput{ AutoEnableOrganizationMembers: output.AutoEnableOrganizationMembers, DetectorId: aws.String(detectorID), - Features: []*guardduty.OrganizationFeatureConfiguration{feature}, + Features: []awstypes.OrganizationFeatureConfiguration{feature}, } - _, err = conn.UpdateOrganizationConfigurationWithContext(ctx, input) + _, err = conn.UpdateOrganizationConfiguration(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Organization Configuration (%s) Feature (%s): %s", detectorID, name, err) @@ -118,7 +119,7 @@ func resourceOrganizationConfigurationFeaturePut(ctx context.Context, d *schema. func resourceOrganizationConfigurationFeatureRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID, name, err := organizationConfigurationFeatureParseResourceID(d.Id()) if err != nil { @@ -166,42 +167,38 @@ func organizationConfigurationFeatureParseResourceID(id string) (string, string, return "", "", fmt.Errorf("unexpected format for ID (%[1]s), expected DETECTORID%[2]sFEATURENAME", id, organizationConfigurationFeatureResourceIDSeparator) } -func FindOrganizationConfigurationFeatureByTwoPartKey(ctx context.Context, conn *guardduty.GuardDuty, detectorID, name string) (*guardduty.OrganizationFeatureConfigurationResult, error) { +func FindOrganizationConfigurationFeatureByTwoPartKey(ctx context.Context, conn *guardduty.Client, detectorID, name string) (*awstypes.OrganizationFeatureConfigurationResult, error) { output, err := FindOrganizationConfigurationByID(ctx, conn, detectorID) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(tfslices.Filter(output.Features, func(v *guardduty.OrganizationFeatureConfigurationResult) bool { - return aws.StringValue(v.Name) == name + return tfresource.AssertSingleValueResult(tfslices.Filter(output.Features, func(v awstypes.OrganizationFeatureConfigurationResult) bool { + return string(v.Name) == name })) } -func expandOrganizationAdditionalConfiguration(tfMap map[string]interface{}) *guardduty.OrganizationAdditionalConfiguration { - if tfMap == nil { - return nil - } - - apiObject := &guardduty.OrganizationAdditionalConfiguration{} +func expandOrganizationAdditionalConfiguration(tfMap map[string]interface{}) awstypes.OrganizationAdditionalConfiguration { + apiObject := awstypes.OrganizationAdditionalConfiguration{} if v, ok := tfMap["auto_enable"].(string); ok && v != "" { - apiObject.AutoEnable = aws.String(v) + apiObject.AutoEnable = awstypes.OrgFeatureStatus(v) } if v, ok := tfMap[names.AttrName].(string); ok && v != "" { - apiObject.Name = aws.String(v) + apiObject.Name = awstypes.OrgFeatureAdditionalConfiguration(v) } return apiObject } -func expandOrganizationAdditionalConfigurations(tfList []interface{}) []*guardduty.OrganizationAdditionalConfiguration { +func expandOrganizationAdditionalConfigurations(tfList []interface{}) []awstypes.OrganizationAdditionalConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*guardduty.OrganizationAdditionalConfiguration + var apiObjects []awstypes.OrganizationAdditionalConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -212,35 +209,23 @@ func expandOrganizationAdditionalConfigurations(tfList []interface{}) []*guarddu apiObject := expandOrganizationAdditionalConfiguration(tfMap) - if apiObject == nil { - continue - } - apiObjects = append(apiObjects, apiObject) } return apiObjects } -func flattenOrganizationAdditionalConfigurationResult(apiObject *guardduty.OrganizationAdditionalConfigurationResult) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenOrganizationAdditionalConfigurationResult(apiObject awstypes.OrganizationAdditionalConfigurationResult) map[string]interface{} { tfMap := map[string]interface{}{} - if v := apiObject.AutoEnable; v != nil { - tfMap["auto_enable"] = aws.StringValue(v) - } + tfMap["auto_enable"] = string(apiObject.AutoEnable) - if v := apiObject.Name; v != nil { - tfMap[names.AttrName] = aws.StringValue(v) - } + tfMap[names.AttrName] = string(apiObject.Name) return tfMap } -func flattenOrganizationAdditionalConfigurationResults(apiObjects []*guardduty.OrganizationAdditionalConfigurationResult) []interface{} { +func flattenOrganizationAdditionalConfigurationResults(apiObjects []awstypes.OrganizationAdditionalConfigurationResult) []interface{} { if len(apiObjects) == 0 { return nil } @@ -248,10 +233,6 @@ func flattenOrganizationAdditionalConfigurationResults(apiObjects []*guardduty.O var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenOrganizationAdditionalConfigurationResult(apiObject)) } diff --git a/internal/service/guardduty/organization_configuration_feature_test.go b/internal/service/guardduty/organization_configuration_feature_test.go index a936230d2c3..d835516fb05 100644 --- a/internal/service/guardduty/organization_configuration_feature_test.go +++ b/internal/service/guardduty/organization_configuration_feature_test.go @@ -162,7 +162,7 @@ func testAccOrganizationConfigurationFeatureExists(ctx context.Context, n string return fmt.Errorf("Not found: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) _, err := tfguardduty.FindOrganizationConfigurationFeatureByTwoPartKey(ctx, conn, rs.Primary.Attributes["detector_id"], rs.Primary.Attributes[names.AttrName]) From 9ac1da9fcfeab8bc01586e5ca0a4662b93b80e9f Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 22:14:48 +0100 Subject: [PATCH 12/22] r/guardduty_organization_configuration: Migrate to AWS SDK v2 --- .../guardduty/organization_configuration.go | 86 ++++++++++--------- .../organization_configuration_test.go | 2 +- 2 files changed, 45 insertions(+), 43 deletions(-) diff --git a/internal/service/guardduty/organization_configuration.go b/internal/service/guardduty/organization_configuration.go index 676d497b1ab..f611f188643 100644 --- a/internal/service/guardduty/organization_configuration.go +++ b/internal/service/guardduty/organization_configuration.go @@ -7,15 +7,17 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "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/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/tfresource" ) @@ -41,11 +43,11 @@ func ResourceOrganizationConfiguration() *schema.Resource { Deprecated: "Use auto_enable_organization_members instead", }, "auto_enable_organization_members": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ExactlyOneOf: []string{"auto_enable", "auto_enable_organization_members"}, - ValidateFunc: validation.StringInSlice(guardduty.AutoEnableMembers_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ExactlyOneOf: []string{"auto_enable", "auto_enable_organization_members"}, + ValidateDiagFunc: enum.Validate[awstypes.AutoEnableMembers](), }, "datasources": { Type: schema.TypeList, @@ -148,14 +150,14 @@ func ResourceOrganizationConfiguration() *schema.Resource { // AutoEnable in the resource update function. if attr := d.GetRawConfig().GetAttr("auto_enable_organization_members"); attr.IsKnown() && !attr.IsNull() { - return d.SetNew("auto_enable", attr.AsString() != guardduty.AutoEnableMembersNone) + return d.SetNew("auto_enable", attr.AsString() != string(awstypes.AutoEnableMembersNone)) } if attr := d.GetRawConfig().GetAttr("auto_enable"); attr.IsKnown() && !attr.IsNull() { if attr.True() { - return d.SetNew("auto_enable_organization_members", guardduty.AutoEnableMembersNew) + return d.SetNew("auto_enable_organization_members", string(awstypes.AutoEnableMembersNew)) } else { - return d.SetNew("auto_enable_organization_members", guardduty.AutoEnableMembersNone) + return d.SetNew("auto_enable_organization_members", string(awstypes.AutoEnableMembersNone)) } } @@ -167,11 +169,11 @@ func ResourceOrganizationConfiguration() *schema.Resource { func resourceOrganizationConfigurationPut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get("detector_id").(string) input := &guardduty.UpdateOrganizationConfigurationInput{ - AutoEnableOrganizationMembers: aws.String(d.Get("auto_enable_organization_members").(string)), + AutoEnableOrganizationMembers: awstypes.AutoEnableMembers(d.Get("auto_enable_organization_members").(string)), DetectorId: aws.String(detectorID), } @@ -184,7 +186,7 @@ func resourceOrganizationConfigurationPut(ctx context.Context, d *schema.Resourc conns.GlobalMutexKV.Lock(detectorID) defer conns.GlobalMutexKV.Unlock(detectorID) - _, err := conn.UpdateOrganizationConfigurationWithContext(ctx, input) + _, err := conn.UpdateOrganizationConfiguration(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Organization Configuration (%s): %s", detectorID, err) @@ -199,7 +201,7 @@ func resourceOrganizationConfigurationPut(ctx context.Context, d *schema.Resourc func resourceOrganizationConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) output, err := FindOrganizationConfigurationByID(ctx, conn, d.Id()) @@ -231,12 +233,12 @@ func resourceOrganizationConfigurationRead(ctx context.Context, d *schema.Resour return diags } -func expandOrganizationDataSourceConfigurations(tfMap map[string]interface{}) *guardduty.OrganizationDataSourceConfigurations { +func expandOrganizationDataSourceConfigurations(tfMap map[string]interface{}) *awstypes.OrganizationDataSourceConfigurations { if tfMap == nil { return nil } - apiObject := &guardduty.OrganizationDataSourceConfigurations{} + apiObject := &awstypes.OrganizationDataSourceConfigurations{} if v, ok := tfMap["kubernetes"].([]interface{}); ok && len(v) > 0 { apiObject.Kubernetes = expandOrganizationKubernetesConfiguration(v[0].(map[string]interface{})) @@ -253,12 +255,12 @@ func expandOrganizationDataSourceConfigurations(tfMap map[string]interface{}) *g return apiObject } -func expandOrganizationS3LogsConfiguration(tfMap map[string]interface{}) *guardduty.OrganizationS3LogsConfiguration { +func expandOrganizationS3LogsConfiguration(tfMap map[string]interface{}) *awstypes.OrganizationS3LogsConfiguration { if tfMap == nil { return nil } - apiObject := &guardduty.OrganizationS3LogsConfiguration{} + apiObject := &awstypes.OrganizationS3LogsConfiguration{} if v, ok := tfMap["auto_enable"].(bool); ok { apiObject.AutoEnable = aws.Bool(v) @@ -267,7 +269,7 @@ func expandOrganizationS3LogsConfiguration(tfMap map[string]interface{}) *guardd return apiObject } -func expandOrganizationKubernetesConfiguration(tfMap map[string]interface{}) *guardduty.OrganizationKubernetesConfiguration { +func expandOrganizationKubernetesConfiguration(tfMap map[string]interface{}) *awstypes.OrganizationKubernetesConfiguration { if tfMap == nil { return nil } @@ -282,12 +284,12 @@ func expandOrganizationKubernetesConfiguration(tfMap map[string]interface{}) *gu return nil } - return &guardduty.OrganizationKubernetesConfiguration{ + return &awstypes.OrganizationKubernetesConfiguration{ AuditLogs: expandOrganizationKubernetesAuditLogsConfiguration(m), } } -func expandOrganizationMalwareProtectionConfiguration(tfMap map[string]interface{}) *guardduty.OrganizationMalwareProtectionConfiguration { +func expandOrganizationMalwareProtectionConfiguration(tfMap map[string]interface{}) *awstypes.OrganizationMalwareProtectionConfiguration { if tfMap == nil { return nil } @@ -302,12 +304,12 @@ func expandOrganizationMalwareProtectionConfiguration(tfMap map[string]interface return nil } - return &guardduty.OrganizationMalwareProtectionConfiguration{ + return &awstypes.OrganizationMalwareProtectionConfiguration{ ScanEc2InstanceWithFindings: expandOrganizationScanEc2InstanceWithFindings(m), } } -func expandOrganizationScanEc2InstanceWithFindings(tfMap map[string]interface{}) *guardduty.OrganizationScanEc2InstanceWithFindings { // nosemgrep:ci.caps3-in-func-name +func expandOrganizationScanEc2InstanceWithFindings(tfMap map[string]interface{}) *awstypes.OrganizationScanEc2InstanceWithFindings { // nosemgrep:ci.caps3-in-func-name if tfMap == nil { return nil } @@ -322,17 +324,17 @@ func expandOrganizationScanEc2InstanceWithFindings(tfMap map[string]interface{}) return nil } - return &guardduty.OrganizationScanEc2InstanceWithFindings{ + return &awstypes.OrganizationScanEc2InstanceWithFindings{ EbsVolumes: expandOrganizationEbsVolumes(m), } } -func expandOrganizationEbsVolumes(tfMap map[string]interface{}) *guardduty.OrganizationEbsVolumes { // nosemgrep:ci.caps3-in-func-name +func expandOrganizationEbsVolumes(tfMap map[string]interface{}) *awstypes.OrganizationEbsVolumes { // nosemgrep:ci.caps3-in-func-name if tfMap == nil { return nil } - apiObject := &guardduty.OrganizationEbsVolumes{} + apiObject := &awstypes.OrganizationEbsVolumes{} if v, ok := tfMap["auto_enable"].(bool); ok { apiObject.AutoEnable = aws.Bool(v) @@ -341,12 +343,12 @@ func expandOrganizationEbsVolumes(tfMap map[string]interface{}) *guardduty.Organ return apiObject } -func expandOrganizationKubernetesAuditLogsConfiguration(tfMap map[string]interface{}) *guardduty.OrganizationKubernetesAuditLogsConfiguration { +func expandOrganizationKubernetesAuditLogsConfiguration(tfMap map[string]interface{}) *awstypes.OrganizationKubernetesAuditLogsConfiguration { if tfMap == nil { return nil } - apiObject := &guardduty.OrganizationKubernetesAuditLogsConfiguration{} + apiObject := &awstypes.OrganizationKubernetesAuditLogsConfiguration{} if v, ok := tfMap["enable"].(bool); ok { apiObject.AutoEnable = aws.Bool(v) @@ -355,7 +357,7 @@ func expandOrganizationKubernetesAuditLogsConfiguration(tfMap map[string]interfa return apiObject } -func flattenOrganizationDataSourceConfigurationsResult(apiObject *guardduty.OrganizationDataSourceConfigurationsResult) map[string]interface{} { +func flattenOrganizationDataSourceConfigurationsResult(apiObject *awstypes.OrganizationDataSourceConfigurationsResult) map[string]interface{} { if apiObject == nil { return nil } @@ -374,7 +376,7 @@ func flattenOrganizationDataSourceConfigurationsResult(apiObject *guardduty.Orga return tfMap } -func flattenOrganizationS3LogsConfigurationResult(apiObject *guardduty.OrganizationS3LogsConfigurationResult) map[string]interface{} { +func flattenOrganizationS3LogsConfigurationResult(apiObject *awstypes.OrganizationS3LogsConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } @@ -382,13 +384,13 @@ func flattenOrganizationS3LogsConfigurationResult(apiObject *guardduty.Organizat tfMap := map[string]interface{}{} if v := apiObject.AutoEnable; v != nil { - tfMap["auto_enable"] = aws.BoolValue(v) + tfMap["auto_enable"] = aws.ToBool(v) } return tfMap } -func flattenOrganizationKubernetesConfigurationResult(apiObject *guardduty.OrganizationKubernetesConfigurationResult) map[string]interface{} { +func flattenOrganizationKubernetesConfigurationResult(apiObject *awstypes.OrganizationKubernetesConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } @@ -402,7 +404,7 @@ func flattenOrganizationKubernetesConfigurationResult(apiObject *guardduty.Organ return tfMap } -func flattenOrganizationKubernetesAuditLogsConfigurationResult(apiObject *guardduty.OrganizationKubernetesAuditLogsConfigurationResult) map[string]interface{} { +func flattenOrganizationKubernetesAuditLogsConfigurationResult(apiObject *awstypes.OrganizationKubernetesAuditLogsConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } @@ -410,13 +412,13 @@ func flattenOrganizationKubernetesAuditLogsConfigurationResult(apiObject *guardd tfMap := map[string]interface{}{} if v := apiObject.AutoEnable; v != nil { - tfMap["enable"] = aws.BoolValue(v) + tfMap["enable"] = aws.ToBool(v) } return tfMap } -func flattenOrganizationMalwareProtectionConfigurationResult(apiObject *guardduty.OrganizationMalwareProtectionConfigurationResult) map[string]interface{} { +func flattenOrganizationMalwareProtectionConfigurationResult(apiObject *awstypes.OrganizationMalwareProtectionConfigurationResult) map[string]interface{} { if apiObject == nil { return nil } @@ -430,7 +432,7 @@ func flattenOrganizationMalwareProtectionConfigurationResult(apiObject *guarddut return tfMap } -func flattenOrganizationScanEc2InstanceWithFindingsResult(apiObject *guardduty.OrganizationScanEc2InstanceWithFindingsResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name +func flattenOrganizationScanEc2InstanceWithFindingsResult(apiObject *awstypes.OrganizationScanEc2InstanceWithFindingsResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name if apiObject == nil { return nil } @@ -444,7 +446,7 @@ func flattenOrganizationScanEc2InstanceWithFindingsResult(apiObject *guardduty.O return tfMap } -func flattenOrganizationEbsVolumesResult(apiObject *guardduty.OrganizationEbsVolumesResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name +func flattenOrganizationEbsVolumesResult(apiObject *awstypes.OrganizationEbsVolumesResult) map[string]interface{} { // nosemgrep:ci.caps3-in-func-name if apiObject == nil { return nil } @@ -452,20 +454,20 @@ func flattenOrganizationEbsVolumesResult(apiObject *guardduty.OrganizationEbsVol tfMap := map[string]interface{}{} if v := apiObject.AutoEnable; v != nil { - tfMap["auto_enable"] = aws.BoolValue(v) + tfMap["auto_enable"] = aws.ToBool(v) } return tfMap } -func FindOrganizationConfigurationByID(ctx context.Context, conn *guardduty.GuardDuty, id string) (*guardduty.DescribeOrganizationConfigurationOutput, error) { +func FindOrganizationConfigurationByID(ctx context.Context, conn *guardduty.Client, id string) (*guardduty.DescribeOrganizationConfigurationOutput, error) { input := &guardduty.DescribeOrganizationConfigurationInput{ DetectorId: aws.String(id), } - output, err := conn.DescribeOrganizationConfigurationWithContext(ctx, input) + output, err := conn.DescribeOrganizationConfiguration(ctx, input) - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/guardduty/organization_configuration_test.go b/internal/service/guardduty/organization_configuration_test.go index 446af1d33f2..706077bdb4d 100644 --- a/internal/service/guardduty/organization_configuration_test.go +++ b/internal/service/guardduty/organization_configuration_test.go @@ -287,7 +287,7 @@ func testAccCheckOrganizationConfigurationExists(ctx context.Context, n string) return fmt.Errorf("Not found: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) _, err := tfguardduty.FindOrganizationConfigurationByID(ctx, conn, rs.Primary.ID) From 44bb8fd456adef479e6516f9019db946ace6dcff Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 22:19:38 +0100 Subject: [PATCH 13/22] r/guardduty_publishing_destination: Migrate to AWS SDK v2 --- .../guardduty/publishing_destination.go | 51 ++++++++++--------- .../guardduty/publishing_destination_test.go | 12 ++--- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/internal/service/guardduty/publishing_destination.go b/internal/service/guardduty/publishing_destination.go index b022edf8ff6..7941e8c38cf 100644 --- a/internal/service/guardduty/publishing_destination.go +++ b/internal/service/guardduty/publishing_destination.go @@ -9,13 +9,14 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" @@ -40,10 +41,10 @@ func ResourcePublishingDestination() *schema.Resource { ForceNew: true, }, "destination_type": { - Type: schema.TypeString, - Optional: true, - Default: guardduty.DestinationTypeS3, - ValidateFunc: validation.StringInSlice(guardduty.DestinationType_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.DestinationTypeS3, + ValidateDiagFunc: enum.Validate[awstypes.DestinationType](), }, names.AttrDestinationARN: { Type: schema.TypeString, @@ -61,30 +62,30 @@ func ResourcePublishingDestination() *schema.Resource { func resourcePublishingDestinationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get("detector_id").(string) input := guardduty.CreatePublishingDestinationInput{ DetectorId: aws.String(detectorID), - DestinationProperties: &guardduty.DestinationProperties{ + DestinationProperties: &awstypes.DestinationProperties{ DestinationArn: aws.String(d.Get(names.AttrDestinationARN).(string)), KmsKeyArn: aws.String(d.Get(names.AttrKMSKeyARN).(string)), }, - DestinationType: aws.String(d.Get("destination_type").(string)), + DestinationType: awstypes.DestinationType(d.Get("destination_type").(string)), } - output, err := conn.CreatePublishingDestinationWithContext(ctx, &input) + output, err := conn.CreatePublishingDestination(ctx, &input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating GuardDuty Publishing Destination: %s", err) } - d.SetId(fmt.Sprintf("%s:%s", d.Get("detector_id"), aws.StringValue(output.DestinationId))) + d.SetId(fmt.Sprintf("%s:%s", d.Get("detector_id"), aws.ToString(output.DestinationId))) - _, err = waitPublishingDestinationCreated(ctx, conn, aws.StringValue(output.DestinationId), detectorID) + _, err = waitPublishingDestinationCreated(ctx, conn, aws.ToString(output.DestinationId), detectorID) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for GuardDuty PublishingDestination status to be \"%s\": %s", - guardduty.PublishingStatusPublishing, err) + string(awstypes.PublishingStatusPublishing), err) } return append(diags, resourcePublishingDestinationRead(ctx, d, meta)...) @@ -92,7 +93,7 @@ func resourcePublishingDestinationCreate(ctx context.Context, d *schema.Resource func resourcePublishingDestinationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) destinationId, detectorId, err := DecodePublishDestinationID(d.Id()) @@ -105,9 +106,9 @@ func resourcePublishingDestinationRead(ctx context.Context, d *schema.ResourceDa DestinationId: aws.String(destinationId), } - gdo, err := conn.DescribePublishingDestinationWithContext(ctx, input) + gdo, err := conn.DescribePublishingDestination(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the one or more input parameters have invalid values.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the one or more input parameters have invalid values.") { log.Printf("[WARN] GuardDuty Publishing Destination: %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -124,7 +125,7 @@ func resourcePublishingDestinationRead(ctx context.Context, d *schema.ResourceDa func resourcePublishingDestinationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) destinationId, detectorId, err := DecodePublishDestinationID(d.Id()) @@ -135,13 +136,13 @@ func resourcePublishingDestinationUpdate(ctx context.Context, d *schema.Resource input := guardduty.UpdatePublishingDestinationInput{ DestinationId: aws.String(destinationId), DetectorId: aws.String(detectorId), - DestinationProperties: &guardduty.DestinationProperties{ + DestinationProperties: &awstypes.DestinationProperties{ DestinationArn: aws.String(d.Get(names.AttrDestinationARN).(string)), KmsKeyArn: aws.String(d.Get(names.AttrKMSKeyARN).(string)), }, } - if _, err = conn.UpdatePublishingDestinationWithContext(ctx, &input); err != nil { + if _, err = conn.UpdatePublishingDestination(ctx, &input); err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Publishing Destination (%s): %s", d.Id(), err) } @@ -150,7 +151,7 @@ func resourcePublishingDestinationUpdate(ctx context.Context, d *schema.Resource func resourcePublishingDestinationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) destinationId, detectorId, err := DecodePublishDestinationID(d.Id()) @@ -163,10 +164,10 @@ func resourcePublishingDestinationDelete(ctx context.Context, d *schema.Resource DetectorId: aws.String(detectorId), } - log.Printf("[DEBUG] Delete GuardDuty Publishing Destination: %s", input) - _, err = conn.DeletePublishingDestinationWithContext(ctx, &input) + log.Printf("[DEBUG] Delete GuardDuty Publishing Destination: %+v", input) + _, err = conn.DeletePublishingDestination(ctx, &input) - if tfawserr.ErrCodeEquals(err, guardduty.ErrCodeBadRequestException) { + if errs.IsA[*awstypes.BadRequestException](err) { return diags } diff --git a/internal/service/guardduty/publishing_destination_test.go b/internal/service/guardduty/publishing_destination_test.go index cacc26fb8aa..80885bcf61f 100644 --- a/internal/service/guardduty/publishing_destination_test.go +++ b/internal/service/guardduty/publishing_destination_test.go @@ -8,8 +8,8 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -208,15 +208,15 @@ func testAccCheckPublishingDestinationExists(ctx context.Context, name string) r DestinationId: aws.String(destination_id), } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) - _, err := conn.DescribePublishingDestinationWithContext(ctx, input) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) + _, err := conn.DescribePublishingDestination(ctx, input) return err } } func testAccCheckPublishingDestinationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_publishing_destination" { @@ -234,7 +234,7 @@ func testAccCheckPublishingDestinationDestroy(ctx context.Context) resource.Test DestinationId: aws.String(destination_id), } - _, err := conn.DescribePublishingDestinationWithContext(ctx, input) + _, err := conn.DescribePublishingDestination(ctx, input) // Catch expected error. if err == nil { return fmt.Errorf("Resource still exists.") From cdf818c94894f527e4193040a2edc95e67c8fa09 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 22:29:07 +0100 Subject: [PATCH 14/22] r/guardduty_threatintelset: Migrate to AWS SDK v2 --- internal/service/guardduty/threatintelset.go | 71 ++++++++++--------- .../service/guardduty/threatintelset_test.go | 19 ++--- 2 files changed, 46 insertions(+), 44 deletions(-) diff --git a/internal/service/guardduty/threatintelset.go b/internal/service/guardduty/threatintelset.go index 44d98027a45..3231f3db854 100644 --- a/internal/service/guardduty/threatintelset.go +++ b/internal/service/guardduty/threatintelset.go @@ -10,15 +10,16 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "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/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -53,10 +54,10 @@ func ResourceThreatIntelSet() *schema.Resource { Required: true, }, names.AttrFormat: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(guardduty.ThreatIntelSetFormat_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.ThreatIntelSetFormat](), }, names.AttrLocation: { Type: schema.TypeString, @@ -76,27 +77,27 @@ func ResourceThreatIntelSet() *schema.Resource { func resourceThreatIntelSetCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) detectorID := d.Get("detector_id").(string) name := d.Get(names.AttrName).(string) input := &guardduty.CreateThreatIntelSetInput{ DetectorId: aws.String(detectorID), Name: aws.String(name), - Format: aws.String(d.Get(names.AttrFormat).(string)), + Format: awstypes.ThreatIntelSetFormat(d.Get(names.AttrFormat).(string)), Location: aws.String(d.Get(names.AttrLocation).(string)), Activate: aws.Bool(d.Get("activate").(bool)), Tags: getTagsIn(ctx), } - resp, err := conn.CreateThreatIntelSetWithContext(ctx, input) + resp, err := conn.CreateThreatIntelSet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating GuardDuty Threat Intel Set (%s): %s", name, err) } stateConf := &retry.StateChangeConf{ - Pending: []string{guardduty.ThreatIntelSetStatusActivating, guardduty.ThreatIntelSetStatusDeactivating}, - Target: []string{guardduty.ThreatIntelSetStatusActive, guardduty.ThreatIntelSetStatusInactive}, + Pending: enum.Slice(awstypes.ThreatIntelSetStatusActivating, awstypes.ThreatIntelSetStatusDeactivating), + Target: enum.Slice(awstypes.ThreatIntelSetStatusActive, awstypes.ThreatIntelSetStatusInactive), Refresh: threatintelsetRefreshStatusFunc(ctx, conn, *resp.ThreatIntelSetId, detectorID), Timeout: 5 * time.Minute, MinTimeout: 3 * time.Second, @@ -106,14 +107,14 @@ func resourceThreatIntelSetCreate(ctx context.Context, d *schema.ResourceData, m return sdkdiag.AppendErrorf(diags, "creating GuardDuty Threat Intel Set (%s): waiting for completion: %s", name, err) } - d.SetId(fmt.Sprintf("%s:%s", detectorID, aws.StringValue(resp.ThreatIntelSetId))) + d.SetId(fmt.Sprintf("%s:%s", detectorID, aws.ToString(resp.ThreatIntelSetId))) return append(diags, resourceThreatIntelSetRead(ctx, d, meta)...) } func resourceThreatIntelSetRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) threatIntelSetId, detectorId, err := DecodeThreatIntelSetID(d.Id()) if err != nil { @@ -124,9 +125,9 @@ func resourceThreatIntelSetRead(ctx context.Context, d *schema.ResourceData, met ThreatIntelSetId: aws.String(threatIntelSetId), } - resp, err := conn.GetThreatIntelSetWithContext(ctx, input) + resp, err := conn.GetThreatIntelSet(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { log.Printf("[WARN] GuardDuty ThreatIntelSet %q not found, removing from state", threatIntelSetId) d.SetId("") return diags @@ -147,7 +148,7 @@ func resourceThreatIntelSetRead(ctx context.Context, d *schema.ResourceData, met d.Set(names.AttrFormat, resp.Format) d.Set(names.AttrLocation, resp.Location) d.Set(names.AttrName, resp.Name) - d.Set("activate", aws.StringValue(resp.Status) == guardduty.ThreatIntelSetStatusActive) + d.Set("activate", resp.Status == awstypes.ThreatIntelSetStatusActive) setTagsOut(ctx, resp.Tags) @@ -156,7 +157,7 @@ func resourceThreatIntelSetRead(ctx context.Context, d *schema.ResourceData, met func resourceThreatIntelSetUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) threatIntelSetID, detectorId, err := DecodeThreatIntelSetID(d.Id()) if err != nil { @@ -179,7 +180,7 @@ func resourceThreatIntelSetUpdate(ctx context.Context, d *schema.ResourceData, m input.Activate = aws.Bool(d.Get("activate").(bool)) } - if _, err = conn.UpdateThreatIntelSetWithContext(ctx, input); err != nil { + if _, err = conn.UpdateThreatIntelSet(ctx, input); err != nil { return sdkdiag.AppendErrorf(diags, "updating GuardDuty Threat Intel Set (%s): %s", d.Id(), err) } } @@ -189,7 +190,7 @@ func resourceThreatIntelSetUpdate(ctx context.Context, d *schema.ResourceData, m func resourceThreatIntelSetDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).GuardDutyConn(ctx) + conn := meta.(*conns.AWSClient).GuardDutyClient(ctx) threatIntelSetID, detectorId, err := DecodeThreatIntelSetID(d.Id()) if err != nil { @@ -200,20 +201,20 @@ func resourceThreatIntelSetDelete(ctx context.Context, d *schema.ResourceData, m ThreatIntelSetId: aws.String(threatIntelSetID), } - _, err = conn.DeleteThreatIntelSetWithContext(ctx, input) + _, err = conn.DeleteThreatIntelSet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "deleting GuardDuty Threat Intel Set (%s): %s", d.Id(), err) } stateConf := &retry.StateChangeConf{ - Pending: []string{ - guardduty.ThreatIntelSetStatusActive, - guardduty.ThreatIntelSetStatusActivating, - guardduty.ThreatIntelSetStatusInactive, - guardduty.ThreatIntelSetStatusDeactivating, - guardduty.ThreatIntelSetStatusDeletePending, - }, - Target: []string{guardduty.ThreatIntelSetStatusDeleted}, + Pending: enum.Slice( + awstypes.ThreatIntelSetStatusActive, + awstypes.ThreatIntelSetStatusActivating, + awstypes.ThreatIntelSetStatusInactive, + awstypes.ThreatIntelSetStatusDeactivating, + awstypes.ThreatIntelSetStatusDeletePending, + ), + Target: enum.Slice(awstypes.ThreatIntelSetStatusDeleted), Refresh: threatintelsetRefreshStatusFunc(ctx, conn, threatIntelSetID, detectorId), Timeout: 5 * time.Minute, MinTimeout: 3 * time.Second, @@ -221,23 +222,23 @@ func resourceThreatIntelSetDelete(ctx context.Context, d *schema.ResourceData, m _, err = stateConf.WaitForStateContext(ctx) if err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for GuardDuty ThreatIntelSet status to be \"%s\": %s", guardduty.ThreatIntelSetStatusDeleted, err) + return sdkdiag.AppendErrorf(diags, "waiting for GuardDuty ThreatIntelSet status to be \"%s\": %s", string(awstypes.ThreatIntelSetStatusDeleted), err) } return diags } -func threatintelsetRefreshStatusFunc(ctx context.Context, conn *guardduty.GuardDuty, threatIntelSetID, detectorID string) retry.StateRefreshFunc { +func threatintelsetRefreshStatusFunc(ctx context.Context, conn *guardduty.Client, threatIntelSetID, detectorID string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &guardduty.GetThreatIntelSetInput{ DetectorId: aws.String(detectorID), ThreatIntelSetId: aws.String(threatIntelSetID), } - resp, err := conn.GetThreatIntelSetWithContext(ctx, input) + resp, err := conn.GetThreatIntelSet(ctx, input) if err != nil { return nil, "failed", err } - return resp, *resp.Status, nil + return resp, string(resp.Status), nil } } diff --git a/internal/service/guardduty/threatintelset_test.go b/internal/service/guardduty/threatintelset_test.go index 384f592a63b..7b778f4271b 100644 --- a/internal/service/guardduty/threatintelset_test.go +++ b/internal/service/guardduty/threatintelset_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "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/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/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" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfguardduty "github.com/hashicorp/terraform-provider-aws/internal/service/guardduty" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -118,7 +119,7 @@ func testAccThreatIntelSet_tags(t *testing.T) { func testAccCheckThreatIntelSetDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_guardduty_threatintelset" { @@ -134,15 +135,15 @@ func testAccCheckThreatIntelSetDestroy(ctx context.Context) resource.TestCheckFu DetectorId: aws.String(detectorId), } - resp, err := conn.GetThreatIntelSetWithContext(ctx, input) + resp, err := conn.GetThreatIntelSet(ctx, input) if err != nil { - if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { + if errs.IsAErrorMessageContains[*awstypes.BadRequestException](err, "The request is rejected because the input detectorId is not owned by the current account.") { return nil } return err } - if *resp.Status == guardduty.ThreatIntelSetStatusDeletePending || *resp.Status == guardduty.ThreatIntelSetStatusDeleted { + if resp.Status == awstypes.ThreatIntelSetStatusDeletePending || resp.Status == awstypes.ThreatIntelSetStatusDeleted { return nil } @@ -170,8 +171,8 @@ func testAccCheckThreatIntelSetExists(ctx context.Context, name string) resource ThreatIntelSetId: aws.String(threatIntelSetId), } - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) - _, err = conn.GetThreatIntelSetWithContext(ctx, input) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) + _, err = conn.GetThreatIntelSet(ctx, input) return err } } From 440932ec331e35bcf94823208033c460207054ef Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 22:56:05 +0100 Subject: [PATCH 15/22] guardduty: misc: Migrate to AWS SDK v2 --- internal/service/guardduty/guardduty_test.go | 4 +- internal/service/guardduty/status.go | 43 +++++---- internal/service/guardduty/sweep.go | 96 +++++++++++--------- internal/service/guardduty/wait.go | 22 +++-- 4 files changed, 87 insertions(+), 78 deletions(-) diff --git a/internal/service/guardduty/guardduty_test.go b/internal/service/guardduty/guardduty_test.go index 1bbf0bef073..06eca3fb85e 100644 --- a/internal/service/guardduty/guardduty_test.go +++ b/internal/service/guardduty/guardduty_test.go @@ -103,7 +103,7 @@ func testAccMemberFromEnv(t *testing.T) (string, string) { // testAccPreCheckDetectorExists verifies the current account has a single active GuardDuty detector configured. func testAccPreCheckDetectorExists(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) _, err := tfguardduty.FindDetector(ctx, conn) @@ -118,7 +118,7 @@ func testAccPreCheckDetectorExists(ctx context.Context, t *testing.T) { // testAccPreCheckDetectorNotExists verifies the current account has no active GuardDuty detector configured. func testAccPreCheckDetectorNotExists(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyClient(ctx) _, err := tfguardduty.FindDetector(ctx, conn) diff --git a/internal/service/guardduty/status.go b/internal/service/guardduty/status.go index 8f2954d23db..5d5ccadea08 100644 --- a/internal/service/guardduty/status.go +++ b/internal/service/guardduty/status.go @@ -6,8 +6,9 @@ package guardduty import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" ) @@ -24,7 +25,7 @@ const ( ) // statusAdminAccountAdmin fetches the AdminAccount and its AdminStatus -func statusAdminAccountAdmin(ctx context.Context, conn *guardduty.GuardDuty, adminAccountID string) retry.StateRefreshFunc { +func statusAdminAccountAdmin(ctx context.Context, conn *guardduty.Client, adminAccountID string) retry.StateRefreshFunc { return func() (interface{}, string, error) { adminAccount, err := getOrganizationAdminAccount(ctx, conn, adminAccountID) @@ -36,19 +37,19 @@ func statusAdminAccountAdmin(ctx context.Context, conn *guardduty.GuardDuty, adm return adminAccount, adminStatusNotFound, nil } - return adminAccount, aws.StringValue(adminAccount.AdminStatus), nil + return adminAccount, string(adminAccount.AdminStatus), nil } } // statusPublishingDestination fetches the PublishingDestination and its Status -func statusPublishingDestination(ctx context.Context, conn *guardduty.GuardDuty, destinationID, detectorID string) retry.StateRefreshFunc { +func statusPublishingDestination(ctx context.Context, conn *guardduty.Client, destinationID, detectorID string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &guardduty.DescribePublishingDestinationInput{ DetectorId: aws.String(detectorID), DestinationId: aws.String(destinationID), } - output, err := conn.DescribePublishingDestinationWithContext(ctx, input) + output, err := conn.DescribePublishingDestination(ctx, input) if err != nil { return output, publishingStatusFailed, err @@ -58,33 +59,31 @@ func statusPublishingDestination(ctx context.Context, conn *guardduty.GuardDuty, return output, publishingStatusUnknown, nil } - return output, aws.StringValue(output.Status), nil + return output, string(output.Status), nil } } // TODO: Migrate to shared internal package guardduty -func getOrganizationAdminAccount(ctx context.Context, conn *guardduty.GuardDuty, adminAccountID string) (*guardduty.AdminAccount, error) { +func getOrganizationAdminAccount(ctx context.Context, conn *guardduty.Client, adminAccountID string) (*awstypes.AdminAccount, error) { input := &guardduty.ListOrganizationAdminAccountsInput{} - var result *guardduty.AdminAccount + var result *awstypes.AdminAccount - err := conn.ListOrganizationAdminAccountsPagesWithContext(ctx, input, func(page *guardduty.ListOrganizationAdminAccountsOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := guardduty.NewListOrganizationAdminAccountsPaginator(conn, input) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return result, err } for _, adminAccount := range page.AdminAccounts { - if adminAccount == nil { - continue - } - - if aws.StringValue(adminAccount.AdminAccountId) == adminAccountID { - result = adminAccount - return false + if aws.ToString(adminAccount.AdminAccountId) == adminAccountID { + result = &adminAccount } } - return !lastPage - }) + } - return result, err + return result, nil } diff --git a/internal/service/guardduty/sweep.go b/internal/service/guardduty/sweep.go index e0f7190271b..a67a8e9ec9c 100644 --- a/internal/service/guardduty/sweep.go +++ b/internal/service/guardduty/sweep.go @@ -7,13 +7,12 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/sweep" - "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv1" + "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv2" ) func RegisterSweepers() { @@ -37,19 +36,32 @@ func sweepDetectors(region string) error { return fmt.Errorf("error getting client: %w", err) } - conn := client.GuardDutyConn(ctx) + conn := client.GuardDutyClient(ctx) input := &guardduty.ListDetectorsInput{} var sweeperErrs *multierror.Error - err = conn.ListDetectorsPagesWithContext(ctx, input, func(page *guardduty.ListDetectorsOutput, lastPage bool) bool { + pages := guardduty.NewListDetectorsPaginator(conn, input) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping GuardDuty Detector sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error retrieving GuardDuty Detectors: %w", err) + } + for _, detectorID := range page.DetectorIds { - id := aws.StringValue(detectorID) + id := detectorID input := &guardduty.DeleteDetectorInput{ - DetectorId: detectorID, + DetectorId: &id, } log.Printf("[INFO] Deleting GuardDuty Detector: %s", id) - _, err := conn.DeleteDetectorWithContext(ctx, input) + _, err := conn.DeleteDetector(ctx, input) if tfawserr.ErrCodeContains(err, "AccessDenied") { log.Printf("[WARN] Skipping GuardDuty Detector (%s): %s", id, err) continue @@ -60,17 +72,6 @@ func sweepDetectors(region string) error { sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) } } - - return !lastPage - }) - - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping GuardDuty Detector sweep for %s: %s", region, err) - return nil - } - - if err != nil { - return fmt.Errorf("error retrieving GuardDuty Detectors: %w", err) } return sweeperErrs.ErrorOrNil() @@ -84,26 +85,50 @@ func sweepPublishingDestinations(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.GuardDutyConn(ctx) + conn := client.GuardDutyClient(ctx) var sweeperErrs *multierror.Error detect_input := &guardduty.ListDetectorsInput{} - err = conn.ListDetectorsPagesWithContext(ctx, detect_input, func(page *guardduty.ListDetectorsOutput, lastPage bool) bool { + pages := guardduty.NewListDetectorsPaginator(conn, detect_input) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + sweeperErr := fmt.Errorf("Error receiving Guardduty detectors for publishing sweep : %w", err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + } + for _, detectorID := range page.DetectorIds { + id := detectorID list_input := &guardduty.ListPublishingDestinationsInput{ - DetectorId: detectorID, + DetectorId: &id, } - err = conn.ListPublishingDestinationsPagesWithContext(ctx, list_input, func(page *guardduty.ListPublishingDestinationsOutput, lastPage bool) bool { + pages := guardduty.NewListPublishingDestinationsPaginator(conn, list_input) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping GuardDuty Publishing Destination sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error retrieving GuardDuty Publishing Destinations: %s", err) + } + for _, destination_element := range page.Destinations { input := &guardduty.DeletePublishingDestinationInput{ DestinationId: destination_element.DestinationId, - DetectorId: detectorID, + DetectorId: &id, } log.Printf("[INFO] Deleting GuardDuty Publishing Destination: %s", *destination_element.DestinationId) - _, err := conn.DeletePublishingDestinationWithContext(ctx, input) + _, err := conn.DeletePublishingDestination(ctx, input) if err != nil { sweeperErr := fmt.Errorf("error deleting GuardDuty Publishing Destination (%s): %w", *destination_element.DestinationId, err) @@ -111,25 +136,8 @@ func sweepPublishingDestinations(region string) error { sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) } } - return !lastPage - }) + } } - return !lastPage - }) - - if err != nil { - sweeperErr := fmt.Errorf("Error receiving Guardduty detectors for publishing sweep : %w", err) - log.Printf("[ERROR] %s", sweeperErr) - sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) - } - - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping GuardDuty Publishing Destination sweep for %s: %s", region, err) - return nil - } - - if err != nil { - return fmt.Errorf("error retrieving GuardDuty Publishing Destinations: %s", err) } return sweeperErrs.ErrorOrNil() diff --git a/internal/service/guardduty/wait.go b/internal/service/guardduty/wait.go index 03d546e35d8..76a393a7729 100644 --- a/internal/service/guardduty/wait.go +++ b/internal/service/guardduty/wait.go @@ -7,8 +7,10 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/service/guardduty" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + awstypes "github.com/aws/aws-sdk-go-v2/service/guardduty/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" ) const ( @@ -30,17 +32,17 @@ const ( ) // waitAdminAccountEnabled waits for an AdminAccount to return Enabled -func waitAdminAccountEnabled(ctx context.Context, conn *guardduty.GuardDuty, adminAccountID string) (*guardduty.AdminAccount, error) { +func waitAdminAccountEnabled(ctx context.Context, conn *guardduty.Client, adminAccountID string) (*awstypes.AdminAccount, error) { stateConf := &retry.StateChangeConf{ Pending: []string{adminStatusNotFound}, - Target: []string{guardduty.AdminStatusEnabled}, + Target: enum.Slice(awstypes.AdminStatusEnabled), Refresh: statusAdminAccountAdmin(ctx, conn, adminAccountID), Timeout: adminAccountEnabledTimeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*guardduty.AdminAccount); ok { + if output, ok := outputRaw.(*awstypes.AdminAccount); ok { return output, err } @@ -48,9 +50,9 @@ func waitAdminAccountEnabled(ctx context.Context, conn *guardduty.GuardDuty, adm } // waitAdminAccountNotFound waits for an AdminAccount to return NotFound -func waitAdminAccountNotFound(ctx context.Context, conn *guardduty.GuardDuty, adminAccountID string) (*guardduty.AdminAccount, error) { +func waitAdminAccountNotFound(ctx context.Context, conn *guardduty.Client, adminAccountID string) (*awstypes.AdminAccount, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{guardduty.AdminStatusDisableInProgress}, + Pending: enum.Slice(awstypes.AdminStatusDisableInProgress), Target: []string{adminStatusNotFound}, Refresh: statusAdminAccountAdmin(ctx, conn, adminAccountID), Timeout: adminAccountNotFoundTimeout, @@ -58,7 +60,7 @@ func waitAdminAccountNotFound(ctx context.Context, conn *guardduty.GuardDuty, ad outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*guardduty.AdminAccount); ok { + if output, ok := outputRaw.(*awstypes.AdminAccount); ok { return output, err } @@ -66,10 +68,10 @@ func waitAdminAccountNotFound(ctx context.Context, conn *guardduty.GuardDuty, ad } // waitPublishingDestinationCreated waits for GuardDuty to return Publishing -func waitPublishingDestinationCreated(ctx context.Context, conn *guardduty.GuardDuty, destinationID, detectorID string) (*guardduty.CreatePublishingDestinationOutput, error) { +func waitPublishingDestinationCreated(ctx context.Context, conn *guardduty.Client, destinationID, detectorID string) (*guardduty.CreatePublishingDestinationOutput, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{guardduty.PublishingStatusPendingVerification}, - Target: []string{guardduty.PublishingStatusPublishing}, + Pending: enum.Slice(awstypes.PublishingStatusPendingVerification), + Target: enum.Slice(awstypes.PublishingStatusPublishing), Refresh: statusPublishingDestination(ctx, conn, destinationID, detectorID), Timeout: publishingDestinationCreatedTimeout, } From 5498d7a75da0dfc83ea5fdd7692f01195ff0d1e7 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 17 Jul 2024 23:23:11 +0100 Subject: [PATCH 16/22] Fix lints --- internal/service/guardduty/finding_ids_data_source.go | 1 - internal/service/guardduty/status.go | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/internal/service/guardduty/finding_ids_data_source.go b/internal/service/guardduty/finding_ids_data_source.go index 1739b2139b4..fbf51e2e7c6 100644 --- a/internal/service/guardduty/finding_ids_data_source.go +++ b/internal/service/guardduty/finding_ids_data_source.go @@ -104,7 +104,6 @@ func findFindingIds(ctx context.Context, conn *guardduty.Client, id string) ([]s } findingIds = append(findingIds, page.FindingIds...) - } return findingIds, nil diff --git a/internal/service/guardduty/status.go b/internal/service/guardduty/status.go index 5d5ccadea08..a9f919cbcdd 100644 --- a/internal/service/guardduty/status.go +++ b/internal/service/guardduty/status.go @@ -78,11 +78,11 @@ func getOrganizationAdminAccount(ctx context.Context, conn *guardduty.Client, ad } for _, adminAccount := range page.AdminAccounts { + account := adminAccount if aws.ToString(adminAccount.AdminAccountId) == adminAccountID { - result = &adminAccount + result = &account } } - } return result, nil From d0ec4755d98a240d149784ad0bd0352249e4c0e8 Mon Sep 17 00:00:00 2001 From: Adrian Johnson Date: Fri, 2 Aug 2024 11:52:55 -0500 Subject: [PATCH 17/22] aws_guardduty_ipsec: fix tests --- internal/service/guardduty/generate.go | 2 +- internal/service/guardduty/ipset_test.go | 76 ++++++++++++++------ internal/service/guardduty/tags_gen.go | 88 ++++++++++++++++++++++++ 3 files changed, 143 insertions(+), 23 deletions(-) diff --git a/internal/service/guardduty/generate.go b/internal/service/guardduty/generate.go index fe4dadcf8f4..bfc0372ffaa 100644 --- a/internal/service/guardduty/generate.go +++ b/internal/service/guardduty/generate.go @@ -1,7 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ServiceTagsMap -KVTValues -SkipTypesImp -SkipAWSServiceImp -SkipAWSImp +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ServiceTagsMap -KVTValues -SkipTypesImp -SkipAWSServiceImp -ListTags -UpdateTags //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/guardduty/ipset_test.go b/internal/service/guardduty/ipset_test.go index 02a1db189a8..32da7a5596a 100644 --- a/internal/service/guardduty/ipset_test.go +++ b/internal/service/guardduty/ipset_test.go @@ -177,46 +177,79 @@ func testAccCheckIPSetExists(ctx context.Context, name string) resource.TestChec } } -func testAccIPSetConfig_basic(bucketName, keyName, ipsetName string, activate bool) string { +func testAccIPSetConfig_base(rName string) string { return fmt.Sprintf(` -resource "aws_guardduty_detector" "test" {} - resource "aws_s3_bucket" "test" { - bucket = "%s" + bucket = %[1]q force_destroy = true } +resource "aws_s3_bucket_ownership_controls" "test" { + bucket = aws_s3_bucket.test.id + rule { + object_ownership = "BucketOwnerPreferred" + } +} + +resource "aws_s3_bucket_public_access_block" "test" { + bucket = aws_s3_bucket.test.id + + block_public_acls = false + block_public_policy = false + ignore_public_acls = false + restrict_public_buckets = false +} + +resource "aws_s3_bucket_acl" "test" { + depends_on = [ + aws_s3_bucket_ownership_controls.test, + aws_s3_bucket_public_access_block.test, + ] + + bucket = aws_s3_bucket.test.id + acl = "public-read" +} +`, rName) +} + +func testAccIPSetConfig_basic(bucketName, keyName, ipsetName string, activate bool) string { + return acctest.ConfigCompose(testAccIPSetConfig_base(bucketName), fmt.Sprintf(` +resource "aws_guardduty_detector" "test" {} + resource "aws_s3_object" "test" { acl = "public-read" content = "10.0.0.0/8\n" bucket = aws_s3_bucket.test.id - key = "%s" + key = %[1]q + + depends_on = [ + aws_s3_bucket_acl.test, + ] } resource "aws_guardduty_ipset" "test" { - name = "%s" + name = %[2]q detector_id = aws_guardduty_detector.test.id format = "TXT" location = "https://s3.amazonaws.com/${aws_s3_object.test.bucket}/${aws_s3_object.test.key}" - activate = %t + activate = %[3]t } -`, bucketName, keyName, ipsetName, activate) +`, keyName, ipsetName, activate)) } func testAccIPSetConfig_tags1(rName, tagKey1, tagValue1 string) string { - return fmt.Sprintf(` + return acctest.ConfigCompose(testAccIPSetConfig_base(rName), fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} -resource "aws_s3_bucket" "test" { - bucket = %[1]q - force_destroy = true -} - resource "aws_s3_object" "test" { acl = "public-read" content = "10.0.0.0/8\n" bucket = aws_s3_bucket.test.id key = %[1]q + + depends_on = [ + aws_s3_bucket_acl.test, + ] } resource "aws_guardduty_ipset" "test" { @@ -230,23 +263,22 @@ resource "aws_guardduty_ipset" "test" { %[2]q = %[3]q } } -`, rName, tagKey1, tagValue1) +`, rName, tagKey1, tagValue1)) } func testAccIPSetConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return fmt.Sprintf(` + return acctest.ConfigCompose(testAccIPSetConfig_base(rName), fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} -resource "aws_s3_bucket" "test" { - bucket = %[1]q - force_destroy = true -} - resource "aws_s3_object" "test" { acl = "public-read" content = "10.0.0.0/8\n" bucket = aws_s3_bucket.test.id key = %[1]q + + depends_on = [ + aws_s3_bucket_acl.test, + ] } resource "aws_guardduty_ipset" "test" { @@ -261,5 +293,5 @@ resource "aws_guardduty_ipset" "test" { %[4]q = %[5]q } } -`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } diff --git a/internal/service/guardduty/tags_gen.go b/internal/service/guardduty/tags_gen.go index e112e228925..63e0fd57d77 100644 --- a/internal/service/guardduty/tags_gen.go +++ b/internal/service/guardduty/tags_gen.go @@ -3,11 +3,51 @@ package guardduty import ( "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" + "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/logging" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/types/option" + "github.com/hashicorp/terraform-provider-aws/names" ) +// listTags lists guardduty 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 *guardduty.Client, identifier string, optFns ...func(*guardduty.Options)) (tftags.KeyValueTags, error) { + input := &guardduty.ListTagsForResourceInput{ + ResourceArn: aws.String(identifier), + } + + output, err := conn.ListTagsForResource(ctx, input, optFns...) + + if err != nil { + return tftags.New(ctx, nil), err + } + + return KeyValueTags(ctx, output.Tags), nil +} + +// ListTags lists guardduty 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).GuardDutyClient(ctx), identifier) + + if err != nil { + return err + } + + if inContext, ok := tftags.FromContext(ctx); ok { + inContext.TagsOut = option.Some(tags) + } + + return nil +} + // map[string]string handling // Tags returns guardduty service tags. @@ -38,3 +78,51 @@ func setTagsOut(ctx context.Context, tags map[string]string) { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } } + +// updateTags updates guardduty 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 *guardduty.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*guardduty.Options)) error { + oldTags := tftags.New(ctx, oldTagsMap) + newTags := tftags.New(ctx, newTagsMap) + + ctx = tflog.SetField(ctx, logging.KeyResourceId, identifier) + + removedTags := oldTags.Removed(newTags) + removedTags = removedTags.IgnoreSystem(names.GuardDuty) + if len(removedTags) > 0 { + input := &guardduty.UntagResourceInput{ + ResourceArn: aws.String(identifier), + TagKeys: removedTags.Keys(), + } + + _, err := conn.UntagResource(ctx, input, optFns...) + + if err != nil { + return fmt.Errorf("untagging resource (%s): %w", identifier, err) + } + } + + updatedTags := oldTags.Updated(newTags) + updatedTags = updatedTags.IgnoreSystem(names.GuardDuty) + if len(updatedTags) > 0 { + input := &guardduty.TagResourceInput{ + ResourceArn: aws.String(identifier), + Tags: Tags(updatedTags), + } + + _, err := conn.TagResource(ctx, input, optFns...) + + if err != nil { + return fmt.Errorf("tagging resource (%s): %w", identifier, err) + } + } + + return nil +} + +// UpdateTags updates guardduty 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).GuardDutyClient(ctx), identifier, oldTags, newTags) +} From ef237ff1ab0d3076eb9123ff82a15b4b72be61af Mon Sep 17 00:00:00 2001 From: Adrian Johnson Date: Fri, 2 Aug 2024 14:00:50 -0500 Subject: [PATCH 18/22] aws_guardduty_threatintelset: fix tests --- .../guardduty/finding_ids_data_source_test.go | 1 - .../service/guardduty/threatintelset_test.go | 79 +++++++++++++------ 2 files changed, 57 insertions(+), 23 deletions(-) diff --git a/internal/service/guardduty/finding_ids_data_source_test.go b/internal/service/guardduty/finding_ids_data_source_test.go index 63e53c67324..7daeb0bb6a7 100644 --- a/internal/service/guardduty/finding_ids_data_source_test.go +++ b/internal/service/guardduty/finding_ids_data_source_test.go @@ -29,7 +29,6 @@ func testAccFindingIDsDataSource_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "detector_id", detectorDataSourceName, names.AttrID), resource.TestCheckResourceAttrSet(dataSourceName, "has_findings"), - resource.TestCheckResourceAttrSet(dataSourceName, "finding_ids.#"), ), }, }, diff --git a/internal/service/guardduty/threatintelset_test.go b/internal/service/guardduty/threatintelset_test.go index 7b778f4271b..165429d5915 100644 --- a/internal/service/guardduty/threatintelset_test.go +++ b/internal/service/guardduty/threatintelset_test.go @@ -177,46 +177,81 @@ func testAccCheckThreatIntelSetExists(ctx context.Context, name string) resource } } -func testAccThreatIntelSetConfig_basic(bucketName, keyName, threatintelsetName string, activate bool) string { +func testAccThreatIntelSetConfig_base(rName string) string { return fmt.Sprintf(` -resource "aws_guardduty_detector" "test" {} - resource "aws_s3_bucket" "test" { - bucket = "%s" + bucket = %[1]q force_destroy = true } +resource "aws_s3_bucket_ownership_controls" "test" { + bucket = aws_s3_bucket.test.id + rule { + object_ownership = "BucketOwnerPreferred" + } +} + +resource "aws_s3_bucket_public_access_block" "test" { + bucket = aws_s3_bucket.test.id + + block_public_acls = false + block_public_policy = false + ignore_public_acls = false + restrict_public_buckets = false +} + +resource "aws_s3_bucket_acl" "test" { + depends_on = [ + aws_s3_bucket_ownership_controls.test, + aws_s3_bucket_public_access_block.test, + ] + + bucket = aws_s3_bucket.test.id + acl = "public-read" +} +`, rName) +} + +func testAccThreatIntelSetConfig_basic(bucketName, keyName, threatintelsetName string, activate bool) string { + return acctest.ConfigCompose(testAccThreatIntelSetConfig_base(bucketName), + fmt.Sprintf(` +resource "aws_guardduty_detector" "test" {} + resource "aws_s3_object" "test" { acl = "public-read" content = "10.0.0.0/8\n" bucket = aws_s3_bucket.test.id - key = "%s" + key = %[1]q + + depends_on = [ + aws_s3_bucket_acl.test, + ] } resource "aws_guardduty_threatintelset" "test" { - name = "%s" + name = %[2]q detector_id = aws_guardduty_detector.test.id format = "TXT" location = "https://s3.amazonaws.com/${aws_s3_object.test.bucket}/${aws_s3_object.test.key}" - activate = %t + activate = %[3]t } -`, bucketName, keyName, threatintelsetName, activate) +`, keyName, threatintelsetName, activate)) } func testAccThreatIntelSetConfig_tags1(rName, tagKey1, tagValue1 string) string { - return fmt.Sprintf(` + return acctest.ConfigCompose(testAccThreatIntelSetConfig_base(rName), + fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} -resource "aws_s3_bucket" "test" { - bucket = %[1]q - force_destroy = true -} - resource "aws_s3_object" "test" { acl = "public-read" content = "10.0.0.0/8\n" bucket = aws_s3_bucket.test.id key = %[1]q + + depends_on = [ + aws_s3_bucket_acl.test, + ] } resource "aws_guardduty_threatintelset" "test" { @@ -230,23 +265,23 @@ resource "aws_guardduty_threatintelset" "test" { %[2]q = %[3]q } } -`, rName, tagKey1, tagValue1) +`, rName, tagKey1, tagValue1)) } func testAccThreatIntelSetConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return fmt.Sprintf(` + return acctest.ConfigCompose(testAccThreatIntelSetConfig_base(rName), + fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} -resource "aws_s3_bucket" "test" { - bucket = %[1]q - force_destroy = true -} - resource "aws_s3_object" "test" { acl = "public-read" content = "10.0.0.0/8\n" bucket = aws_s3_bucket.test.id key = %[1]q + + depends_on = [ + aws_s3_bucket_acl.test, + ] } resource "aws_guardduty_threatintelset" "test" { @@ -261,5 +296,5 @@ resource "aws_guardduty_threatintelset" "test" { %[4]q = %[5]q } } -`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } From c840b6f86c24168140ac9ac5e676fc43429b09b7 Mon Sep 17 00:00:00 2001 From: Adrian Johnson Date: Fri, 2 Aug 2024 14:07:08 -0500 Subject: [PATCH 19/22] add error precheck for access denied --- .../service/guardduty/malware_protection_plan_test.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/internal/service/guardduty/malware_protection_plan_test.go b/internal/service/guardduty/malware_protection_plan_test.go index e1119109ffb..c0d0af8a0e7 100644 --- a/internal/service/guardduty/malware_protection_plan_test.go +++ b/internal/service/guardduty/malware_protection_plan_test.go @@ -23,6 +23,17 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) +func init() { + acctest.RegisterServiceErrorCheckFunc(names.GuardDutyServiceID, testAccErrorCheckSkip) + +} + +func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { + return acctest.ErrorCheckSkipMessagesContaining(t, + "AccessDeniedException: User", + ) +} + func TestAccGuardDutyMalwareProtectionPlan_basic(t *testing.T) { ctx := acctest.Context(t) From 04d6e348cddc89a4d21949171cc0177e29fce819 Mon Sep 17 00:00:00 2001 From: Adrian Johnson Date: Fri, 2 Aug 2024 14:37:48 -0500 Subject: [PATCH 20/22] chore: linter --- internal/service/guardduty/malware_protection_plan_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/service/guardduty/malware_protection_plan_test.go b/internal/service/guardduty/malware_protection_plan_test.go index c0d0af8a0e7..6d84663b6f4 100644 --- a/internal/service/guardduty/malware_protection_plan_test.go +++ b/internal/service/guardduty/malware_protection_plan_test.go @@ -25,7 +25,6 @@ import ( func init() { acctest.RegisterServiceErrorCheckFunc(names.GuardDutyServiceID, testAccErrorCheckSkip) - } func testAccErrorCheckSkip(t *testing.T) resource.ErrorCheckFunc { From f057711689e28ed862bfb0241e8ec4999c1fdd6f Mon Sep 17 00:00:00 2001 From: Adrian Johnson Date: Fri, 2 Aug 2024 15:07:43 -0500 Subject: [PATCH 21/22] chore: linter --- internal/service/guardduty/tags_gen.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/service/guardduty/tags_gen.go b/internal/service/guardduty/tags_gen.go index 63e0fd57d77..ec3ad1890d6 100644 --- a/internal/service/guardduty/tags_gen.go +++ b/internal/service/guardduty/tags_gen.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/guardduty" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" From e14726408142a51f44d60453c111b163013e7096 Mon Sep 17 00:00:00 2001 From: Adrian Johnson Date: Fri, 2 Aug 2024 15:28:27 -0500 Subject: [PATCH 22/22] chore: linter --- internal/service/guardduty/generate.go | 2 +- internal/service/guardduty/tags_gen.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/service/guardduty/generate.go b/internal/service/guardduty/generate.go index bfc0372ffaa..69da3152fb7 100644 --- a/internal/service/guardduty/generate.go +++ b/internal/service/guardduty/generate.go @@ -1,7 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ServiceTagsMap -KVTValues -SkipTypesImp -SkipAWSServiceImp -ListTags -UpdateTags +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ServiceTagsMap -KVTValues -SkipTypesImp -ListTags -UpdateTags //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/guardduty/tags_gen.go b/internal/service/guardduty/tags_gen.go index ec3ad1890d6..63e0fd57d77 100644 --- a/internal/service/guardduty/tags_gen.go +++ b/internal/service/guardduty/tags_gen.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/guardduty" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging"