From 9d06385672c83ee0f099092cc5f22eae6dfe1f6d Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Tue, 23 Jul 2024 12:48:51 +0200 Subject: [PATCH 01/39] feat: regenerate client to v2 --- go.mod | 1 + go.sum | 2 + internal/conns/awsclient_gen.go | 6 +- internal/service/storagegateway/generate.go | 2 +- .../service_endpoint_resolver_gen.go | 66 ++++---- .../service_endpoints_gen_test.go | 146 +++++++++++++++--- .../storagegateway/service_package_gen.go | 28 ++-- internal/service/storagegateway/tags_gen.go | 36 ++--- names/data/names_data.hcl | 2 +- 9 files changed, 192 insertions(+), 97 deletions(-) diff --git a/go.mod b/go.mod index 859016104c4a..1014edefa947 100644 --- a/go.mod +++ b/go.mod @@ -283,6 +283,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect + github.com/aws/aws-sdk-go-v2/service/storagegateway v1.31.3 // indirect github.com/bgentry/speakeasy v0.1.0 // indirect github.com/boombuler/barcode v1.0.1 // indirect github.com/bufbuild/protocompile v0.6.0 // indirect diff --git a/go.sum b/go.sum index 963aae45472d..38e02ab19ebf 100644 --- a/go.sum +++ b/go.sum @@ -438,6 +438,8 @@ github.com/aws/aws-sdk-go-v2/service/ssoadmin v1.27.3 h1:pBE7FzR3AUpauidRUITPlDW github.com/aws/aws-sdk-go-v2/service/ssoadmin v1.27.3/go.mod h1:EyoPT+dUT5zqspxSub9KHDWOZyIP30bPgIavBvGGVz0= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw= +github.com/aws/aws-sdk-go-v2/service/storagegateway v1.31.3 h1:0hdxWCS8mM4qsZI3GldBkXeee4X25aC9wZGQhpbt6w8= +github.com/aws/aws-sdk-go-v2/service/storagegateway v1.31.3/go.mod h1:N2tZQtDCR/Ls4o1pH6neRhhlkhKNE6SoruLn6nTpnzU= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ= github.com/aws/aws-sdk-go-v2/service/swf v1.25.3 h1:7zYsHA9ORjiCHYzTJf0g+gwo3mPpn2XbMlWQreiXWdM= diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index 173fa10866cc..559e4a8d49ca 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -195,6 +195,7 @@ import ( ssmsap_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ssmsap" sso_sdkv2 "github.com/aws/aws-sdk-go-v2/service/sso" ssoadmin_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ssoadmin" + storagegateway_sdkv2 "github.com/aws/aws-sdk-go-v2/service/storagegateway" sts_sdkv2 "github.com/aws/aws-sdk-go-v2/service/sts" swf_sdkv2 "github.com/aws/aws-sdk-go-v2/service/swf" synthetics_sdkv2 "github.com/aws/aws-sdk-go-v2/service/synthetics" @@ -247,7 +248,6 @@ import ( servicecatalog_sdkv1 "github.com/aws/aws-sdk-go/service/servicecatalog" ses_sdkv1 "github.com/aws/aws-sdk-go/service/ses" simpledb_sdkv1 "github.com/aws/aws-sdk-go/service/simpledb" - storagegateway_sdkv1 "github.com/aws/aws-sdk-go/service/storagegateway" worklink_sdkv1 "github.com/aws/aws-sdk-go/service/worklink" "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/names" @@ -1169,8 +1169,8 @@ func (c *AWSClient) SimpleDBConn(ctx context.Context) *simpledb_sdkv1.SimpleDB { return errs.Must(conn[*simpledb_sdkv1.SimpleDB](ctx, c, names.SimpleDB, make(map[string]any))) } -func (c *AWSClient) StorageGatewayConn(ctx context.Context) *storagegateway_sdkv1.StorageGateway { - return errs.Must(conn[*storagegateway_sdkv1.StorageGateway](ctx, c, names.StorageGateway, make(map[string]any))) +func (c *AWSClient) StorageGatewayClient(ctx context.Context) *storagegateway_sdkv2.Client { + return errs.Must(client[*storagegateway_sdkv2.Client](ctx, c, names.StorageGateway, make(map[string]any))) } func (c *AWSClient) SyntheticsClient(ctx context.Context) *synthetics_sdkv2.Client { diff --git a/internal/service/storagegateway/generate.go b/internal/service/storagegateway/generate.go index 81f7facca182..a786dec53634 100644 --- a/internal/service/storagegateway/generate.go +++ b/internal/service/storagegateway/generate.go @@ -1,7 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -ListTags -ListTagsInIDElem=ResourceARN -ServiceTagsSlice -TagOp=AddTagsToResource -TagInIDElem=ResourceARN -UntagOp=RemoveTagsFromResource -UpdateTags +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ListTags -ListTagsInIDElem=ResourceARN -ServiceTagsSlice -TagOp=AddTagsToResource -TagInIDElem=ResourceARN -UntagOp=RemoveTagsFromResource -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/storagegateway/service_endpoint_resolver_gen.go b/internal/service/storagegateway/service_endpoint_resolver_gen.go index d9b168c2ab45..c8134416e82b 100644 --- a/internal/service/storagegateway/service_endpoint_resolver_gen.go +++ b/internal/service/storagegateway/service_endpoint_resolver_gen.go @@ -6,65 +6,63 @@ import ( "context" "fmt" "net" - "net/url" - endpoints_sdkv1 "github.com/aws/aws-sdk-go/aws/endpoints" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + storagegateway_sdkv2 "github.com/aws/aws-sdk-go-v2/service/storagegateway" + 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{} +var _ storagegateway_sdkv2.EndpointResolverV2 = resolverSDKv2{} -type resolverSDKv1 struct { - ctx context.Context +type resolverSDKv2 struct { + defaultResolver storagegateway_sdkv2.EndpointResolverV2 } -func newEndpointResolverSDKv1(ctx context.Context) resolverSDKv1 { - return resolverSDKv1{ - ctx: ctx, +func newEndpointResolverSDKv2() resolverSDKv2 { + return resolverSDKv2{ + defaultResolver: storagegateway_sdkv2.NewDefaultEndpointResolverV2(), } } -func (r resolverSDKv1) EndpointFor(service, region string, opts ...func(*endpoints_sdkv1.Options)) (endpoint endpoints_sdkv1.ResolvedEndpoint, err error) { - ctx := r.ctx +func (r resolverSDKv2) ResolveEndpoint(ctx context.Context, params storagegateway_sdkv2.EndpointParameters) (endpoint smithyendpoints.Endpoint, err error) { + params = params.WithDefaults() + useFIPS := aws_sdkv2.ToBool(params.UseFIPS) - var opt endpoints_sdkv1.Options - opt.Set(opts...) - - useFIPS := opt.UseFIPSEndpoint == endpoints_sdkv1.FIPSEndpointStateEnabled + if eps := params.Endpoint; aws_sdkv2.ToString(eps) != "" { + tflog.Debug(ctx, "setting endpoint", map[string]any{ + "tf_aws.endpoint": endpoint, + }) - defaultResolver := endpoints_sdkv1.DefaultResolver() + if useFIPS { + tflog.Debug(ctx, "endpoint set, ignoring UseFIPSEndpoint setting") + params.UseFIPS = aws_sdkv2.Bool(false) + } - if useFIPS { + return r.defaultResolver.ResolveEndpoint(ctx, params) + } else if useFIPS { ctx = tflog.SetField(ctx, "tf_aws.use_fips", useFIPS) - endpoint, err = defaultResolver.EndpointFor(service, region, opts...) + endpoint, err = r.defaultResolver.ResolveEndpoint(ctx, params) if err != nil { return endpoint, err } tflog.Debug(ctx, "endpoint resolved", map[string]any{ - "tf_aws.endpoint": endpoint.URL, + "tf_aws.endpoint": endpoint.URI.String(), }) - var endpointURL *url.URL - endpointURL, err = url.Parse(endpoint.URL) - if err != nil { - return endpoint, err - } - - hostname := endpointURL.Hostname() + hostname := endpoint.URI.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 - }) + params.UseFIPS = aws_sdkv2.Bool(false) } else { - err = fmt.Errorf("looking up accessanalyzer endpoint %q: %s", hostname, err) + err = fmt.Errorf("looking up storagegateway endpoint %q: %s", hostname, err) return } } else { @@ -72,5 +70,13 @@ func (r resolverSDKv1) EndpointFor(service, region string, opts ...func(*endpoin } } - return defaultResolver.EndpointFor(service, region, opts...) + return r.defaultResolver.ResolveEndpoint(ctx, params) +} + +func withBaseEndpoint(endpoint string) func(*storagegateway_sdkv2.Options) { + return func(o *storagegateway_sdkv2.Options) { + if endpoint != "" { + o.BaseEndpoint = aws_sdkv2.String(endpoint) + } + } } diff --git a/internal/service/storagegateway/service_endpoints_gen_test.go b/internal/service/storagegateway/service_endpoints_gen_test.go index 2cb9cbabdcac..536600315232 100644 --- a/internal/service/storagegateway/service_endpoints_gen_test.go +++ b/internal/service/storagegateway/service_endpoints_gen_test.go @@ -4,18 +4,22 @@ package storagegateway_test import ( "context" + "errors" "fmt" "maps" "net" "net/url" "os" "path/filepath" + "reflect" "strings" "testing" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" - storagegateway_sdkv1 "github.com/aws/aws-sdk-go/service/storagegateway" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + storagegateway_sdkv2 "github.com/aws/aws-sdk-go-v2/service/storagegateway" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/google/go-cmp/cmp" "github.com/hashicorp/aws-sdk-go-base/v2/servicemocks" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -240,54 +244,63 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S } func defaultEndpoint(region string) (url.URL, error) { - r := endpoints.DefaultResolver() + r := storagegateway_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(storagegateway_sdkv1.EndpointsID, region) + ep, err := r.ResolveEndpoint(context.Background(), storagegateway_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + }) if err != nil { return url.URL{}, err } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return *url, nil + return ep.URI, nil } func defaultFIPSEndpoint(region string) (url.URL, error) { - r := endpoints.DefaultResolver() + r := storagegateway_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(storagegateway_sdkv1.EndpointsID, region, func(opt *endpoints.Options) { - opt.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled + ep, err := r.ResolveEndpoint(context.Background(), storagegateway_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + UseFIPS: aws_sdkv2.Bool(true), }) if err != nil { return url.URL{}, err } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return *url, nil + return ep.URI, nil } func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { t.Helper() - client := meta.StorageGatewayConn(ctx) + client := meta.StorageGatewayClient(ctx) - req, _ := client.ListGatewaysRequest(&storagegateway_sdkv1.ListGatewaysInput{}) + var result apiCallParams - req.HTTPRequest.URL.Path = "/" - - return apiCallParams{ - endpoint: req.HTTPRequest.URL.String(), - region: aws_sdkv1.StringValue(client.Config.Region), + _, err := client.ListGateways(ctx, &storagegateway_sdkv2.ListGatewaysInput{}, + func(opts *storagegateway_sdkv2.Options) { + opts.APIOptions = append(opts.APIOptions, + addRetrieveEndpointURLMiddleware(t, &result.endpoint), + addRetrieveRegionMiddleware(&result.region), + addCancelRequestMiddleware(), + ) + }, + ) + if err == nil { + t.Fatal("Expected an error, got none") + } else if !errors.Is(err, errCancelOperation) { + t.Fatalf("Unexpected error: %s", err) } + + return result } func withNoConfig(_ *caseSetup) { @@ -466,6 +479,89 @@ func testEndpointCase(t *testing.T, region string, testcase endpointTestCase, ca } } +func addRetrieveEndpointURLMiddleware(t *testing.T, endpoint *string) func(*middleware.Stack) error { + return func(stack *middleware.Stack) error { + return stack.Finalize.Add( + retrieveEndpointURLMiddleware(t, endpoint), + middleware.After, + ) + } +} + +func retrieveEndpointURLMiddleware(t *testing.T, endpoint *string) middleware.FinalizeMiddleware { + return middleware.FinalizeMiddlewareFunc( + "Test: Retrieve Endpoint", + func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { + t.Helper() + + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + t.Fatalf("Expected *github.com/aws/smithy-go/transport/http.Request, got %s", fullTypeName(in.Request)) + } + + url := request.URL + url.RawQuery = "" + url.Path = "/" + + *endpoint = url.String() + + return next.HandleFinalize(ctx, in) + }) +} + +func addRetrieveRegionMiddleware(region *string) func(*middleware.Stack) error { + return func(stack *middleware.Stack) error { + return stack.Serialize.Add( + retrieveRegionMiddleware(region), + middleware.After, + ) + } +} + +func retrieveRegionMiddleware(region *string) middleware.SerializeMiddleware { + return middleware.SerializeMiddlewareFunc( + "Test: Retrieve Region", + func(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (middleware.SerializeOutput, middleware.Metadata, error) { + *region = awsmiddleware.GetRegion(ctx) + + return next.HandleSerialize(ctx, in) + }, + ) +} + +var errCancelOperation = fmt.Errorf("Test: Canceling request") + +func addCancelRequestMiddleware() func(*middleware.Stack) error { + return func(stack *middleware.Stack) error { + return stack.Finalize.Add( + cancelRequestMiddleware(), + middleware.After, + ) + } +} + +// cancelRequestMiddleware creates a Smithy middleware that intercepts the request before sending and cancels it +func cancelRequestMiddleware() middleware.FinalizeMiddleware { + return middleware.FinalizeMiddlewareFunc( + "Test: Cancel Requests", + func(_ context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { + return middleware.FinalizeOutput{}, middleware.Metadata{}, errCancelOperation + }) +} + +func fullTypeName(i interface{}) string { + return fullValueTypeName(reflect.ValueOf(i)) +} + +func fullValueTypeName(v reflect.Value) string { + if v.Kind() == reflect.Ptr { + return "*" + fullValueTypeName(reflect.Indirect(v)) + } + + requestType := v.Type() + return fmt.Sprintf("%s.%s", requestType.PkgPath(), requestType.Name()) +} + func generateSharedConfigFile(config configFile) string { var buf strings.Builder diff --git a/internal/service/storagegateway/service_package_gen.go b/internal/service/storagegateway/service_package_gen.go index 2c934e1c2840..7fda39d7bc24 100644 --- a/internal/service/storagegateway/service_package_gen.go +++ b/internal/service/storagegateway/service_package_gen.go @@ -5,10 +5,8 @@ package storagegateway import ( "context" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - storagegateway_sdkv1 "github.com/aws/aws-sdk-go/service/storagegateway" - "github.com/hashicorp/terraform-plugin-log/tflog" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + storagegateway_sdkv2 "github.com/aws/aws-sdk-go-v2/service/storagegateway" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" "github.com/hashicorp/terraform-provider-aws/names" @@ -114,22 +112,14 @@ func (p *servicePackage) ServicePackageName() string { return names.StorageGateway } -// 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) (*storagegateway_sdkv1.StorageGateway, error) { - sess := config[names.AttrSession].(*session_sdkv1.Session) +// NewClient returns a new AWS SDK for Go v2 client for this service package's AWS API. +func (p *servicePackage) NewClient(ctx context.Context, config map[string]any) (*storagegateway_sdkv2.Client, error) { + cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) - 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 storagegateway_sdkv1.New(sess.Copy(&cfg)), nil + return storagegateway_sdkv2.NewFromConfig(cfg, + storagegateway_sdkv2.WithEndpointResolverV2(newEndpointResolverSDKv2()), + withBaseEndpoint(config[names.AttrEndpoint].(string)), + ), nil } func ServicePackage(ctx context.Context) conns.ServicePackage { diff --git a/internal/service/storagegateway/tags_gen.go b/internal/service/storagegateway/tags_gen.go index 6b49703edee9..148815be925d 100644 --- a/internal/service/storagegateway/tags_gen.go +++ b/internal/service/storagegateway/tags_gen.go @@ -5,9 +5,9 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" - "github.com/aws/aws-sdk-go/service/storagegateway/storagegatewayiface" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" @@ -19,12 +19,12 @@ import ( // listTags lists storagegateway 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 storagegatewayiface.StorageGatewayAPI, identifier string) (tftags.KeyValueTags, error) { +func listTags(ctx context.Context, conn *storagegateway.Client, identifier string, optFns ...func(*storagegateway.Options)) (tftags.KeyValueTags, error) { input := &storagegateway.ListTagsForResourceInput{ ResourceARN: aws.String(identifier), } - output, err := conn.ListTagsForResourceWithContext(ctx, input) + output, err := conn.ListTagsForResource(ctx, input, optFns...) if err != nil { return tftags.New(ctx, nil), err @@ -36,7 +36,7 @@ func listTags(ctx context.Context, conn storagegatewayiface.StorageGatewayAPI, i // ListTags lists storagegateway 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).StorageGatewayConn(ctx), identifier) + tags, err := listTags(ctx, meta.(*conns.AWSClient).StorageGatewayClient(ctx), identifier) if err != nil { return err @@ -52,11 +52,11 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri // []*SERVICE.Tag handling // Tags returns storagegateway service tags. -func Tags(tags tftags.KeyValueTags) []*storagegateway.Tag { - result := make([]*storagegateway.Tag, 0, len(tags)) +func Tags(tags tftags.KeyValueTags) []awstypes.Tag { + result := make([]awstypes.Tag, 0, len(tags)) for k, v := range tags.Map() { - tag := &storagegateway.Tag{ + tag := awstypes.Tag{ Key: aws.String(k), Value: aws.String(v), } @@ -68,11 +68,11 @@ func Tags(tags tftags.KeyValueTags) []*storagegateway.Tag { } // KeyValueTags creates tftags.KeyValueTags from storagegateway service tags. -func KeyValueTags(ctx context.Context, tags []*storagegateway.Tag) tftags.KeyValueTags { +func KeyValueTags(ctx context.Context, tags []awstypes.Tag) tftags.KeyValueTags { m := make(map[string]*string, len(tags)) for _, tag := range tags { - m[aws.StringValue(tag.Key)] = tag.Value + m[aws.ToString(tag.Key)] = tag.Value } return tftags.New(ctx, m) @@ -80,7 +80,7 @@ func KeyValueTags(ctx context.Context, tags []*storagegateway.Tag) tftags.KeyVal // getTagsIn returns storagegateway service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) []*storagegateway.Tag { +func getTagsIn(ctx context.Context) []awstypes.Tag { if inContext, ok := tftags.FromContext(ctx); ok { if tags := Tags(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { return tags @@ -91,7 +91,7 @@ func getTagsIn(ctx context.Context) []*storagegateway.Tag { } // setTagsOut sets storagegateway service tags in Context. -func setTagsOut(ctx context.Context, tags []*storagegateway.Tag) { +func setTagsOut(ctx context.Context, tags []awstypes.Tag) { if inContext, ok := tftags.FromContext(ctx); ok { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } @@ -100,7 +100,7 @@ func setTagsOut(ctx context.Context, tags []*storagegateway.Tag) { // updateTags updates storagegateway 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 storagegatewayiface.StorageGatewayAPI, identifier string, oldTagsMap, newTagsMap any) error { +func updateTags(ctx context.Context, conn *storagegateway.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*storagegateway.Options)) error { oldTags := tftags.New(ctx, oldTagsMap) newTags := tftags.New(ctx, newTagsMap) @@ -111,10 +111,10 @@ func updateTags(ctx context.Context, conn storagegatewayiface.StorageGatewayAPI, if len(removedTags) > 0 { input := &storagegateway.RemoveTagsFromResourceInput{ ResourceARN: aws.String(identifier), - TagKeys: aws.StringSlice(removedTags.Keys()), + TagKeys: removedTags.Keys(), } - _, err := conn.RemoveTagsFromResourceWithContext(ctx, input) + _, err := conn.RemoveTagsFromResource(ctx, input, optFns...) if err != nil { return fmt.Errorf("untagging resource (%s): %w", identifier, err) @@ -129,7 +129,7 @@ func updateTags(ctx context.Context, conn storagegatewayiface.StorageGatewayAPI, Tags: Tags(updatedTags), } - _, err := conn.AddTagsToResourceWithContext(ctx, input) + _, err := conn.AddTagsToResource(ctx, input, optFns...) if err != nil { return fmt.Errorf("tagging resource (%s): %w", identifier, err) @@ -142,5 +142,5 @@ func updateTags(ctx context.Context, conn storagegatewayiface.StorageGatewayAPI, // UpdateTags updates storagegateway 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).StorageGatewayConn(ctx), identifier, oldTags, newTags) + return updateTags(ctx, meta.(*conns.AWSClient).StorageGatewayClient(ctx), identifier, oldTags, newTags) } diff --git a/names/data/names_data.hcl b/names/data/names_data.hcl index d3fcf6b3b489..f0bbe5a924ba 100644 --- a/names/data/names_data.hcl +++ b/names/data/names_data.hcl @@ -8988,7 +8988,7 @@ service "storagegateway" { sdk { id = "Storage Gateway" - client_version = [1] + client_version = [2] } names { From 4bba24e348ca65f9d6fe874c680786871bce8a30 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Tue, 23 Jul 2024 12:49:06 +0200 Subject: [PATCH 02/39] feat: migrate r/cache to sdkv2 --- internal/service/storagegateway/cache.go | 25 ++++++++++--------- internal/service/storagegateway/cache_test.go | 10 ++++---- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/internal/service/storagegateway/cache.go b/internal/service/storagegateway/cache.go index 358ffb9662af..263dc9ffd9bb 100644 --- a/internal/service/storagegateway/cache.go +++ b/internal/service/storagegateway/cache.go @@ -9,9 +9,10 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/storagegateway" + "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/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" @@ -49,17 +50,17 @@ func resourceCache() *schema.Resource { func resourceCacheCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) diskID := d.Get("disk_id").(string) gatewayARN := d.Get("gateway_arn").(string) id := cacheCreateResourceID(gatewayARN, diskID) inputAC := &storagegateway.AddCacheInput{ - DiskIds: aws.StringSlice([]string{diskID}), + DiskIds: []string{diskID}, GatewayARN: aws.String(gatewayARN), } - _, err := conn.AddCacheWithContext(ctx, inputAC) + _, err := conn.AddCache(ctx, inputAC) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Cache (%s): %s", id, err) @@ -76,8 +77,8 @@ func resourceCacheCreate(ctx context.Context, d *schema.ResourceData, meta inter inputLLD := &storagegateway.ListLocalDisksInput{ GatewayARN: aws.String(gatewayARN), } - disk, err := findLocalDisk(ctx, conn, inputLLD, func(v *storagegateway.Disk) bool { - return aws.StringValue(v.DiskId) == diskID || aws.StringValue(v.DiskNode) == diskID || aws.StringValue(v.DiskPath) == diskID + disk, err := findLocalDisk(ctx, conn, inputLLD, func(v awstypes.Disk) bool { + return aws.ToString(v.DiskId) == diskID || aws.ToString(v.DiskNode) == diskID || aws.ToString(v.DiskPath) == diskID }) switch { @@ -85,7 +86,7 @@ func resourceCacheCreate(ctx context.Context, d *schema.ResourceData, meta inter case err != nil: return sdkdiag.AppendErrorf(diags, "reading Storage Gateway local disk: %s", err) default: - id = cacheCreateResourceID(gatewayARN, aws.StringValue(disk.DiskId)) + id = cacheCreateResourceID(gatewayARN, aws.ToString(disk.DiskId)) d.SetId(id) } @@ -94,7 +95,7 @@ func resourceCacheCreate(ctx context.Context, d *schema.ResourceData, meta inter func resourceCacheRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) gatewayARN, diskID, err := cacheParseResourceID(d.Id()) if err != nil { @@ -105,7 +106,7 @@ func resourceCacheRead(ctx context.Context, d *schema.ResourceData, meta interfa GatewayARN: aws.String(gatewayARN), } - output, err := conn.DescribeCacheWithContext(ctx, input) + output, err := conn.DescribeCache(ctx, input) if err != nil { if IsErrGatewayNotFound(err) { log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) @@ -123,7 +124,7 @@ func resourceCacheRead(ctx context.Context, d *schema.ResourceData, meta interfa found := false for _, existingDiskID := range output.DiskIds { - if aws.StringValue(existingDiskID) == diskID { + if existingDiskID == diskID { found = true break } diff --git a/internal/service/storagegateway/cache_test.go b/internal/service/storagegateway/cache_test.go index a61f04fefa0b..21c24f4fd251 100644 --- a/internal/service/storagegateway/cache_test.go +++ b/internal/service/storagegateway/cache_test.go @@ -8,8 +8,8 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -146,7 +146,7 @@ func testAccCheckCacheExists(ctx context.Context, resourceName string) resource. return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) gatewayARN, diskID, err := tfstoragegateway.CacheParseResourceID(rs.Primary.ID) if err != nil { @@ -157,7 +157,7 @@ func testAccCheckCacheExists(ctx context.Context, resourceName string) resource. GatewayARN: aws.String(gatewayARN), } - output, err := conn.DescribeCacheWithContext(ctx, input) + output, err := conn.DescribeCache(ctx, input) if err != nil { return fmt.Errorf("error reading Storage Gateway cache: %s", err) @@ -168,7 +168,7 @@ func testAccCheckCacheExists(ctx context.Context, resourceName string) resource. } for _, existingDiskID := range output.DiskIds { - if aws.StringValue(existingDiskID) == diskID { + if existingDiskID == diskID { return nil } } From bd171da79b1b67d0288e56b78bd348a60847a482 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Tue, 23 Jul 2024 12:49:22 +0200 Subject: [PATCH 03/39] feat: migrate errors and find package to use sdkv2 --- internal/service/storagegateway/errors.go | 11 ++-- internal/service/storagegateway/find.go | 71 ++++++++++++----------- 2 files changed, 41 insertions(+), 41 deletions(-) diff --git a/internal/service/storagegateway/errors.go b/internal/service/storagegateway/errors.go index 064880e8fac3..0ea5de3704e8 100644 --- a/internal/service/storagegateway/errors.go +++ b/internal/service/storagegateway/errors.go @@ -4,8 +4,7 @@ package storagegateway import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) @@ -23,12 +22,12 @@ const ( // // See https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIErrorResponses for details. func operationErrorCode(err error) string { - if v, ok := errs.As[*storagegateway.InternalServerError](err); ok && v.Error_ != nil { - return aws.StringValue(v.Error_.ErrorCode) + if v, ok := errs.As[*awstypes.InternalServerError](err); ok && v.Error_ != nil { + return string(v.Error_.ErrorCode) } - if v, ok := errs.As[*storagegateway.InvalidGatewayRequestException](err); ok && v.Error_ != nil { - return aws.StringValue(v.Error_.ErrorCode) + if v, ok := errs.As[*awstypes.InvalidGatewayRequestException](err); ok && v.Error_ != nil { + return string(v.Error_.ErrorCode) } return "" diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go index b5e7c7685928..7cf71de6f5e2 100644 --- a/internal/service/storagegateway/find.go +++ b/internal/service/storagegateway/find.go @@ -6,26 +6,27 @@ package storagegateway import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func findLocalDisk(ctx context.Context, conn *storagegateway.StorageGateway, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[*storagegateway.Disk]) (*storagegateway.Disk, error) { +func findLocalDisk(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[awstypes.Disk]) (*awstypes.Disk, error) { output, err := findLocalDisks(ctx, conn, input, filter) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func findLocalDisks(ctx context.Context, conn *storagegateway.StorageGateway, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[*storagegateway.Disk]) ([]*storagegateway.Disk, error) { - output, err := conn.ListLocalDisksWithContext(ctx, input) +func findLocalDisks(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[awstypes.Disk]) ([]awstypes.Disk, error) { + output, err := conn.ListLocalDisks(ctx, input) if err != nil { return nil, err @@ -38,34 +39,34 @@ func findLocalDisks(ctx context.Context, conn *storagegateway.StorageGateway, in return tfslices.Filter(output.Disks, filter), nil } -func findLocalDiskByGatewayARNAndDiskID(ctx context.Context, conn *storagegateway.StorageGateway, gatewayARN, diskID string) (*storagegateway.Disk, error) { +func findLocalDiskByGatewayARNAndDiskID(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskID string) (*awstypes.Disk, error) { input := &storagegateway.ListLocalDisksInput{ GatewayARN: aws.String(gatewayARN), } - return findLocalDisk(ctx, conn, input, func(v *storagegateway.Disk) bool { - return aws.StringValue(v.DiskId) == diskID + return findLocalDisk(ctx, conn, input, func(v awstypes.Disk) bool { + return aws.ToString(v.DiskId) == diskID }) } -func findLocalDiskByGatewayARNAndDiskPath(ctx context.Context, conn *storagegateway.StorageGateway, gatewayARN, diskPath string) (*storagegateway.Disk, error) { +func findLocalDiskByGatewayARNAndDiskPath(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskPath string) (*awstypes.Disk, error) { input := &storagegateway.ListLocalDisksInput{ GatewayARN: aws.String(gatewayARN), } - return findLocalDisk(ctx, conn, input, func(v *storagegateway.Disk) bool { - return aws.StringValue(v.DiskPath) == diskPath + return findLocalDisk(ctx, conn, input, func(v awstypes.Disk) bool { + return aws.ToString(v.DiskPath) == diskPath }) } -func FindUploadBufferDisk(ctx context.Context, conn *storagegateway.StorageGateway, gatewayARN string, diskID string) (*string, error) { +func FindUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gatewayARN string, diskID string) (*string, error) { input := &storagegateway.DescribeUploadBufferInput{ GatewayARN: aws.String(gatewayARN), } - var result *string + var result string - output, err := conn.DescribeUploadBufferWithContext(ctx, input) + output, err := conn.DescribeUploadBuffer(ctx, input) if err != nil { return nil, err @@ -76,23 +77,23 @@ func FindUploadBufferDisk(ctx context.Context, conn *storagegateway.StorageGatew } for _, diskId := range output.DiskIds { - if aws.StringValue(diskId) == diskID { + if diskId == diskID { result = diskId break } } - return result, err + return &result, err } -func FindGatewayByARN(ctx context.Context, conn *storagegateway.StorageGateway, arn string) (*storagegateway.DescribeGatewayInformationOutput, error) { +func FindGatewayByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*storagegateway.DescribeGatewayInformationOutput, error) { input := &storagegateway.DescribeGatewayInformationInput{ GatewayARN: aws.String(arn), } - output, err := conn.DescribeGatewayInformationWithContext(ctx, input) + output, err := conn.DescribeGatewayInformation(ctx, input) - if operationErrorCode(err) == operationErrCodeGatewayNotFound || tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeGatewayNotFound) { + if operationErrorCode(err) == operationErrCodeGatewayNotFound || tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -110,12 +111,12 @@ func FindGatewayByARN(ctx context.Context, conn *storagegateway.StorageGateway, return output, nil } -func FindNFSFileShareByARN(ctx context.Context, conn *storagegateway.StorageGateway, arn string) (*storagegateway.NFSFileShareInfo, error) { +func FindNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.NFSFileShareInfo, error) { input := &storagegateway.DescribeNFSFileSharesInput{ - FileShareARNList: aws.StringSlice([]string{arn}), + FileShareARNList: []string{arn}, } - output, err := conn.DescribeNFSFileSharesWithContext(ctx, input) + output, err := conn.DescribeNFSFileShares(ctx, input) if operationErrorCode(err) == operationErrCodeFileShareNotFound { return nil, &retry.NotFoundError{ @@ -128,7 +129,7 @@ func FindNFSFileShareByARN(ctx context.Context, conn *storagegateway.StorageGate return nil, err } - if output == nil || len(output.NFSFileShareInfoList) == 0 || output.NFSFileShareInfoList[0] == nil { + if output == nil || len(output.NFSFileShareInfoList) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -136,15 +137,15 @@ func FindNFSFileShareByARN(ctx context.Context, conn *storagegateway.StorageGate return nil, tfresource.NewTooManyResultsError(count, input) } - return output.NFSFileShareInfoList[0], nil + return &output.NFSFileShareInfoList[0], nil } -func FindSMBFileShareByARN(ctx context.Context, conn *storagegateway.StorageGateway, arn string) (*storagegateway.SMBFileShareInfo, error) { +func FindSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.SMBFileShareInfo, error) { input := &storagegateway.DescribeSMBFileSharesInput{ - FileShareARNList: aws.StringSlice([]string{arn}), + FileShareARNList: []string{arn}, } - output, err := conn.DescribeSMBFileSharesWithContext(ctx, input) + output, err := conn.DescribeSMBFileShares(ctx, input) if operationErrorCode(err) == operationErrCodeFileShareNotFound { return nil, &retry.NotFoundError{ @@ -157,7 +158,7 @@ func FindSMBFileShareByARN(ctx context.Context, conn *storagegateway.StorageGate return nil, err } - if output == nil || len(output.SMBFileShareInfoList) == 0 || output.SMBFileShareInfoList[0] == nil { + if output == nil || len(output.SMBFileShareInfoList) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -165,15 +166,15 @@ func FindSMBFileShareByARN(ctx context.Context, conn *storagegateway.StorageGate return nil, tfresource.NewTooManyResultsError(count, input) } - return output.SMBFileShareInfoList[0], nil + return &output.SMBFileShareInfoList[0], nil } -func FindFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.StorageGateway, arn string) (*storagegateway.FileSystemAssociationInfo, error) { +func FindFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.FileSystemAssociationInfo, error) { input := &storagegateway.DescribeFileSystemAssociationsInput{ - FileSystemAssociationARNList: []*string{aws.String(arn)}, + FileSystemAssociationARNList: []string{arn}, } - output, err := conn.DescribeFileSystemAssociationsWithContext(ctx, input) + output, err := conn.DescribeFileSystemAssociations(ctx, input) if operationErrorCode(err) == operationErrCodeFileSystemAssociationNotFound { return nil, &retry.NotFoundError{ @@ -186,7 +187,7 @@ func FindFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.St return nil, err } - if output == nil || len(output.FileSystemAssociationInfoList) == 0 || output.FileSystemAssociationInfoList[0] == nil { + if output == nil || len(output.FileSystemAssociationInfoList) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -194,5 +195,5 @@ func FindFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.St return nil, tfresource.NewTooManyResultsError(count, input) } - return output.FileSystemAssociationInfoList[0], nil + return &output.FileSystemAssociationInfoList[0], nil } From 68394b56ead219d5f7aba2926fc46c5a0f1b476b Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:54:49 +0200 Subject: [PATCH 04/39] feat: migrate r/working_storage to SDKv2 --- .../service/storagegateway/working_storage.go | 26 +++++++++---------- .../storagegateway/working_storage_test.go | 10 +++---- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/internal/service/storagegateway/working_storage.go b/internal/service/storagegateway/working_storage.go index 8dd87dcc4265..4b63e318c7e4 100644 --- a/internal/service/storagegateway/working_storage.go +++ b/internal/service/storagegateway/working_storage.go @@ -9,9 +9,9 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/storagegateway" + "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/storagegateway" "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" @@ -48,18 +48,18 @@ func ResourceWorkingStorage() *schema.Resource { func resourceWorkingStorageCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) diskID := d.Get("disk_id").(string) gatewayARN := d.Get("gateway_arn").(string) input := &storagegateway.AddWorkingStorageInput{ - DiskIds: []*string{aws.String(diskID)}, + DiskIds: []string{diskID}, GatewayARN: aws.String(gatewayARN), } - log.Printf("[DEBUG] Adding Storage Gateway Working Storage: %s", input) - _, err := conn.AddWorkingStorageWithContext(ctx, input) + log.Printf("[DEBUG] Adding Storage Gateway Working Storage: %#v", input) + _, err := conn.AddWorkingStorage(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "adding Storage Gateway Working Storage: %s", err) } @@ -71,9 +71,9 @@ func resourceWorkingStorageCreate(ctx context.Context, d *schema.ResourceData, m func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - gatewayARN, diskID, err := DecodeWorkingStorageID(d.Id()) + gatewayARN, diskID, err := decodeWorkingStorageID(d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Working Storage (%s): %s", d.Id(), err) } @@ -82,9 +82,9 @@ func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, met GatewayARN: aws.String(gatewayARN), } - output, err := conn.DescribeWorkingStorageWithContext(ctx, input) + output, err := conn.DescribeWorkingStorage(ctx, input) if err != nil { - if IsErrGatewayNotFound(err) { + if isErrGatewayNotFound(err) { log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -100,7 +100,7 @@ func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, met found := false for _, existingDiskID := range output.DiskIds { - if aws.StringValue(existingDiskID) == diskID { + if existingDiskID == diskID { found = true break } @@ -118,7 +118,7 @@ func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, met return diags } -func DecodeWorkingStorageID(id string) (string, string, error) { +func decodeWorkingStorageID(id string) (string, string, error) { // id = arn:aws:storagegateway:us-east-1:123456789012:gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 idFormatErr := fmt.Errorf("expected ID in form of GatewayARN:DiskId, received: %s", id) gatewayARNAndDisk, err := arn.Parse(id) diff --git a/internal/service/storagegateway/working_storage_test.go b/internal/service/storagegateway/working_storage_test.go index 665bab7f84cf..b9ae1fbbce7e 100644 --- a/internal/service/storagegateway/working_storage_test.go +++ b/internal/service/storagegateway/working_storage_test.go @@ -8,8 +8,8 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -116,7 +116,7 @@ func testAccCheckWorkingStorageExists(ctx context.Context, resourceName string) return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) gatewayARN, diskID, err := tfstoragegateway.DecodeWorkingStorageID(rs.Primary.ID) if err != nil { @@ -127,7 +127,7 @@ func testAccCheckWorkingStorageExists(ctx context.Context, resourceName string) GatewayARN: aws.String(gatewayARN), } - output, err := conn.DescribeWorkingStorageWithContext(ctx, input) + output, err := conn.DescribeWorkingStorage(ctx, input) if err != nil { return fmt.Errorf("error reading Storage Gateway working storage: %s", err) @@ -138,7 +138,7 @@ func testAccCheckWorkingStorageExists(ctx context.Context, resourceName string) } for _, existingDiskID := range output.DiskIds { - if aws.StringValue(existingDiskID) == diskID { + if existingDiskID == diskID { return nil } } From ef9d002b179d7c7ca5f6128b199ca2637301fcf1 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:55:05 +0200 Subject: [PATCH 05/39] feat: migrate r/cached_iscsi_volume to SDKv2 --- .../storagegateway/cached_iscsi_volume.go | 52 ++++++++++--------- .../cached_iscsi_volume_test.go | 44 ++++++++-------- 2 files changed, 50 insertions(+), 46 deletions(-) diff --git a/internal/service/storagegateway/cached_iscsi_volume.go b/internal/service/storagegateway/cached_iscsi_volume.go index cbd454d0a863..ad119c092321 100644 --- a/internal/service/storagegateway/cached_iscsi_volume.go +++ b/internal/service/storagegateway/cached_iscsi_volume.go @@ -10,15 +10,17 @@ 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/storagegateway" - "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/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "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" @@ -123,14 +125,14 @@ func resourceCachediSCSIVolume() *schema.Resource { func resourceCachediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.CreateCachediSCSIVolumeInput{ ClientToken: aws.String(id.UniqueId()), GatewayARN: aws.String(d.Get("gateway_arn").(string)), NetworkInterfaceId: aws.String(d.Get(names.AttrNetworkInterfaceID).(string)), TargetName: aws.String(d.Get("target_name").(string)), - VolumeSizeInBytes: aws.Int64(int64(d.Get("volume_size_in_bytes").(int))), + VolumeSizeInBytes: int64(d.Get("volume_size_in_bytes").(int)), Tags: getTagsIn(ctx), } @@ -150,30 +152,30 @@ func resourceCachediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData input.KMSEncrypted = aws.Bool(v.(bool)) } - log.Printf("[DEBUG] Creating Storage Gateway cached iSCSI volume: %s", input) - output, err := conn.CreateCachediSCSIVolumeWithContext(ctx, input) + log.Printf("[DEBUG] Creating Storage Gateway cached iSCSI volume: %#v", input) + output, err := conn.CreateCachediSCSIVolume(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway cached iSCSI volume: %s", err) } - d.SetId(aws.StringValue(output.VolumeARN)) + d.SetId(aws.ToString(output.VolumeARN)) return append(diags, resourceCachediSCSIVolumeRead(ctx, d, meta)...) } func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DescribeCachediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(d.Id())}, + VolumeARNs: []string{d.Id()}, } log.Printf("[DEBUG] Reading Storage Gateway cached iSCSI volume: %s", input) - output, err := conn.DescribeCachediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeCachediSCSIVolumes(ctx, input) if err != nil { - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) || tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) || errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { log.Printf("[WARN] Storage Gateway cached iSCSI volume %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -181,7 +183,7 @@ func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "reading Storage Gateway cached iSCSI volume %q: %s", d.Id(), err) } - if output == nil || len(output.CachediSCSIVolumes) == 0 || output.CachediSCSIVolumes[0] == nil || aws.StringValue(output.CachediSCSIVolumes[0].VolumeARN) != d.Id() { + if output == nil || len(output.CachediSCSIVolumes) == 0 || aws.ToString(output.CachediSCSIVolumes[0].VolumeARN) != d.Id() { log.Printf("[WARN] Storage Gateway cached iSCSI volume %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -189,7 +191,7 @@ func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, volume := output.CachediSCSIVolumes[0] - arn := aws.StringValue(volume.VolumeARN) + arn := aws.ToString(volume.VolumeARN) d.Set(names.AttrARN, arn) d.Set(names.AttrSnapshotID, volume.SourceSnapshotId) d.Set("volume_arn", arn) @@ -208,10 +210,10 @@ func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, d.Set(names.AttrNetworkInterfaceID, volume.VolumeiSCSIAttributes.NetworkInterfaceId) d.Set("network_interface_port", volume.VolumeiSCSIAttributes.NetworkInterfacePort) - targetARN := aws.StringValue(volume.VolumeiSCSIAttributes.TargetARN) + targetARN := aws.ToString(volume.VolumeiSCSIAttributes.TargetARN) d.Set(names.AttrTargetARN, targetARN) - gatewayARN, targetName, err := ParseVolumeGatewayARNAndTargetNameFromARN(targetARN) + gatewayARN, targetName, err := parseVolumeGatewayARNAndTargetNameFromARN(targetARN) if err != nil { return sdkdiag.AppendErrorf(diags, "parsing Storage Gateway volume gateway ARN and target name from target ARN %q: %s", targetARN, err) } @@ -232,22 +234,22 @@ func resourceCachediSCSIVolumeUpdate(ctx context.Context, d *schema.ResourceData func resourceCachediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DeleteVolumeInput{ VolumeARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting Storage Gateway cached iSCSI volume: %s", input) + log.Printf("[DEBUG] Deleting Storage Gateway cached iSCSI volume: %#v", input) err := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { - _, err := conn.DeleteVolumeWithContext(ctx, input) + _, err := conn.DeleteVolume(ctx, input) if err != nil { - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { return nil } // InvalidGatewayRequestException: The specified gateway is not connected. // Can occur during concurrent DeleteVolume operations - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified gateway is not connected") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { return retry.RetryableError(err) } return retry.NonRetryableError(err) @@ -255,9 +257,9 @@ func resourceCachediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData return nil }) if tfresource.TimedOut(err) { - _, err = conn.DeleteVolumeWithContext(ctx, input) + _, err = conn.DeleteVolume(ctx, input) } - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { return diags } if err != nil { @@ -267,7 +269,7 @@ func resourceCachediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData return diags } -func ParseVolumeGatewayARNAndTargetNameFromARN(inputARN string) (string, string, error) { +func parseVolumeGatewayARNAndTargetNameFromARN(inputARN string) (string, string, error) { // inputARN = arn:aws:storagegateway:us-east-2:111122223333:gateway/sgw-12A3456B/target/iqn.1997-05.com.amazon:TargetName targetARN, err := arn.Parse(inputARN) if err != nil { diff --git a/internal/service/storagegateway/cached_iscsi_volume_test.go b/internal/service/storagegateway/cached_iscsi_volume_test.go index d387804db4f4..83b7e53006de 100644 --- a/internal/service/storagegateway/cached_iscsi_volume_test.go +++ b/internal/service/storagegateway/cached_iscsi_volume_test.go @@ -9,14 +9,16 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" - "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/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" 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" tfstoragegateway "github.com/hashicorp/terraform-provider-aws/internal/service/storagegateway" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -81,7 +83,7 @@ func TestParseVolumeGatewayARNAndTargetNameFromARN(t *testing.T) { func TestAccStorageGatewayCachediSCSIVolume_basic(t *testing.T) { ctx := acctest.Context(t) - var cachedIscsiVolume storagegateway.CachediSCSIVolume + var cachedIscsiVolume awstypes.CachediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_cached_iscsi_volume.test" @@ -121,7 +123,7 @@ func TestAccStorageGatewayCachediSCSIVolume_basic(t *testing.T) { func TestAccStorageGatewayCachediSCSIVolume_kms(t *testing.T) { ctx := acctest.Context(t) - var cachedIscsiVolume storagegateway.CachediSCSIVolume + var cachedIscsiVolume awstypes.CachediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_cached_iscsi_volume.test" keyResourceName := "aws_kms_key.test" @@ -151,7 +153,7 @@ func TestAccStorageGatewayCachediSCSIVolume_kms(t *testing.T) { func TestAccStorageGatewayCachediSCSIVolume_tags(t *testing.T) { ctx := acctest.Context(t) - var cachedIscsiVolume storagegateway.CachediSCSIVolume + var cachedIscsiVolume awstypes.CachediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_cached_iscsi_volume.test" @@ -200,7 +202,7 @@ func TestAccStorageGatewayCachediSCSIVolume_tags(t *testing.T) { func TestAccStorageGatewayCachediSCSIVolume_snapshotID(t *testing.T) { ctx := acctest.Context(t) - var cachedIscsiVolume storagegateway.CachediSCSIVolume + var cachedIscsiVolume awstypes.CachediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_cached_iscsi_volume.test" @@ -240,7 +242,7 @@ func TestAccStorageGatewayCachediSCSIVolume_snapshotID(t *testing.T) { func TestAccStorageGatewayCachediSCSIVolume_sourceVolumeARN(t *testing.T) { acctest.Skip(t, "This test can cause Storage Gateway 2.0.10.0 to enter an irrecoverable state during volume deletion.") ctx := acctest.Context(t) - var cachedIscsiVolume storagegateway.CachediSCSIVolume + var cachedIscsiVolume awstypes.CachediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_cached_iscsi_volume.test" @@ -279,7 +281,7 @@ func TestAccStorageGatewayCachediSCSIVolume_sourceVolumeARN(t *testing.T) { func TestAccStorageGatewayCachediSCSIVolume_disappears(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.CachediSCSIVolume + var storedIscsiVolume awstypes.CachediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_cached_iscsi_volume.test" @@ -301,30 +303,30 @@ func TestAccStorageGatewayCachediSCSIVolume_disappears(t *testing.T) { }) } -func testAccCheckCachediSCSIVolumeExists(ctx context.Context, resourceName string, cachedIscsiVolume *storagegateway.CachediSCSIVolume) resource.TestCheckFunc { +func testAccCheckCachediSCSIVolumeExists(ctx context.Context, resourceName string, cachedIscsiVolume *awstypes.CachediSCSIVolume) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DescribeCachediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(rs.Primary.ID)}, + VolumeARNs: []string{rs.Primary.ID}, } - output, err := conn.DescribeCachediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeCachediSCSIVolumes(ctx, input) if err != nil { return fmt.Errorf("error reading Storage Gateway cached iSCSI volume: %s", err) } - if output == nil || len(output.CachediSCSIVolumes) == 0 || output.CachediSCSIVolumes[0] == nil || aws.StringValue(output.CachediSCSIVolumes[0].VolumeARN) != rs.Primary.ID { + if output == nil || len(output.CachediSCSIVolumes) == 0 || aws.ToString(output.CachediSCSIVolumes[0].VolumeARN) != rs.Primary.ID { return fmt.Errorf("Storage Gateway cached iSCSI volume %q not found", rs.Primary.ID) } - *cachedIscsiVolume = *output.CachediSCSIVolumes[0] + *cachedIscsiVolume = output.CachediSCSIVolumes[0] return nil } @@ -332,7 +334,7 @@ func testAccCheckCachediSCSIVolumeExists(ctx context.Context, resourceName strin func testAccCheckCachediSCSIVolumeDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_cached_iscsi_volume" { @@ -340,25 +342,25 @@ func testAccCheckCachediSCSIVolumeDestroy(ctx context.Context) resource.TestChec } input := &storagegateway.DescribeCachediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(rs.Primary.ID)}, + VolumeARNs: []string{rs.Primary.ID}, } - output, err := conn.DescribeCachediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeCachediSCSIVolumes(ctx, input) if err != nil { if tfstoragegateway.IsErrGatewayNotFound(err) { return nil } - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { return nil } - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { return nil } return err } - if output != nil && len(output.CachediSCSIVolumes) > 0 && output.CachediSCSIVolumes[0] != nil && aws.StringValue(output.CachediSCSIVolumes[0].VolumeARN) == rs.Primary.ID { + if output != nil && len(output.CachediSCSIVolumes) > 0 && aws.ToString(output.CachediSCSIVolumes[0].VolumeARN) == rs.Primary.ID { return fmt.Errorf("Storage Gateway cached iSCSI volume %q still exists", rs.Primary.ID) } } From 2773371e46314e15a35ecd060d2a2df42bda01f0 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:55:18 +0200 Subject: [PATCH 06/39] feat: migrate r/file_system_association to SDKv2 --- .../storagegateway/file_system_association.go | 35 +++++++++-------- .../file_system_association_test.go | 39 ++++++++++--------- 2 files changed, 39 insertions(+), 35 deletions(-) diff --git a/internal/service/storagegateway/file_system_association.go b/internal/service/storagegateway/file_system_association.go index 5d0bc55a30ba..c37d11f5bf79 100644 --- a/internal/service/storagegateway/file_system_association.go +++ b/internal/service/storagegateway/file_system_association.go @@ -8,8 +8,9 @@ import ( "log" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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/id" @@ -105,7 +106,7 @@ func resourceFileSystemAssociation() *schema.Resource { func resourceFileSystemAssociationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) gatewayARN := d.Get("gateway_arn").(string) input := &storagegateway.AssociateFileSystemInput{ @@ -125,13 +126,13 @@ func resourceFileSystemAssociationCreate(ctx context.Context, d *schema.Resource input.CacheAttributes = expandFileSystemAssociationCacheAttributes(v.([]interface{})) } - output, err := conn.AssociateFileSystemWithContext(ctx, input) + output, err := conn.AssociateFileSystem(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway (%s) File System Association: %s", gatewayARN, err) } - d.SetId(aws.StringValue(output.FileSystemAssociationARN)) + d.SetId(aws.ToString(output.FileSystemAssociationARN)) if _, err = waitFileSystemAssociationAvailable(ctx, conn, d.Id(), fileSystemAssociationCreateTimeout); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway File System Association (%s) create: %s", d.Id(), err) @@ -142,9 +143,9 @@ func resourceFileSystemAssociationCreate(ctx context.Context, d *schema.Resource func resourceFileSystemAssociationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - filesystem, err := FindFileSystemAssociationByARN(ctx, conn, d.Id()) + filesystem, err := findFileSystemAssociationByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway File System Association (%s) not found, removing from state", d.Id()) @@ -172,7 +173,7 @@ func resourceFileSystemAssociationRead(ctx context.Context, d *schema.ResourceDa func resourceFileSystemAssociationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) if d.HasChangesExcept(names.AttrTagsAll) { input := &storagegateway.UpdateFileSystemAssociationInput{ @@ -186,7 +187,7 @@ func resourceFileSystemAssociationUpdate(ctx context.Context, d *schema.Resource input.CacheAttributes = expandFileSystemAssociationCacheAttributes(v.([]interface{})) } - _, err := conn.UpdateFileSystemAssociationWithContext(ctx, input) + _, err := conn.UpdateFileSystemAssociation(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway File System Association (%s): %s", d.Id(), err) @@ -202,14 +203,14 @@ func resourceFileSystemAssociationUpdate(ctx context.Context, d *schema.Resource func resourceFileSystemAssociationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DisassociateFileSystemInput{ FileSystemAssociationARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting Storage Gateway File System Association: %s", input) - _, err := conn.DisassociateFileSystemWithContext(ctx, input) + log.Printf("[DEBUG] Deleting Storage Gateway File System Association: %#v", input) + _, err := conn.DisassociateFileSystem(ctx, input) if operationErrorCode(err) == operationErrCodeFileSystemAssociationNotFound { return diags @@ -226,27 +227,27 @@ func resourceFileSystemAssociationDelete(ctx context.Context, d *schema.Resource return diags } -func expandFileSystemAssociationCacheAttributes(l []interface{}) *storagegateway.CacheAttributes { +func expandFileSystemAssociationCacheAttributes(l []interface{}) *awstypes.CacheAttributes { if len(l) == 0 || l[0] == nil { return nil } m := l[0].(map[string]interface{}) - ca := &storagegateway.CacheAttributes{ - CacheStaleTimeoutInSeconds: aws.Int64(int64(m["cache_stale_timeout_in_seconds"].(int))), + ca := &awstypes.CacheAttributes{ + CacheStaleTimeoutInSeconds: aws.Int32(int32(m["cache_stale_timeout_in_seconds"].(int))), } return ca } -func flattenFileSystemAssociationCacheAttributes(ca *storagegateway.CacheAttributes) []interface{} { +func flattenFileSystemAssociationCacheAttributes(ca *awstypes.CacheAttributes) []interface{} { if ca == nil { return []interface{}{} } m := map[string]interface{}{ - "cache_stale_timeout_in_seconds": aws.Int64Value(ca.CacheStaleTimeoutInSeconds), + "cache_stale_timeout_in_seconds": aws.ToInt32(ca.CacheStaleTimeoutInSeconds), } return []interface{}{m} diff --git a/internal/service/storagegateway/file_system_association_test.go b/internal/service/storagegateway/file_system_association_test.go index 033c668830da..7c93b5857a7e 100644 --- a/internal/service/storagegateway/file_system_association_test.go +++ b/internal/service/storagegateway/file_system_association_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" @@ -23,7 +23,7 @@ import ( func TestAccStorageGatewayFileSystemAssociation_basic(t *testing.T) { ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" gatewayResourceName := "aws_storagegateway_gateway.test" @@ -32,7 +32,7 @@ func TestAccStorageGatewayFileSystemAssociation_basic(t *testing.T) { username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.StorageGateway) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -61,14 +61,14 @@ func TestAccStorageGatewayFileSystemAssociation_basic(t *testing.T) { func TestAccStorageGatewayFileSystemAssociation_tags(t *testing.T) { ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" domainName := acctest.RandomDomainName() username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.StorageGateway) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -113,14 +113,14 @@ func TestAccStorageGatewayFileSystemAssociation_tags(t *testing.T) { func TestAccStorageGatewayFileSystemAssociation_cacheAttributes(t *testing.T) { ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" domainName := acctest.RandomDomainName() username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.StorageGateway) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -153,14 +153,14 @@ func TestAccStorageGatewayFileSystemAssociation_cacheAttributes(t *testing.T) { func TestAccStorageGatewayFileSystemAssociation_auditDestination(t *testing.T) { ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" domainName := acctest.RandomDomainName() username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.StorageGateway) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -197,14 +197,14 @@ func TestAccStorageGatewayFileSystemAssociation_auditDestination(t *testing.T) { func TestAccStorageGatewayFileSystemAssociation_disappears(t *testing.T) { ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" domainName := acctest.RandomDomainName() username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.StorageGateway) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -223,14 +223,14 @@ func TestAccStorageGatewayFileSystemAssociation_disappears(t *testing.T) { func TestAccStorageGatewayFileSystemAssociation_Disappears_storageGateway(t *testing.T) { ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" domainName := acctest.RandomDomainName() username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.StorageGateway) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -251,14 +251,17 @@ func TestAccStorageGatewayFileSystemAssociation_Disappears_fsxFileSystem(t *test t.Skip("A bug in the service API has been reported. Deleting the FSx file system before the association prevents association from being deleted.") ctx := acctest.Context(t) - var fileSystemAssociation storagegateway.FileSystemAssociationInfo + var fileSystemAssociation awstypes.FileSystemAssociationInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_file_system_association.test" domainName := acctest.RandomDomainName() username := "Admin" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, storagegateway.EndpointsID) }, + PreCheck: func() { + acctest.PreCheck(ctx, t) + acctest.PreCheckPartitionHasService(t, names.StorageGateway) + }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckFileSystemAssociationDestroy(ctx), @@ -277,7 +280,7 @@ func TestAccStorageGatewayFileSystemAssociation_Disappears_fsxFileSystem(t *test func testAccCheckFileSystemAssociationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_file_system_association" { @@ -301,14 +304,14 @@ func testAccCheckFileSystemAssociationDestroy(ctx context.Context) resource.Test } } -func testAccCheckFileSystemAssociationExists(ctx context.Context, resourceName string, v *storagegateway.FileSystemAssociationInfo) resource.TestCheckFunc { +func testAccCheckFileSystemAssociationExists(ctx context.Context, resourceName string, v *awstypes.FileSystemAssociationInfo) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) output, err := tfstoragegateway.FindFileSystemAssociationByARN(ctx, conn, rs.Primary.ID) From 921fbf6cdc2d018b28668db479547ce365b3558a Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:55:30 +0200 Subject: [PATCH 07/39] feat: migrate r/gateway to SDKv2 --- internal/service/storagegateway/gateway.go | 160 +++++++++--------- .../service/storagegateway/gateway_test.go | 6 +- 2 files changed, 82 insertions(+), 84 deletions(-) diff --git a/internal/service/storagegateway/gateway.go b/internal/service/storagegateway/gateway.go index a356ed0f2880..35e90d634f22 100644 --- a/internal/service/storagegateway/gateway.go +++ b/internal/service/storagegateway/gateway.go @@ -13,8 +13,9 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" @@ -22,6 +23,7 @@ import ( "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/flex" @@ -250,10 +252,10 @@ func resourceGateway() *schema.Resource { ), }, "smb_security_strategy": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice(storagegateway.SMBSecurityStrategy_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.SMBSecurityStrategy](), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -276,7 +278,7 @@ func resourceGateway() *schema.Resource { func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) region := meta.(*conns.AWSClient).Region activationKey := d.Get("activation_key").(string) @@ -367,13 +369,13 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int input.TapeDriveType = aws.String(v.(string)) } - log.Printf("[DEBUG] Activating Storage Gateway Gateway: %s", input) - output, err := conn.ActivateGatewayWithContext(ctx, input) + log.Printf("[DEBUG] Activating Storage Gateway Gateway: %#v", input) + output, err := conn.ActivateGateway(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "activating Storage Gateway Gateway: %s", err) } - d.SetId(aws.StringValue(output.GatewayARN)) + d.SetId(aws.ToString(output.GatewayARN)) log.Printf("[INFO] Storage Gateway Gateway ID: %s", d.Id()) log.Printf("[DEBUG] Waiting for Storage Gateway Gateway (%s) to be connected", d.Id()) @@ -388,8 +390,8 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int CloudWatchLogGroupARN: aws.String(v.(string)), } - log.Printf("[DEBUG] Storage Gateway Gateway %q setting CloudWatch Log Group", input) - _, err := conn.UpdateGatewayInformationWithContext(ctx, input) + log.Printf("[DEBUG] Storage Gateway Gateway %#v setting CloudWatch Log Group", input) + _, err := conn.UpdateGatewayInformation(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "setting CloudWatch Log Group: %s", err) } @@ -400,7 +402,7 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int input.GatewayARN = aws.String(d.Id()) log.Printf("[DEBUG] Storage Gateway Gateway %q updating maintenance start time", d.Id()) - _, err := conn.UpdateMaintenanceStartTimeWithContext(ctx, input) + _, err := conn.UpdateMaintenanceStartTime(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating maintenance start time: %s", err) @@ -409,14 +411,14 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int if v, ok := d.GetOk("smb_active_directory_settings"); ok && len(v.([]interface{})) > 0 { input := expandGatewayDomain(v.([]interface{}), d.Id()) - log.Printf("[DEBUG] Storage Gateway Gateway %q joining Active Directory domain: %s", d.Id(), aws.StringValue(input.DomainName)) - _, err := conn.JoinDomainWithContext(ctx, input) + log.Printf("[DEBUG] Storage Gateway Gateway %q joining Active Directory domain: %s", d.Id(), aws.ToString(input.DomainName)) + _, err := conn.JoinDomain(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "joining Active Directory domain: %s", err) } log.Printf("[DEBUG] Waiting for Storage Gateway Gateway (%s) to be connected", d.Id()) if _, err = waitGatewayJoinDomainJoined(ctx, conn, d.Id()); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%q) to join domain (%s): %s", d.Id(), aws.StringValue(input.DomainName), err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%q) to join domain (%s): %s", d.Id(), aws.ToString(input.DomainName), err) } } @@ -427,7 +429,7 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int } log.Printf("[DEBUG] Storage Gateway Gateway %q setting SMB guest password", d.Id()) - _, err := conn.SetSMBGuestPasswordWithContext(ctx, input) + _, err := conn.SetSMBGuestPassword(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "setting SMB guest password: %s", err) } @@ -436,11 +438,11 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int if v, ok := d.GetOk("smb_security_strategy"); ok { input := &storagegateway.UpdateSMBSecurityStrategyInput{ GatewayARN: aws.String(d.Id()), - SMBSecurityStrategy: aws.String(v.(string)), + SMBSecurityStrategy: awstypes.SMBSecurityStrategy(v.(string)), } - log.Printf("[DEBUG] Storage Gateway Gateway %q setting SMB Security Strategy", input) - _, err := conn.UpdateSMBSecurityStrategyWithContext(ctx, input) + log.Printf("[DEBUG] Storage Gateway Gateway %#v setting SMB Security Strategy", input) + _, err := conn.UpdateSMBSecurityStrategy(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "setting SMB Security Strategy: %s", err) } @@ -452,8 +454,8 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int FileSharesVisible: aws.Bool(v.(bool)), } - log.Printf("[DEBUG] Storage Gateway Gateway %q setting SMB File Share Visibility", input) - _, err := conn.UpdateSMBFileShareVisibilityWithContext(ctx, input) + log.Printf("[DEBUG] Storage Gateway Gateway %#v setting SMB File Share Visibility", input) + _, err := conn.UpdateSMBFileShareVisibility(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) SMB file share visibility: %s", d.Id(), err) } @@ -475,7 +477,7 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int if bandwidthInput.AverageDownloadRateLimitInBitsPerSec != nil || bandwidthInput.AverageUploadRateLimitInBitsPerSec != nil { log.Printf("[DEBUG] Storage Gateway Gateway %q setting Bandwidth Rate Limit: %#v", d.Id(), bandwidthInput) - _, err := conn.UpdateBandwidthRateLimitWithContext(ctx, bandwidthInput) + _, err := conn.UpdateBandwidthRateLimit(ctx, bandwidthInput) if err != nil { return sdkdiag.AppendErrorf(diags, "setting Bandwidth Rate Limit: %s", err) } @@ -487,9 +489,9 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - output, err := FindGatewayByARN(ctx, conn, d.Id()) + output, err := findGatewayByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway Gateway (%s) not found, removing from state", d.Id()) @@ -507,10 +509,10 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter GatewayARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Reading Storage Gateway SMB Settings: %s", smbSettingsInput) - smbSettingsOutput, err := conn.DescribeSMBSettingsWithContext(ctx, smbSettingsInput) - if err != nil && !tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "This operation is not valid for the specified gateway") { - if IsErrGatewayNotFound(err) { + log.Printf("[DEBUG] Reading Storage Gateway SMB Settings: %#v", smbSettingsInput) + smbSettingsOutput, err := conn.DescribeSMBSettings(ctx, smbSettingsInput) + if err != nil && !errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway") { + if isErrGatewayNotFound(err) { log.Printf("[WARN] Storage Gateway Gateway %q not found - removing from state", d.Id()) d.SetId("") return diags @@ -540,14 +542,14 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter // Treat the entire nested argument as a whole, based on domain name // to simplify schema and difference logic - if smbSettingsOutput == nil || aws.StringValue(smbSettingsOutput.DomainName) == "" { + if smbSettingsOutput == nil || aws.ToString(smbSettingsOutput.DomainName) == "" { if err := d.Set("smb_active_directory_settings", []interface{}{}); err != nil { return sdkdiag.AppendErrorf(diags, "setting smb_active_directory_settings: %s", err) } } else { m := map[string]interface{}{ - names.AttrDomainName: aws.StringValue(smbSettingsOutput.DomainName), - "active_directory_status": aws.StringValue(smbSettingsOutput.ActiveDirectoryStatus), + names.AttrDomainName: aws.ToString(smbSettingsOutput.DomainName), + "active_directory_status": smbSettingsOutput.ActiveDirectoryStatus, // The Storage Gateway API currently provides no way to read these values // "password": ..., // "username": ..., @@ -581,7 +583,7 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter // as the API does clue us in whether or not its actually set at all, // which can be used to tell Terraform to show a difference in this case // as well as ensuring there is some sort of attribute value (unlike the others) - if smbSettingsOutput == nil || !aws.BoolValue(smbSettingsOutput.SMBGuestPasswordSet) { + if smbSettingsOutput == nil || !aws.ToBool(smbSettingsOutput.SMBGuestPasswordSet) { d.Set("smb_guest_password", "") } @@ -599,14 +601,14 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "setting gateway_network_interface: %s", err) } - switch aws.StringValue(output.GatewayType) { + switch aws.ToString(output.GatewayType) { case gatewayTypeCached, gatewayTypeStored, gatewayTypeVTL, gatewayTypeVTLSnow: - bandwidthOutput, err := conn.DescribeBandwidthRateLimitWithContext(ctx, &storagegateway.DescribeBandwidthRateLimitInput{ + bandwidthOutput, err := conn.DescribeBandwidthRateLimit(ctx, &storagegateway.DescribeBandwidthRateLimitInput{ GatewayARN: aws.String(d.Id()), }) - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "not supported") || - tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "not valid") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "not supported") || + errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "not valid") { err = nil } @@ -620,12 +622,12 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter } } - maintenanceStartTimeOutput, err := conn.DescribeMaintenanceStartTimeWithContext(ctx, &storagegateway.DescribeMaintenanceStartTimeInput{ + maintenanceStartTimeOutput, err := conn.DescribeMaintenanceStartTime(ctx, &storagegateway.DescribeMaintenanceStartTimeInput{ GatewayARN: aws.String(d.Id()), }) - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified operation is not supported") || - tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "This operation is not valid for the specified gateway") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified operation is not supported") || + errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway") { err = nil } @@ -646,7 +648,7 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) if d.HasChanges("gateway_name", "gateway_timezone", names.AttrCloudWatchLogGroupARN) { input := &storagegateway.UpdateGatewayInformationInput{ @@ -656,8 +658,8 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int GatewayTimezone: aws.String(d.Get("gateway_timezone").(string)), } - log.Printf("[DEBUG] Updating Storage Gateway Gateway: %s", input) - _, err := conn.UpdateGatewayInformationWithContext(ctx, input) + log.Printf("[DEBUG] Updating Storage Gateway Gateway: %#v", input) + _, err := conn.UpdateGatewayInformation(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s): %s", d.Id(), err) @@ -669,8 +671,8 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int input := expandUpdateMaintenanceStartTimeInput(v.([]interface{})[0].(map[string]interface{})) input.GatewayARN = aws.String(d.Id()) - log.Printf("[DEBUG] Updating Storage Gateway maintenance start time: %s", input) - _, err := conn.UpdateMaintenanceStartTimeWithContext(ctx, input) + log.Printf("[DEBUG] Updating Storage Gateway maintenance start time: %#v", input) + _, err := conn.UpdateMaintenanceStartTime(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) maintenance start time: %s", d.Id(), err) @@ -680,9 +682,9 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int if d.HasChange("smb_active_directory_settings") { input := expandGatewayDomain(d.Get("smb_active_directory_settings").([]interface{}), d.Id()) - domainName := aws.StringValue(input.DomainName) + domainName := aws.ToString(input.DomainName) - _, err := conn.JoinDomainWithContext(ctx, input) + _, err := conn.JoinDomain(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "joining Storage Gateway Gateway (%s) to Active Directory domain (%s): %s", d.Id(), domainName, err) @@ -699,7 +701,7 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int Password: aws.String(d.Get("smb_guest_password").(string)), } - _, err := conn.SetSMBGuestPasswordWithContext(ctx, input) + _, err := conn.SetSMBGuestPassword(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) SMB guest password: %s", d.Id(), err) @@ -709,11 +711,11 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int if d.HasChange("smb_security_strategy") { input := &storagegateway.UpdateSMBSecurityStrategyInput{ GatewayARN: aws.String(d.Id()), - SMBSecurityStrategy: aws.String(d.Get("smb_security_strategy").(string)), + SMBSecurityStrategy: awstypes.SMBSecurityStrategy(d.Get("smb_security_strategy").(string)), } - log.Printf("[DEBUG] Updating Storage Gateway SMB security strategy: %s", input) - _, err := conn.UpdateSMBSecurityStrategyWithContext(ctx, input) + log.Printf("[DEBUG] Updating Storage Gateway SMB security strategy: %#v", input) + _, err := conn.UpdateSMBSecurityStrategy(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) SMB security strategy: %s", d.Id(), err) @@ -726,8 +728,8 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int GatewayARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Updating Storage Gateway SMB file share visibility: %s", input) - _, err := conn.UpdateSMBFileShareVisibilityWithContext(ctx, input) + log.Printf("[DEBUG] Updating Storage Gateway SMB file share visibility: %#v", input) + _, err := conn.UpdateSMBFileShareVisibility(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) SMB file share visibility: %s", d.Id(), err) @@ -765,8 +767,8 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int } if needsUpdate { - log.Printf("[DEBUG] Updating Storage Gateway bandwidth rate limit: %s", updateInput) - _, err := conn.UpdateBandwidthRateLimitWithContext(ctx, updateInput) + log.Printf("[DEBUG] Updating Storage Gateway bandwidth rate limit: %#v", updateInput) + _, err := conn.UpdateBandwidthRateLimit(ctx, updateInput) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) bandwidth rate limit: %s", d.Id(), err) @@ -774,8 +776,8 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int } if needsDelete { - log.Printf("[DEBUG] Deleting Storage Gateway bandwidth rate limit: %s", deleteInput) - _, err := conn.DeleteBandwidthRateLimitWithContext(ctx, deleteInput) + log.Printf("[DEBUG] Deleting Storage Gateway bandwidth rate limit: %#v", deleteInput) + _, err := conn.DeleteBandwidthRateLimit(ctx, deleteInput) if err != nil { return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Gateway (%s) bandwidth rate limit: %s", d.Id(), err) @@ -788,14 +790,14 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int func resourceGatewayDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) log.Printf("[DEBUG] Deleting Storage Gateway Gateway: %s", d.Id()) - _, err := conn.DeleteGatewayWithContext(ctx, &storagegateway.DeleteGatewayInput{ + _, err := conn.DeleteGateway(ctx, &storagegateway.DeleteGatewayInput{ GatewayARN: aws.String(d.Id()), }) - if operationErrorCode(err) == operationErrCodeGatewayNotFound || tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeGatewayNotFound) { + if operationErrorCode(err) == operationErrCodeGatewayNotFound || tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { return diags } @@ -821,7 +823,7 @@ func expandGatewayDomain(l []interface{}, gatewayArn string) *storagegateway.Joi GatewayARN: aws.String(gatewayArn), Password: aws.String(tfMap[names.AttrPassword].(string)), UserName: aws.String(tfMap[names.AttrUsername].(string)), - TimeoutInSeconds: aws.Int64(int64(tfMap["timeout_in_seconds"].(int))), + TimeoutInSeconds: aws.Int32(int32(tfMap["timeout_in_seconds"].(int))), } if v, ok := tfMap["organizational_unit"].(string); ok && v != "" { @@ -829,13 +831,13 @@ func expandGatewayDomain(l []interface{}, gatewayArn string) *storagegateway.Joi } if v, ok := tfMap["domain_controllers"].(*schema.Set); ok && v.Len() > 0 { - domain.DomainControllers = flex.ExpandStringSet(v) + domain.DomainControllers = flex.ExpandStringValueSet(v) } return domain } -func flattenGatewayNetworkInterfaces(nis []*storagegateway.NetworkInterface) []interface{} { +func flattenGatewayNetworkInterfaces(nis []awstypes.NetworkInterface) []interface{} { if len(nis) == 0 { return nil } @@ -843,12 +845,8 @@ func flattenGatewayNetworkInterfaces(nis []*storagegateway.NetworkInterface) []i var tfList []interface{} for _, ni := range nis { - if ni == nil { - continue - } - tfMap := map[string]interface{}{ - "ipv4_address": aws.StringValue(ni.Ipv4Address), + "ipv4_address": aws.ToString(ni.Ipv4Address), } tfList = append(tfList, tfMap) @@ -864,20 +862,20 @@ func expandUpdateMaintenanceStartTimeInput(tfMap map[string]interface{}) *storag apiObject := &storagegateway.UpdateMaintenanceStartTimeInput{} - if v, null, _ := nullable.Int(tfMap["day_of_month"].(string)).ValueInt64(); !null && v > 0 { - apiObject.DayOfMonth = aws.Int64(v) + if v, null, _ := nullable.Int(tfMap["day_of_month"].(string)).ValueInt32(); !null && v > 0 { + apiObject.DayOfMonth = aws.Int32(v) } - if v, null, _ := nullable.Int(tfMap["day_of_week"].(string)).ValueInt64(); !null { - apiObject.DayOfWeek = aws.Int64(v) + if v, null, _ := nullable.Int(tfMap["day_of_week"].(string)).ValueInt32(); !null { + apiObject.DayOfWeek = aws.Int32(v) } if v, ok := tfMap["hour_of_day"].(int); ok { - apiObject.HourOfDay = aws.Int64(int64(v)) + apiObject.HourOfDay = aws.Int32(int32(v)) } if v, ok := tfMap["minute_of_hour"].(int); ok { - apiObject.MinuteOfHour = aws.Int64(int64(v)) + apiObject.MinuteOfHour = aws.Int32(int32(v)) } return apiObject @@ -891,30 +889,30 @@ func flattenDescribeMaintenanceStartTimeOutput(apiObject *storagegateway.Describ tfMap := map[string]interface{}{} if v := apiObject.DayOfMonth; v != nil { - tfMap["day_of_month"] = strconv.FormatInt(aws.Int64Value(v), 10) + tfMap["day_of_month"] = strconv.FormatInt(int64(aws.ToInt32(v)), 10) } if v := apiObject.DayOfWeek; v != nil { - tfMap["day_of_week"] = strconv.FormatInt(aws.Int64Value(v), 10) + tfMap["day_of_week"] = strconv.FormatInt(int64(aws.ToInt32(v)), 10) } if v := apiObject.HourOfDay; v != nil { - tfMap["hour_of_day"] = aws.Int64Value(v) + tfMap["hour_of_day"] = aws.ToInt32(v) } if v := apiObject.MinuteOfHour; v != nil { - tfMap["minute_of_hour"] = aws.Int64Value(v) + tfMap["minute_of_hour"] = aws.ToInt32(v) } return tfMap } // The API returns multiple responses for a missing gateway -func IsErrGatewayNotFound(err error) bool { - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified gateway was not found.") { +func isErrGatewayNotFound(err error) bool { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found.") { return true } - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeGatewayNotFound) { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { return true } return false diff --git a/internal/service/storagegateway/gateway_test.go b/internal/service/storagegateway/gateway_test.go index 3d7ab1ce7fc2..89d0426b8361 100644 --- a/internal/service/storagegateway/gateway_test.go +++ b/internal/service/storagegateway/gateway_test.go @@ -10,7 +10,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -874,7 +874,7 @@ func TestAccStorageGatewayGateway_maintenanceStartTime(t *testing.T) { func testAccCheckGatewayDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_gateway" { @@ -905,7 +905,7 @@ func testAccCheckGatewayExists(ctx context.Context, resourceName string, gateway return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) output, err := tfstoragegateway.FindGatewayByARN(ctx, conn, rs.Primary.ID) From 90183a0384d38621f82c2248c0f05a92629fa744 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:55:42 +0200 Subject: [PATCH 08/39] feat: migrate r/nfs_file_share to SDKv2 --- .../service/storagegateway/nfs_file_share.go | 70 ++++++++++--------- .../storagegateway/nfs_file_share_test.go | 52 +++++++------- 2 files changed, 62 insertions(+), 60 deletions(-) diff --git a/internal/service/storagegateway/nfs_file_share.go b/internal/service/storagegateway/nfs_file_share.go index 95372fe68130..3acce16797d1 100644 --- a/internal/service/storagegateway/nfs_file_share.go +++ b/internal/service/storagegateway/nfs_file_share.go @@ -10,13 +10,15 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -173,10 +175,10 @@ func resourceNFSFileShare() *schema.Resource { ), }, "object_acl": { - Type: schema.TypeString, - Optional: true, - Default: storagegateway.ObjectACLPrivate, - ValidateFunc: validation.StringInSlice(storagegateway.ObjectACL_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.ObjectACLPrivate, + ValidateDiagFunc: enum.Validate[awstypes.ObjectACL](), }, names.AttrPath: { Type: schema.TypeString, @@ -219,7 +221,7 @@ func resourceNFSFileShare() *schema.Resource { func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) fileShareDefaults, err := expandNFSFileShareDefaults(d.Get("nfs_file_share_defaults").([]interface{})) @@ -228,7 +230,7 @@ func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, met } input := &storagegateway.CreateNFSFileShareInput{ - ClientList: flex.ExpandStringSet(d.Get("client_list").(*schema.Set)), + ClientList: flex.ExpandStringValueSet(d.Get("client_list").(*schema.Set)), ClientToken: aws.String(id.UniqueId()), DefaultStorageClass: aws.String(d.Get("default_storage_class").(string)), GatewayARN: aws.String(d.Get("gateway_arn").(string)), @@ -236,7 +238,7 @@ func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, met KMSEncrypted: aws.Bool(d.Get("kms_encrypted").(bool)), LocationARN: aws.String(d.Get("location_arn").(string)), NFSFileShareDefaults: fileShareDefaults, - ObjectACL: aws.String(d.Get("object_acl").(string)), + ObjectACL: awstypes.ObjectACL(d.Get("object_acl").(string)), ReadOnly: aws.Bool(d.Get("read_only").(bool)), RequesterPays: aws.Bool(d.Get("requester_pays").(bool)), Role: aws.String(d.Get(names.AttrRoleARN).(string)), @@ -272,14 +274,14 @@ func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, met input.VPCEndpointDNSName = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating Storage Gateway NFS File Share: %s", input) - output, err := conn.CreateNFSFileShareWithContext(ctx, input) + log.Printf("[DEBUG] Creating Storage Gateway NFS File Share: %#v", input) + output, err := conn.CreateNFSFileShare(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway NFS File Share: %s", err) } - d.SetId(aws.StringValue(output.FileShareARN)) + d.SetId(aws.ToString(output.FileShareARN)) if _, err = waitNFSFileShareCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway NFS File Share (%s) create: %s", d.Id(), err) @@ -290,9 +292,9 @@ func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, met func resourceNFSFileShareRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - fileshare, err := FindNFSFileShareByARN(ctx, conn, d.Id()) + fileshare, err := findNFSFileShareByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway NFS File Share (%s) not found, removing from state", d.Id()) @@ -310,7 +312,7 @@ func resourceNFSFileShareRead(ctx context.Context, d *schema.ResourceData, meta if err := d.Set("cache_attributes", flattenNFSFileShareCacheAttributes(fileshare.CacheAttributes)); err != nil { return sdkdiag.AppendErrorf(diags, "setting cache_attributes: %s", err) } - if err := d.Set("client_list", flex.FlattenStringSet(fileshare.ClientList)); err != nil { + if err := d.Set("client_list", flex.FlattenStringValueSet(fileshare.ClientList)); err != nil { return sdkdiag.AppendErrorf(diags, "setting client_list: %s", err) } d.Set("default_storage_class", fileshare.DefaultStorageClass) @@ -340,7 +342,7 @@ func resourceNFSFileShareRead(ctx context.Context, d *schema.ResourceData, meta func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) { fileShareDefaults, err := expandNFSFileShareDefaults(d.Get("nfs_file_share_defaults").([]interface{})) @@ -350,13 +352,13 @@ func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, met } input := &storagegateway.UpdateNFSFileShareInput{ - ClientList: flex.ExpandStringSet(d.Get("client_list").(*schema.Set)), + ClientList: flex.ExpandStringValueSet(d.Get("client_list").(*schema.Set)), DefaultStorageClass: aws.String(d.Get("default_storage_class").(string)), FileShareARN: aws.String(d.Id()), GuessMIMETypeEnabled: aws.Bool(d.Get("guess_mime_type_enabled").(bool)), KMSEncrypted: aws.Bool(d.Get("kms_encrypted").(bool)), NFSFileShareDefaults: fileShareDefaults, - ObjectACL: aws.String(d.Get("object_acl").(string)), + ObjectACL: awstypes.ObjectACL(d.Get("object_acl").(string)), ReadOnly: aws.Bool(d.Get("read_only").(bool)), RequesterPays: aws.Bool(d.Get("requester_pays").(bool)), Squash: aws.String(d.Get("squash").(string)), @@ -382,8 +384,8 @@ func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, met input.NotificationPolicy = aws.String(v.(string)) } - log.Printf("[DEBUG] Updating Storage Gateway NFS File Share: %s", input) - _, err = conn.UpdateNFSFileShareWithContext(ctx, input) + log.Printf("[DEBUG] Updating Storage Gateway NFS File Share: %#v", input) + _, err = conn.UpdateNFSFileShare(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway NFS File Share (%s): %s", d.Id(), err) @@ -399,10 +401,10 @@ func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, met func resourceNFSFileShareDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) log.Printf("[DEBUG] Deleting Storage Gateway NFS File Share: %s", d.Id()) - _, err := conn.DeleteFileShareWithContext(ctx, &storagegateway.DeleteFileShareInput{ + _, err := conn.DeleteFileShare(ctx, &storagegateway.DeleteFileShareInput{ FileShareARN: aws.String(d.Id()), }) @@ -421,7 +423,7 @@ func resourceNFSFileShareDelete(ctx context.Context, d *schema.ResourceData, met return diags } -func expandNFSFileShareDefaults(l []interface{}) (*storagegateway.NFSFileShareDefaults, error) { +func expandNFSFileShareDefaults(l []interface{}) (*awstypes.NFSFileShareDefaults, error) { if len(l) == 0 || l[0] == nil { return nil, nil } @@ -438,7 +440,7 @@ func expandNFSFileShareDefaults(l []interface{}) (*storagegateway.NFSFileShareDe return nil, err } - nfsFileShareDefaults := &storagegateway.NFSFileShareDefaults{ + nfsFileShareDefaults := &awstypes.NFSFileShareDefaults{ DirectoryMode: aws.String(m["directory_mode"].(string)), FileMode: aws.String(m["file_mode"].(string)), GroupId: aws.Int64(groupID), @@ -448,42 +450,42 @@ func expandNFSFileShareDefaults(l []interface{}) (*storagegateway.NFSFileShareDe return nfsFileShareDefaults, nil } -func flattenNFSFileShareDefaults(nfsFileShareDefaults *storagegateway.NFSFileShareDefaults) []interface{} { +func flattenNFSFileShareDefaults(nfsFileShareDefaults *awstypes.NFSFileShareDefaults) []interface{} { if nfsFileShareDefaults == nil { return []interface{}{} } m := map[string]interface{}{ - "directory_mode": aws.StringValue(nfsFileShareDefaults.DirectoryMode), - "file_mode": aws.StringValue(nfsFileShareDefaults.FileMode), - "group_id": strconv.Itoa(int(aws.Int64Value(nfsFileShareDefaults.GroupId))), - names.AttrOwnerID: strconv.Itoa(int(aws.Int64Value(nfsFileShareDefaults.OwnerId))), + "directory_mode": aws.ToString(nfsFileShareDefaults.DirectoryMode), + "file_mode": aws.ToString(nfsFileShareDefaults.FileMode), + "group_id": strconv.Itoa(int(aws.ToInt64(nfsFileShareDefaults.GroupId))), + names.AttrOwnerID: strconv.Itoa(int(aws.ToInt64(nfsFileShareDefaults.OwnerId))), } return []interface{}{m} } -func expandNFSFileShareCacheAttributes(l []interface{}) *storagegateway.CacheAttributes { +func expandNFSFileShareCacheAttributes(l []interface{}) *awstypes.CacheAttributes { if len(l) == 0 || l[0] == nil { return nil } m := l[0].(map[string]interface{}) - ca := &storagegateway.CacheAttributes{ - CacheStaleTimeoutInSeconds: aws.Int64(int64(m["cache_stale_timeout_in_seconds"].(int))), + ca := &awstypes.CacheAttributes{ + CacheStaleTimeoutInSeconds: aws.Int32(int32(m["cache_stale_timeout_in_seconds"].(int))), } return ca } -func flattenNFSFileShareCacheAttributes(ca *storagegateway.CacheAttributes) []interface{} { +func flattenNFSFileShareCacheAttributes(ca *awstypes.CacheAttributes) []interface{} { if ca == nil { return []interface{}{} } m := map[string]interface{}{ - "cache_stale_timeout_in_seconds": aws.Int64Value(ca.CacheStaleTimeoutInSeconds), + "cache_stale_timeout_in_seconds": aws.ToInt32(ca.CacheStaleTimeoutInSeconds), } return []interface{}{m} diff --git a/internal/service/storagegateway/nfs_file_share_test.go b/internal/service/storagegateway/nfs_file_share_test.go index b3b865d22c38..219824cc676a 100644 --- a/internal/service/storagegateway/nfs_file_share_test.go +++ b/internal/service/storagegateway/nfs_file_share_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" @@ -22,7 +22,7 @@ import ( func TestAccStorageGatewayNFSFileShare_basic(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" gatewayResourceName := "aws_storagegateway_gateway.test" @@ -54,7 +54,7 @@ func TestAccStorageGatewayNFSFileShare_basic(t *testing.T) { resource.TestCheckResourceAttrPair(resourceName, "location_arn", bucketResourceName, names.AttrARN), resource.TestCheckResourceAttr(resourceName, "nfs_file_share_defaults.#", acctest.Ct0), resource.TestCheckResourceAttr(resourceName, "notification_policy", "{}"), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPrivate), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPrivate)), resource.TestMatchResourceAttr(resourceName, names.AttrPath, regexache.MustCompile(`^/.+`)), resource.TestCheckResourceAttr(resourceName, "read_only", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, "requester_pays", acctest.CtFalse), @@ -75,7 +75,7 @@ func TestAccStorageGatewayNFSFileShare_basic(t *testing.T) { func TestAccStorageGatewayNFSFileShare_audit(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" logResourceName := "aws_cloudwatch_log_group.test" @@ -112,7 +112,7 @@ func TestAccStorageGatewayNFSFileShare_audit(t *testing.T) { func TestAccStorageGatewayNFSFileShare_tags(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -161,7 +161,7 @@ func TestAccStorageGatewayNFSFileShare_tags(t *testing.T) { func TestAccStorageGatewayNFSFileShare_fileShareName(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -196,7 +196,7 @@ func TestAccStorageGatewayNFSFileShare_fileShareName(t *testing.T) { func TestAccStorageGatewayNFSFileShare_clientList(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -242,7 +242,7 @@ func TestAccStorageGatewayNFSFileShare_clientList(t *testing.T) { func TestAccStorageGatewayNFSFileShare_defaultStorageClass(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -277,7 +277,7 @@ func TestAccStorageGatewayNFSFileShare_defaultStorageClass(t *testing.T) { func TestAccStorageGatewayNFSFileShare_guessMIMETypeEnabled(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -312,7 +312,7 @@ func TestAccStorageGatewayNFSFileShare_guessMIMETypeEnabled(t *testing.T) { func TestAccStorageGatewayNFSFileShare_kmsEncrypted(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -344,7 +344,7 @@ func TestAccStorageGatewayNFSFileShare_kmsEncrypted(t *testing.T) { func TestAccStorageGatewayNFSFileShare_kmsKeyARN(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" keyName := "aws_kms_key.test.0" @@ -390,7 +390,7 @@ func TestAccStorageGatewayNFSFileShare_kmsKeyARN(t *testing.T) { func TestAccStorageGatewayNFSFileShare_nFSFileShareDefaults(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -433,7 +433,7 @@ func TestAccStorageGatewayNFSFileShare_nFSFileShareDefaults(t *testing.T) { func TestAccStorageGatewayNFSFileShare_objectACL(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -444,17 +444,17 @@ func TestAccStorageGatewayNFSFileShare_objectACL(t *testing.T) { CheckDestroy: testAccCheckNFSFileShareDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccNFSFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicRead), + Config: testAccNFSFileShareConfig_objectACL(rName, string(awstypes.ObjectACLPublicRead)), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(ctx, resourceName, &nfsFileShare), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicRead), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPublicRead)), ), }, { - Config: testAccNFSFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicReadWrite), + Config: testAccNFSFileShareConfig_objectACL(rName, string(awstypes.ObjectACLPublicReadWrite)), Check: resource.ComposeTestCheckFunc( testAccCheckNFSFileShareExists(ctx, resourceName, &nfsFileShare), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicReadWrite), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPublicReadWrite)), ), }, { @@ -468,7 +468,7 @@ func TestAccStorageGatewayNFSFileShare_objectACL(t *testing.T) { func TestAccStorageGatewayNFSFileShare_readOnly(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -503,7 +503,7 @@ func TestAccStorageGatewayNFSFileShare_readOnly(t *testing.T) { func TestAccStorageGatewayNFSFileShare_requesterPays(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -538,7 +538,7 @@ func TestAccStorageGatewayNFSFileShare_requesterPays(t *testing.T) { func TestAccStorageGatewayNFSFileShare_squash(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -573,7 +573,7 @@ func TestAccStorageGatewayNFSFileShare_squash(t *testing.T) { func TestAccStorageGatewayNFSFileShare_notificationPolicy(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -615,7 +615,7 @@ func TestAccStorageGatewayNFSFileShare_notificationPolicy(t *testing.T) { func TestAccStorageGatewayNFSFileShare_cacheAttributes(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -660,7 +660,7 @@ func TestAccStorageGatewayNFSFileShare_cacheAttributes(t *testing.T) { func TestAccStorageGatewayNFSFileShare_disappears(t *testing.T) { ctx := acctest.Context(t) - var nfsFileShare storagegateway.NFSFileShareInfo + var nfsFileShare awstypes.NFSFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_nfs_file_share.test" @@ -685,7 +685,7 @@ func TestAccStorageGatewayNFSFileShare_disappears(t *testing.T) { func testAccCheckNFSFileShareDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_nfs_file_share" { @@ -709,14 +709,14 @@ func testAccCheckNFSFileShareDestroy(ctx context.Context) resource.TestCheckFunc } } -func testAccCheckNFSFileShareExists(ctx context.Context, resourceName string, nfsFileShare *storagegateway.NFSFileShareInfo) resource.TestCheckFunc { +func testAccCheckNFSFileShareExists(ctx context.Context, resourceName string, nfsFileShare *awstypes.NFSFileShareInfo) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) output, err := tfstoragegateway.FindNFSFileShareByARN(ctx, conn, rs.Primary.ID) From 443784cd83d742e5eb3527ebed5b002c3505f879 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:55:53 +0200 Subject: [PATCH 09/39] feat: migrate r/smb_file_share to SDKv2 --- .../service/storagegateway/smb_file_share.go | 82 ++++++++++--------- .../storagegateway/smb_file_share_test.go | 64 +++++++-------- 2 files changed, 74 insertions(+), 72 deletions(-) diff --git a/internal/service/storagegateway/smb_file_share.go b/internal/service/storagegateway/smb_file_share.go index 71493bdd2206..e685d822ecf8 100644 --- a/internal/service/storagegateway/smb_file_share.go +++ b/internal/service/storagegateway/smb_file_share.go @@ -9,13 +9,15 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -91,10 +93,10 @@ func resourceSMBFileShare() *schema.Resource { }, }, "case_sensitivity": { - Type: schema.TypeString, - Optional: true, - Default: storagegateway.CaseSensitivityClientSpecified, - ValidateFunc: validation.StringInSlice(storagegateway.CaseSensitivity_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.CaseSensitivityClientSpecified, + ValidateDiagFunc: enum.Validate[awstypes.CaseSensitivity](), }, "default_storage_class": { Type: schema.TypeString, @@ -146,10 +148,10 @@ func resourceSMBFileShare() *schema.Resource { ValidateFunc: verify.ValidARN, }, "object_acl": { - Type: schema.TypeString, - Optional: true, - Default: storagegateway.ObjectACLPrivate, - ValidateFunc: validation.StringInSlice(storagegateway.ObjectACL_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.ObjectACLPrivate, + ValidateDiagFunc: enum.Validate[awstypes.ObjectACL](), }, "oplocks_enabled": { Type: schema.TypeBool, @@ -210,7 +212,7 @@ func resourceSMBFileShare() *schema.Resource { func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.CreateSMBFileShareInput{ AccessBasedEnumeration: aws.Bool(d.Get("access_based_enumeration").(bool)), @@ -227,7 +229,7 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("admin_user_list"); ok && v.(*schema.Set).Len() > 0 { - input.AdminUserList = flex.ExpandStringSet(v.(*schema.Set)) + input.AdminUserList = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("audit_destination_arn"); ok { @@ -247,7 +249,7 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("case_sensitivity"); ok { - input.CaseSensitivity = aws.String(v.(string)) + input.CaseSensitivity = awstypes.CaseSensitivity(v.(string)) } if v, ok := d.GetOk("default_storage_class"); ok { @@ -259,7 +261,7 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("invalid_user_list"); ok && v.(*schema.Set).Len() > 0 { - input.InvalidUserList = flex.ExpandStringSet(v.(*schema.Set)) + input.InvalidUserList = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk(names.AttrKMSKeyARN); ok { @@ -271,7 +273,7 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("object_acl"); ok { - input.ObjectACL = aws.String(v.(string)) + input.ObjectACL = awstypes.ObjectACL(v.(string)) } if v, ok := d.GetOk("oplocks_enabled"); ok { @@ -279,21 +281,21 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("valid_user_list"); ok && v.(*schema.Set).Len() > 0 { - input.ValidUserList = flex.ExpandStringSet(v.(*schema.Set)) + input.ValidUserList = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("vpc_endpoint_dns_name"); ok { input.VPCEndpointDNSName = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating Storage Gateway SMB File Share: %s", input) - output, err := conn.CreateSMBFileShareWithContext(ctx, input) + log.Printf("[DEBUG] Creating Storage Gateway SMB File Share: %#v", input) + output, err := conn.CreateSMBFileShare(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway SMB File Share: %s", err) } - d.SetId(aws.StringValue(output.FileShareARN)) + d.SetId(aws.ToString(output.FileShareARN)) if _, err = waitSMBFileShareCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) to create: %s", d.Id(), err) @@ -304,9 +306,9 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - fileshare, err := FindSMBFileShareByARN(ctx, conn, d.Id()) + fileshare, err := findSMBFileShareByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway SMB File Share (%s) not found, removing from state", d.Id()) @@ -319,7 +321,7 @@ func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta } d.Set("access_based_enumeration", fileshare.AccessBasedEnumeration) - d.Set("admin_user_list", aws.StringValueSlice(fileshare.AdminUserList)) + d.Set("admin_user_list", aws.StringSlice(fileshare.AdminUserList)) d.Set(names.AttrARN, fileshare.FileShareARN) d.Set("audit_destination_arn", fileshare.AuditDestinationARN) d.Set("authentication", fileshare.Authentication) @@ -339,7 +341,7 @@ func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta d.Set("file_share_name", fileshare.FileShareName) d.Set("gateway_arn", fileshare.GatewayARN) d.Set("guess_mime_type_enabled", fileshare.GuessMIMETypeEnabled) - d.Set("invalid_user_list", aws.StringValueSlice(fileshare.InvalidUserList)) + d.Set("invalid_user_list", aws.StringSlice(fileshare.InvalidUserList)) d.Set("kms_encrypted", fileshare.KMSEncrypted) d.Set(names.AttrKMSKeyARN, fileshare.KMSKey) d.Set("location_arn", fileshare.LocationARN) @@ -351,7 +353,7 @@ func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta d.Set("requester_pays", fileshare.RequesterPays) d.Set(names.AttrRoleARN, fileshare.Role) d.Set("smb_acl_enabled", fileshare.SMBACLEnabled) - d.Set("valid_user_list", aws.StringValueSlice(fileshare.ValidUserList)) + d.Set("valid_user_list", aws.StringSlice(fileshare.ValidUserList)) d.Set("vpc_endpoint_dns_name", fileshare.VPCEndpointDNSName) setTagsOut(ctx, fileshare.Tags) @@ -361,7 +363,7 @@ func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) { input := &storagegateway.UpdateSMBFileShareInput{ @@ -375,7 +377,7 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met } if d.HasChange("admin_user_list") { - input.AdminUserList = flex.ExpandStringSet(d.Get("admin_user_list").(*schema.Set)) + input.AdminUserList = flex.ExpandStringValueSet(d.Get("admin_user_list").(*schema.Set)) } if d.HasChange("audit_destination_arn") { @@ -386,12 +388,12 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met if v, ok := d.GetOk("cache_attributes"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { input.CacheAttributes = expandCacheAttributes(v.([]interface{})[0].(map[string]interface{})) } else { - input.CacheAttributes = &storagegateway.CacheAttributes{} + input.CacheAttributes = &awstypes.CacheAttributes{} } } if d.HasChange("case_sensitivity") { - input.CaseSensitivity = aws.String(d.Get("case_sensitivity").(string)) + input.CaseSensitivity = awstypes.CaseSensitivity(d.Get("case_sensitivity").(string)) } if d.HasChange("default_storage_class") { @@ -403,7 +405,7 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met } if d.HasChange("invalid_user_list") { - input.InvalidUserList = flex.ExpandStringSet(d.Get("invalid_user_list").(*schema.Set)) + input.InvalidUserList = flex.ExpandStringValueSet(d.Get("invalid_user_list").(*schema.Set)) } // This value can only be set when KMSEncrypted is true. @@ -418,7 +420,7 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met } if d.HasChange("object_acl") { - input.ObjectACL = aws.String(d.Get("object_acl").(string)) + input.ObjectACL = awstypes.ObjectACL(d.Get("object_acl").(string)) } if d.HasChange("oplocks_enabled") { @@ -426,11 +428,11 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met } if d.HasChange("valid_user_list") { - input.ValidUserList = flex.ExpandStringSet(d.Get("valid_user_list").(*schema.Set)) + input.ValidUserList = flex.ExpandStringValueSet(d.Get("valid_user_list").(*schema.Set)) } - log.Printf("[DEBUG] Updating Storage Gateway SMB File Share: %s", input) - _, err := conn.UpdateSMBFileShareWithContext(ctx, input) + log.Printf("[DEBUG] Updating Storage Gateway SMB File Share: %#v", input) + _, err := conn.UpdateSMBFileShare(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway SMB File Share (%s): %s", d.Id(), err) @@ -446,10 +448,10 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met func resourceSMBFileShareDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) log.Printf("[DEBUG] Deleting Storage Gateway SMB File Share: %s", d.Id()) - _, err := conn.DeleteFileShareWithContext(ctx, &storagegateway.DeleteFileShareInput{ + _, err := conn.DeleteFileShare(ctx, &storagegateway.DeleteFileShareInput{ FileShareARN: aws.String(d.Id()), }) @@ -468,21 +470,21 @@ func resourceSMBFileShareDelete(ctx context.Context, d *schema.ResourceData, met return diags } -func expandCacheAttributes(tfMap map[string]interface{}) *storagegateway.CacheAttributes { +func expandCacheAttributes(tfMap map[string]interface{}) *awstypes.CacheAttributes { if tfMap == nil { return nil } - apiObject := &storagegateway.CacheAttributes{} + apiObject := &awstypes.CacheAttributes{} if v, ok := tfMap["cache_stale_timeout_in_seconds"].(int); ok && v != 0 { - apiObject.CacheStaleTimeoutInSeconds = aws.Int64(int64(v)) + apiObject.CacheStaleTimeoutInSeconds = aws.Int32(int32(v)) } return apiObject } -func flattenCacheAttributes(apiObject *storagegateway.CacheAttributes) map[string]interface{} { +func flattenCacheAttributes(apiObject *awstypes.CacheAttributes) map[string]interface{} { if apiObject == nil { return nil } @@ -490,7 +492,7 @@ func flattenCacheAttributes(apiObject *storagegateway.CacheAttributes) map[strin tfMap := map[string]interface{}{} if v := apiObject.CacheStaleTimeoutInSeconds; v != nil { - tfMap["cache_stale_timeout_in_seconds"] = aws.Int64Value(v) + tfMap["cache_stale_timeout_in_seconds"] = aws.ToInt32(v) } return tfMap diff --git a/internal/service/storagegateway/smb_file_share_test.go b/internal/service/storagegateway/smb_file_share_test.go index d8754b9b6b93..fb40c811ca6e 100644 --- a/internal/service/storagegateway/smb_file_share_test.go +++ b/internal/service/storagegateway/smb_file_share_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" @@ -22,7 +22,7 @@ import ( func TestAccStorageGatewaySMBFileShare_Authentication_activeDirectory(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" gatewayResourceName := "aws_storagegateway_gateway.test" @@ -51,7 +51,7 @@ func TestAccStorageGatewaySMBFileShare_Authentication_activeDirectory(t *testing resource.TestCheckResourceAttr(resourceName, "kms_encrypted", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, names.AttrKMSKeyARN, ""), resource.TestCheckResourceAttrPair(resourceName, "location_arn", bucketResourceName, names.AttrARN), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPrivate), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPrivate)), resource.TestMatchResourceAttr(resourceName, names.AttrPath, regexache.MustCompile(`^/.+`)), resource.TestCheckResourceAttr(resourceName, "read_only", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, "requester_pays", acctest.CtFalse), @@ -73,7 +73,7 @@ func TestAccStorageGatewaySMBFileShare_Authentication_activeDirectory(t *testing func TestAccStorageGatewaySMBFileShare_Authentication_guestAccess(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" gatewayResourceName := "aws_storagegateway_gateway.test" @@ -104,7 +104,7 @@ func TestAccStorageGatewaySMBFileShare_Authentication_guestAccess(t *testing.T) resource.TestCheckResourceAttr(resourceName, "kms_encrypted", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, names.AttrKMSKeyARN, ""), resource.TestCheckResourceAttrPair(resourceName, "location_arn", bucketResourceName, names.AttrARN), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPrivate), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPrivate)), resource.TestCheckResourceAttr(resourceName, "read_only", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, "requester_pays", acctest.CtFalse), resource.TestCheckResourceAttrPair(resourceName, names.AttrRoleARN, iamResourceName, names.AttrARN), @@ -124,7 +124,7 @@ func TestAccStorageGatewaySMBFileShare_Authentication_guestAccess(t *testing.T) func TestAccStorageGatewaySMBFileShare_accessBasedEnumeration(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -166,7 +166,7 @@ func TestAccStorageGatewaySMBFileShare_accessBasedEnumeration(t *testing.T) { func TestAccStorageGatewaySMBFileShare_notificationPolicy(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -208,7 +208,7 @@ func TestAccStorageGatewaySMBFileShare_notificationPolicy(t *testing.T) { func TestAccStorageGatewaySMBFileShare_defaultStorageClass(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -243,7 +243,7 @@ func TestAccStorageGatewaySMBFileShare_defaultStorageClass(t *testing.T) { func TestAccStorageGatewaySMBFileShare_encryptedUpdate(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -275,7 +275,7 @@ func TestAccStorageGatewaySMBFileShare_encryptedUpdate(t *testing.T) { func TestAccStorageGatewaySMBFileShare_fileShareName(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -310,7 +310,7 @@ func TestAccStorageGatewaySMBFileShare_fileShareName(t *testing.T) { func TestAccStorageGatewaySMBFileShare_tags(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -356,7 +356,7 @@ func TestAccStorageGatewaySMBFileShare_tags(t *testing.T) { func TestAccStorageGatewaySMBFileShare_guessMIMETypeEnabled(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -444,7 +444,7 @@ func TestAccStorageGatewaySMBFileShare_opLocksEnabled(t *testing.T) { func TestAccStorageGatewaySMBFileShare_invalidUserList(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" domainName := acctest.RandomDomainName() @@ -487,7 +487,7 @@ func TestAccStorageGatewaySMBFileShare_invalidUserList(t *testing.T) { func TestAccStorageGatewaySMBFileShare_kmsEncrypted(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -519,7 +519,7 @@ func TestAccStorageGatewaySMBFileShare_kmsEncrypted(t *testing.T) { func TestAccStorageGatewaySMBFileShare_kmsKeyARN(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" keyName := "aws_kms_key.test.0" @@ -565,7 +565,7 @@ func TestAccStorageGatewaySMBFileShare_kmsKeyARN(t *testing.T) { func TestAccStorageGatewaySMBFileShare_objectACL(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -576,17 +576,17 @@ func TestAccStorageGatewaySMBFileShare_objectACL(t *testing.T) { CheckDestroy: testAccCheckSMBFileShareDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccSMBFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicRead), + Config: testAccSMBFileShareConfig_objectACL(rName, string(awstypes.ObjectACLPublicRead)), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(ctx, resourceName, &smbFileShare), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicRead), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPublicRead)), ), }, { - Config: testAccSMBFileShareConfig_objectACL(rName, storagegateway.ObjectACLPublicReadWrite), + Config: testAccSMBFileShareConfig_objectACL(rName, string(awstypes.ObjectACLPublicReadWrite)), Check: resource.ComposeTestCheckFunc( testAccCheckSMBFileShareExists(ctx, resourceName, &smbFileShare), - resource.TestCheckResourceAttr(resourceName, "object_acl", storagegateway.ObjectACLPublicReadWrite), + resource.TestCheckResourceAttr(resourceName, "object_acl", string(awstypes.ObjectACLPublicReadWrite)), ), }, { @@ -600,7 +600,7 @@ func TestAccStorageGatewaySMBFileShare_objectACL(t *testing.T) { func TestAccStorageGatewaySMBFileShare_readOnly(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -635,7 +635,7 @@ func TestAccStorageGatewaySMBFileShare_readOnly(t *testing.T) { func TestAccStorageGatewaySMBFileShare_requesterPays(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -670,7 +670,7 @@ func TestAccStorageGatewaySMBFileShare_requesterPays(t *testing.T) { func TestAccStorageGatewaySMBFileShare_validUserList(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" domainName := acctest.RandomDomainName() @@ -713,7 +713,7 @@ func TestAccStorageGatewaySMBFileShare_validUserList(t *testing.T) { func TestAccStorageGatewaySMBFileShare_SMB_acl(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" domainName := acctest.RandomDomainName() @@ -756,7 +756,7 @@ func TestAccStorageGatewaySMBFileShare_SMB_acl(t *testing.T) { func TestAccStorageGatewaySMBFileShare_audit(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" logResourceName := "aws_cloudwatch_log_group.test" @@ -793,7 +793,7 @@ func TestAccStorageGatewaySMBFileShare_audit(t *testing.T) { func TestAccStorageGatewaySMBFileShare_cacheAttributes(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -838,7 +838,7 @@ func TestAccStorageGatewaySMBFileShare_cacheAttributes(t *testing.T) { func TestAccStorageGatewaySMBFileShare_caseSensitivity(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -880,7 +880,7 @@ func TestAccStorageGatewaySMBFileShare_caseSensitivity(t *testing.T) { func TestAccStorageGatewaySMBFileShare_disappears(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" @@ -904,7 +904,7 @@ func TestAccStorageGatewaySMBFileShare_disappears(t *testing.T) { func TestAccStorageGatewaySMBFileShare_adminUserList(t *testing.T) { ctx := acctest.Context(t) - var smbFileShare storagegateway.SMBFileShareInfo + var smbFileShare awstypes.SMBFileShareInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_smb_file_share.test" domainName := acctest.RandomDomainName() @@ -947,7 +947,7 @@ func TestAccStorageGatewaySMBFileShare_adminUserList(t *testing.T) { func testAccCheckSMBFileShareDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_smb_file_share" { @@ -971,14 +971,14 @@ func testAccCheckSMBFileShareDestroy(ctx context.Context) resource.TestCheckFunc } } -func testAccCheckSMBFileShareExists(ctx context.Context, resourceName string, smbFileShare *storagegateway.SMBFileShareInfo) resource.TestCheckFunc { +func testAccCheckSMBFileShareExists(ctx context.Context, resourceName string, smbFileShare *awstypes.SMBFileShareInfo) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) output, err := tfstoragegateway.FindSMBFileShareByARN(ctx, conn, rs.Primary.ID) From d1c250dc62e11136442af4715f93effbc5e92aba Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:56:06 +0200 Subject: [PATCH 10/39] feat: migrate r/stored_iscsi_volume to SDKv2 --- .../storagegateway/stored_iscsi_volume.go | 46 ++++++++++--------- .../stored_iscsi_volume_test.go | 40 ++++++++-------- 2 files changed, 45 insertions(+), 41 deletions(-) diff --git a/internal/service/storagegateway/stored_iscsi_volume.go b/internal/service/storagegateway/stored_iscsi_volume.go index 3b9a71fc4752..10b934960a7b 100644 --- a/internal/service/storagegateway/stored_iscsi_volume.go +++ b/internal/service/storagegateway/stored_iscsi_volume.go @@ -8,13 +8,15 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-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" @@ -130,14 +132,14 @@ func resourceStorediSCSIVolume() *schema.Resource { func resourceStorediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.CreateStorediSCSIVolumeInput{ DiskId: aws.String(d.Get("disk_id").(string)), GatewayARN: aws.String(d.Get("gateway_arn").(string)), NetworkInterfaceId: aws.String(d.Get(names.AttrNetworkInterfaceID).(string)), TargetName: aws.String(d.Get("target_name").(string)), - PreserveExistingData: aws.Bool(d.Get("preserve_existing_data").(bool)), + PreserveExistingData: d.Get("preserve_existing_data").(bool), Tags: getTagsIn(ctx), } @@ -153,13 +155,13 @@ func resourceStorediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData input.KMSEncrypted = aws.Bool(v.(bool)) } - log.Printf("[DEBUG] Creating Storage Gateway Stored iSCSI volume: %s", input) - output, err := conn.CreateStorediSCSIVolumeWithContext(ctx, input) + log.Printf("[DEBUG] Creating Storage Gateway Stored iSCSI volume: %#v", input) + output, err := conn.CreateStorediSCSIVolume(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Stored iSCSI volume: %s", err) } - d.SetId(aws.StringValue(output.VolumeARN)) + d.SetId(aws.ToString(output.VolumeARN)) _, err = waitStorediSCSIVolumeAvailable(ctx, conn, d.Id()) @@ -172,17 +174,17 @@ func resourceStorediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData func resourceStorediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(d.Id())}, + VolumeARNs: []string{d.Id()}, } log.Printf("[DEBUG] Reading Storage Gateway Stored iSCSI volume: %s", input) - output, err := conn.DescribeStorediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeStorediSCSIVolumes(ctx, input) if err != nil { - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) || tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) || errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { log.Printf("[WARN] Storage Gateway Stored iSCSI volume %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -190,7 +192,7 @@ func resourceStorediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Stored iSCSI volume %q: %s", d.Id(), err) } - if output == nil || len(output.StorediSCSIVolumes) == 0 || output.StorediSCSIVolumes[0] == nil || aws.StringValue(output.StorediSCSIVolumes[0].VolumeARN) != d.Id() { + if output == nil || len(output.StorediSCSIVolumes) == 0 || aws.ToString(output.StorediSCSIVolumes[0].VolumeARN) != d.Id() { log.Printf("[WARN] Storage Gateway Stored iSCSI volume %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -198,7 +200,7 @@ func resourceStorediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, volume := output.StorediSCSIVolumes[0] - arn := aws.StringValue(volume.VolumeARN) + arn := aws.ToString(volume.VolumeARN) d.Set(names.AttrARN, arn) d.Set("disk_id", volume.VolumeDiskId) d.Set(names.AttrSnapshotID, volume.SourceSnapshotId) @@ -217,10 +219,10 @@ func resourceStorediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, d.Set(names.AttrNetworkInterfaceID, attr.NetworkInterfaceId) d.Set("network_interface_port", attr.NetworkInterfacePort) - targetARN := aws.StringValue(attr.TargetARN) + targetARN := aws.ToString(attr.TargetARN) d.Set(names.AttrTargetARN, targetARN) - gatewayARN, targetName, err := ParseVolumeGatewayARNAndTargetNameFromARN(targetARN) + gatewayARN, targetName, err := parseVolumeGatewayARNAndTargetNameFromARN(targetARN) if err != nil { return sdkdiag.AppendErrorf(diags, "parsing Storage Gateway volume gateway ARN and target name from target ARN %q: %s", targetARN, err) } @@ -240,22 +242,22 @@ func resourceStorediSCSIVolumeUpdate(ctx context.Context, d *schema.ResourceData func resourceStorediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DeleteVolumeInput{ VolumeARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting Storage Gateway Stored iSCSI volume: %s", input) + log.Printf("[DEBUG] Deleting Storage Gateway Stored iSCSI volume: %#v", input) err := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { - _, err := conn.DeleteVolumeWithContext(ctx, input) + _, err := conn.DeleteVolume(ctx, input) if err != nil { - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { return nil } // InvalidGatewayRequestException: The specified gateway is not connected. // Can occur during concurrent DeleteVolume operations - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified gateway is not connected") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { return retry.RetryableError(err) } return retry.NonRetryableError(err) @@ -263,9 +265,9 @@ func resourceStorediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData return nil }) if tfresource.TimedOut(err) { - _, err = conn.DeleteVolumeWithContext(ctx, input) + _, err = conn.DeleteVolume(ctx, input) } - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { return diags } if err != nil { diff --git a/internal/service/storagegateway/stored_iscsi_volume_test.go b/internal/service/storagegateway/stored_iscsi_volume_test.go index 62af384f7c28..9f897e89a3bc 100644 --- a/internal/service/storagegateway/stored_iscsi_volume_test.go +++ b/internal/service/storagegateway/stored_iscsi_volume_test.go @@ -9,21 +9,23 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" 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" tfstoragegateway "github.com/hashicorp/terraform-provider-aws/internal/service/storagegateway" "github.com/hashicorp/terraform-provider-aws/names" ) func TestAccStorageGatewayStorediSCSIVolume_basic(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.StorediSCSIVolume + var storedIscsiVolume awstypes.StorediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_stored_iscsi_volume.test" @@ -65,7 +67,7 @@ func TestAccStorageGatewayStorediSCSIVolume_basic(t *testing.T) { func TestAccStorageGatewayStorediSCSIVolume_kms(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.StorediSCSIVolume + var storedIscsiVolume awstypes.StorediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_stored_iscsi_volume.test" keyResourceName := "aws_kms_key.test" @@ -95,7 +97,7 @@ func TestAccStorageGatewayStorediSCSIVolume_kms(t *testing.T) { func TestAccStorageGatewayStorediSCSIVolume_tags(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.StorediSCSIVolume + var storedIscsiVolume awstypes.StorediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_stored_iscsi_volume.test" @@ -144,7 +146,7 @@ func TestAccStorageGatewayStorediSCSIVolume_tags(t *testing.T) { func TestAccStorageGatewayStorediSCSIVolume_snapshotID(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.StorediSCSIVolume + var storedIscsiVolume awstypes.StorediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_stored_iscsi_volume.test" @@ -182,7 +184,7 @@ func TestAccStorageGatewayStorediSCSIVolume_snapshotID(t *testing.T) { func TestAccStorageGatewayStorediSCSIVolume_disappears(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.StorediSCSIVolume + var storedIscsiVolume awstypes.StorediSCSIVolume rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_stored_iscsi_volume.test" @@ -204,30 +206,30 @@ func TestAccStorageGatewayStorediSCSIVolume_disappears(t *testing.T) { }) } -func testAccCheckStorediSCSIVolumeExists(ctx context.Context, resourceName string, storedIscsiVolume *storagegateway.StorediSCSIVolume) resource.TestCheckFunc { +func testAccCheckStorediSCSIVolumeExists(ctx context.Context, resourceName string, storedIscsiVolume *awstypes.StorediSCSIVolume) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(rs.Primary.ID)}, + VolumeARNs: []string{rs.Primary.ID}, } - output, err := conn.DescribeStorediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeStorediSCSIVolumes(ctx, input) if err != nil { return fmt.Errorf("error reading Storage Gateway stored iSCSI volume: %w", err) } - if output == nil || len(output.StorediSCSIVolumes) == 0 || output.StorediSCSIVolumes[0] == nil || aws.StringValue(output.StorediSCSIVolumes[0].VolumeARN) != rs.Primary.ID { + if output == nil || len(output.StorediSCSIVolumes) == 0 || aws.ToString(output.StorediSCSIVolumes[0].VolumeARN) != rs.Primary.ID { return fmt.Errorf("Storage Gateway stored iSCSI volume %q not found", rs.Primary.ID) } - *storedIscsiVolume = *output.StorediSCSIVolumes[0] + *storedIscsiVolume = output.StorediSCSIVolumes[0] return nil } @@ -235,7 +237,7 @@ func testAccCheckStorediSCSIVolumeExists(ctx context.Context, resourceName strin func testAccCheckStorediSCSIVolumeDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_stored_iscsi_volume" { @@ -243,25 +245,25 @@ func testAccCheckStorediSCSIVolumeDestroy(ctx context.Context) resource.TestChec } input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(rs.Primary.ID)}, + VolumeARNs: []string{rs.Primary.ID}, } - output, err := conn.DescribeStorediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeStorediSCSIVolumes(ctx, input) if err != nil { if tfstoragegateway.IsErrGatewayNotFound(err) { return nil } - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { return nil } - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { return nil } return err } - if output != nil && len(output.StorediSCSIVolumes) > 0 && output.StorediSCSIVolumes[0] != nil && aws.StringValue(output.StorediSCSIVolumes[0].VolumeARN) == rs.Primary.ID { + if output != nil && len(output.StorediSCSIVolumes) > 0 && aws.ToString(output.StorediSCSIVolumes[0].VolumeARN) == rs.Primary.ID { return fmt.Errorf("Storage Gateway stored iSCSI volume %q still exists", rs.Primary.ID) } } From 4cd20695bef99eb69604f477d73f5d332ce75de4 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:56:19 +0200 Subject: [PATCH 11/39] feat: migrate r/upload_buffer to SDKv2 --- .../service/storagegateway/upload_buffer.go | 32 +++++++++---------- .../storagegateway/upload_buffer_test.go | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/internal/service/storagegateway/upload_buffer.go b/internal/service/storagegateway/upload_buffer.go index 8f59c47f3e64..ab25d82d56ac 100644 --- a/internal/service/storagegateway/upload_buffer.go +++ b/internal/service/storagegateway/upload_buffer.go @@ -9,9 +9,9 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/storagegateway" + "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/storagegateway" "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" @@ -57,24 +57,24 @@ func resourceUploadBuffer() *schema.Resource { func resourceUploadBufferCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.AddUploadBufferInput{} if v, ok := d.GetOk("disk_id"); ok { - input.DiskIds = aws.StringSlice([]string{v.(string)}) + input.DiskIds = []string{v.(string)} } // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17809 if v, ok := d.GetOk("disk_path"); ok { - input.DiskIds = aws.StringSlice([]string{v.(string)}) + input.DiskIds = []string{v.(string)} } if v, ok := d.GetOk("gateway_arn"); ok { input.GatewayARN = aws.String(v.(string)) } - output, err := conn.AddUploadBufferWithContext(ctx, input) + output, err := conn.AddUploadBuffer(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "adding Storage Gateway upload buffer: %s", err) @@ -85,12 +85,12 @@ func resourceUploadBufferCreate(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("disk_id"); ok { - d.SetId(fmt.Sprintf("%s:%s", aws.StringValue(output.GatewayARN), v.(string))) + d.SetId(fmt.Sprintf("%s:%s", aws.ToString(output.GatewayARN), v.(string))) return append(diags, resourceUploadBufferRead(ctx, d, meta)...) } - disk, err := findLocalDiskByGatewayARNAndDiskPath(ctx, conn, aws.StringValue(output.GatewayARN), aws.StringValue(input.DiskIds[0])) + disk, err := findLocalDiskByGatewayARNAndDiskPath(ctx, conn, aws.ToString(output.GatewayARN), input.DiskIds[0]) if err != nil { return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks after creating Upload Buffer: %s", err) @@ -100,23 +100,23 @@ func resourceUploadBufferCreate(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks after creating Upload Buffer: disk not found") } - d.SetId(fmt.Sprintf("%s:%s", aws.StringValue(output.GatewayARN), aws.StringValue(disk.DiskId))) + d.SetId(fmt.Sprintf("%s:%s", aws.ToString(output.GatewayARN), aws.ToString(disk.DiskId))) return append(diags, resourceUploadBufferRead(ctx, d, meta)...) } func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - gatewayARN, diskID, err := DecodeUploadBufferID(d.Id()) + gatewayARN, diskID, err := decodeUploadBufferID(d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Upload Buffer (%s): %s", d.Id(), err) } - foundDiskID, err := FindUploadBufferDisk(ctx, conn, gatewayARN, diskID) + foundDiskID, err := findUploadBufferDisk(ctx, conn, gatewayARN, diskID) - if !d.IsNewResource() && IsErrGatewayNotFound(err) { + if !d.IsNewResource() && isErrGatewayNotFound(err) { log.Printf("[WARN] Storage Gateway Upload Buffer (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -140,7 +140,7 @@ func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta d.Set("gateway_arn", gatewayARN) if _, ok := d.GetOk("disk_path"); !ok { - disk, err := findLocalDiskByGatewayARNAndDiskID(ctx, conn, gatewayARN, aws.StringValue(foundDiskID)) + disk, err := findLocalDiskByGatewayARNAndDiskID(ctx, conn, gatewayARN, aws.ToString(foundDiskID)) if err != nil { return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks: %s", err) @@ -156,7 +156,7 @@ func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta return diags } -func DecodeUploadBufferID(id string) (string, string, error) { +func decodeUploadBufferID(id string) (string, string, error) { // id = arn:aws:storagegateway:us-east-1:123456789012:gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 idFormatErr := fmt.Errorf("expected ID in form of GatewayARN:DiskId, received: %s", id) gatewayARNAndDisk, err := arn.Parse(id) diff --git a/internal/service/storagegateway/upload_buffer_test.go b/internal/service/storagegateway/upload_buffer_test.go index a5eda65535fa..a49fa7dd26af 100644 --- a/internal/service/storagegateway/upload_buffer_test.go +++ b/internal/service/storagegateway/upload_buffer_test.go @@ -150,7 +150,7 @@ func testAccCheckUploadBufferExists(ctx context.Context, resourceName string) re return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) gatewayARN, diskID, err := tfstoragegateway.DecodeUploadBufferID(rs.Primary.ID) if err != nil { From 2f03d588fbab2dbe695f3bf8dd785acebbff7ce2 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:56:29 +0200 Subject: [PATCH 12/39] feat: migrate sweepers to SDKv2 --- internal/service/storagegateway/sweep.go | 96 +++++++++++------------- 1 file changed, 42 insertions(+), 54 deletions(-) diff --git a/internal/service/storagegateway/sweep.go b/internal/service/storagegateway/sweep.go index 140390399cfa..f869458078a1 100644 --- a/internal/service/storagegateway/sweep.go +++ b/internal/service/storagegateway/sweep.go @@ -7,11 +7,11 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" "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() { @@ -40,33 +40,29 @@ func sweepGateways(region string) error { if err != nil { return fmt.Errorf("error getting client: %s", err) } - conn := client.StorageGatewayConn(ctx) + conn := client.StorageGatewayClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - err = conn.ListGatewaysPagesWithContext(ctx, &storagegateway.ListGatewaysInput{}, func(page *storagegateway.ListGatewaysOutput, lastPage bool) bool { - if len(page.Gateways) == 0 { - log.Print("[DEBUG] No Storage Gateway Gateways to sweep") - return true + pages := storagegateway.NewListGatewaysPaginator(conn, &storagegateway.ListGatewaysInput{}) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping Storage Gateway Gateway sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error listing Storage Gateway Gateways (%s): %w", region, err) } for _, gateway := range page.Gateways { r := resourceGateway() d := r.Data(nil) - d.SetId(aws.StringValue(gateway.GatewayARN)) + d.SetId(aws.ToString(gateway.GatewayARN)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } - - return !lastPage - }) - - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Storage Gateway Gateway sweep for %s: %s", region, err) - return nil - } - - if err != nil { - return fmt.Errorf("error listing Storage Gateway Gateways (%s): %w", region, err) } err = sweep.SweepOrchestrator(ctx, sweepResources) @@ -84,33 +80,29 @@ func sweepTapePools(region string) error { if err != nil { return fmt.Errorf("error getting client: %s", err) } - conn := client.StorageGatewayConn(ctx) + conn := client.StorageGatewayClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - err = conn.ListTapePoolsPagesWithContext(ctx, &storagegateway.ListTapePoolsInput{}, func(page *storagegateway.ListTapePoolsOutput, lastPage bool) bool { - if len(page.PoolInfos) == 0 { - log.Print("[DEBUG] No Storage Gateway Tape Pools to sweep") - return true + pages := storagegateway.NewListTapePoolsPaginator(conn, &storagegateway.ListTapePoolsInput{}) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping Storage Gateway Tape Pool sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error listing Storage Gateway Tape Pools (%s): %w", region, err) } for _, pool := range page.PoolInfos { r := resourceTapePool() d := r.Data(nil) - d.SetId(aws.StringValue(pool.PoolARN)) + d.SetId(aws.ToString(pool.PoolARN)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } - - return !lastPage - }) - - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Storage Gateway Tape Pool sweep for %s: %s", region, err) - return nil - } - - if err != nil { - return fmt.Errorf("error listing Storage Gateway Tape Pools (%s): %w", region, err) } err = sweep.SweepOrchestrator(ctx, sweepResources) @@ -128,33 +120,29 @@ func sweepFileSystemAssociations(region string) error { if err != nil { return fmt.Errorf("error getting client: %s", err) } - conn := client.StorageGatewayConn(ctx) + conn := client.StorageGatewayClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - err = conn.ListFileSystemAssociationsPagesWithContext(ctx, &storagegateway.ListFileSystemAssociationsInput{}, func(page *storagegateway.ListFileSystemAssociationsOutput, lastPage bool) bool { - if len(page.FileSystemAssociationSummaryList) == 0 { - log.Print("[DEBUG] No Storage Gateway File System Associations to sweep") - return true + pages := storagegateway.NewListFileSystemAssociationsPaginator(conn, &storagegateway.ListFileSystemAssociationsInput{}) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping Storage Gateway File System Association sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error listing Storage Gateway File System Associations (%s): %w", region, err) } for _, assoc := range page.FileSystemAssociationSummaryList { r := resourceFileSystemAssociation() d := r.Data(nil) - d.SetId(aws.StringValue(assoc.FileSystemAssociationARN)) + d.SetId(aws.ToString(assoc.FileSystemAssociationARN)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } - - return !lastPage - }) - - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Storage Gateway File System Association sweep for %s: %s", region, err) - return nil - } - - if err != nil { - return fmt.Errorf("error listing Storage Gateway File System Associations (%s): %w", region, err) } err = sweep.SweepOrchestrator(ctx, sweepResources) From bbff4e1f2e5b196ee1ac6f7dc8fc93d1885be5bf Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:56:42 +0200 Subject: [PATCH 13/39] feat: migrate r/tape_pool to SDKv2 --- internal/service/storagegateway/tape_pool.go | 56 ++++++++++--------- .../service/storagegateway/tape_pool_test.go | 31 +++++----- 2 files changed, 45 insertions(+), 42 deletions(-) diff --git a/internal/service/storagegateway/tape_pool.go b/internal/service/storagegateway/tape_pool.go index 6eb43d5f5476..8f88aa0fc285 100644 --- a/internal/service/storagegateway/tape_pool.go +++ b/internal/service/storagegateway/tape_pool.go @@ -7,12 +7,14 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -44,17 +46,17 @@ func resourceTapePool() *schema.Resource { ValidateFunc: validation.StringLenBetween(1, 100), }, names.AttrStorageClass: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(storagegateway.TapeStorageClass_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.TapeStorageClass](), }, "retention_lock_type": { - Type: schema.TypeString, - Optional: true, - Default: storagegateway.RetentionLockTypeNone, - ForceNew: true, - ValidateFunc: validation.StringInSlice(storagegateway.RetentionLockType_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.RetentionLockTypeNone, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.RetentionLockType](), }, "retention_lock_time_in_days": { Type: schema.TypeInt, @@ -73,43 +75,43 @@ func resourceTapePool() *schema.Resource { func resourceTapePoolCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.CreateTapePoolInput{ PoolName: aws.String(d.Get("pool_name").(string)), - StorageClass: aws.String(d.Get(names.AttrStorageClass).(string)), - RetentionLockType: aws.String(d.Get("retention_lock_type").(string)), - RetentionLockTimeInDays: aws.Int64(int64(d.Get("retention_lock_time_in_days").(int))), + StorageClass: awstypes.TapeStorageClass(d.Get(names.AttrStorageClass).(string)), + RetentionLockType: awstypes.RetentionLockType(d.Get("retention_lock_type").(string)), + RetentionLockTimeInDays: aws.Int32(int32(d.Get("retention_lock_time_in_days").(int))), Tags: getTagsIn(ctx), } - log.Printf("[DEBUG] Creating Storage Gateway Tape Pool: %s", input) - output, err := conn.CreateTapePoolWithContext(ctx, input) + log.Printf("[DEBUG] Creating Storage Gateway Tape Pool: %#v", input) + output, err := conn.CreateTapePool(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Tape Pool: %s", err) } - d.SetId(aws.StringValue(output.PoolARN)) + d.SetId(aws.ToString(output.PoolARN)) return append(diags, resourceTapePoolRead(ctx, d, meta)...) } func resourceTapePoolRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.ListTapePoolsInput{ - PoolARNs: []*string{aws.String(d.Id())}, + PoolARNs: []string{d.Id()}, } - log.Printf("[DEBUG] Reading Storage Gateway Tape Pool: %s", input) - output, err := conn.ListTapePoolsWithContext(ctx, input) + log.Printf("[DEBUG] Reading Storage Gateway Tape Pool: %#v", input) + output, err := conn.ListTapePools(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Tape Pools: %s", err) } - if output == nil || len(output.PoolInfos) == 0 || output.PoolInfos[0] == nil || aws.StringValue(output.PoolInfos[0].PoolARN) != d.Id() { + if output == nil || len(output.PoolInfos) == 0 || aws.ToString(output.PoolInfos[0].PoolARN) != d.Id() { log.Printf("[WARN] Storage Gateway Tape Pool %q not found, removing from state", d.Id()) d.SetId("") return diags @@ -117,7 +119,7 @@ func resourceTapePoolRead(ctx context.Context, d *schema.ResourceData, meta inte pool := output.PoolInfos[0] - poolArn := aws.StringValue(pool.PoolARN) + poolArn := aws.ToString(pool.PoolARN) d.Set(names.AttrARN, poolArn) d.Set("pool_name", pool.PoolName) d.Set("retention_lock_time_in_days", pool.RetentionLockTimeInDays) @@ -137,14 +139,14 @@ func resourceTapePoolUpdate(ctx context.Context, d *schema.ResourceData, meta in func resourceTapePoolDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.DeleteTapePoolInput{ PoolARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting Storage Gateway Tape Pool: %s", input) - _, err := conn.DeleteTapePoolWithContext(ctx, input) + log.Printf("[DEBUG] Deleting Storage Gateway Tape Pool: %#v", input) + _, err := conn.DeleteTapePool(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Tape Pool %q: %s", d.Id(), err) } diff --git a/internal/service/storagegateway/tape_pool_test.go b/internal/service/storagegateway/tape_pool_test.go index 2665741038c9..fa0098e2b8a8 100644 --- a/internal/service/storagegateway/tape_pool_test.go +++ b/internal/service/storagegateway/tape_pool_test.go @@ -9,8 +9,9 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" @@ -22,7 +23,7 @@ import ( func TestAccStorageGatewayTapePool_basic(t *testing.T) { ctx := acctest.Context(t) - var TapePool storagegateway.PoolInfo + var TapePool awstypes.PoolInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_tape_pool.test" @@ -54,7 +55,7 @@ func TestAccStorageGatewayTapePool_basic(t *testing.T) { func TestAccStorageGatewayTapePool_retention(t *testing.T) { ctx := acctest.Context(t) - var TapePool storagegateway.PoolInfo + var TapePool awstypes.PoolInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_tape_pool.test" @@ -86,7 +87,7 @@ func TestAccStorageGatewayTapePool_retention(t *testing.T) { func TestAccStorageGatewayTapePool_tags(t *testing.T) { ctx := acctest.Context(t) - var TapePool storagegateway.PoolInfo + var TapePool awstypes.PoolInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_tape_pool.test" @@ -132,7 +133,7 @@ func TestAccStorageGatewayTapePool_tags(t *testing.T) { func TestAccStorageGatewayTapePool_disappears(t *testing.T) { ctx := acctest.Context(t) - var storedIscsiVolume storagegateway.PoolInfo + var storedIscsiVolume awstypes.PoolInfo rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_storagegateway_tape_pool.test" @@ -154,30 +155,30 @@ func TestAccStorageGatewayTapePool_disappears(t *testing.T) { }) } -func testAccCheckTapePoolExists(ctx context.Context, resourceName string, TapePool *storagegateway.PoolInfo) resource.TestCheckFunc { +func testAccCheckTapePoolExists(ctx context.Context, resourceName string, TapePool *awstypes.PoolInfo) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.ListTapePoolsInput{ - PoolARNs: []*string{aws.String(rs.Primary.ID)}, + PoolARNs: []string{rs.Primary.ID}, } - output, err := conn.ListTapePoolsWithContext(ctx, input) + output, err := conn.ListTapePools(ctx, input) if err != nil { return fmt.Errorf("error reading Storage Gateway Tape Pool: %s", err) } - if output == nil || len(output.PoolInfos) == 0 || output.PoolInfos[0] == nil || aws.StringValue(output.PoolInfos[0].PoolARN) != rs.Primary.ID { + if output == nil || len(output.PoolInfos) == 0 || aws.ToString(output.PoolInfos[0].PoolARN) != rs.Primary.ID { return fmt.Errorf("Storage Gateway Tape Pool %q not found", rs.Primary.ID) } - *TapePool = *output.PoolInfos[0] + *TapePool = output.PoolInfos[0] return nil } @@ -185,7 +186,7 @@ func testAccCheckTapePoolExists(ctx context.Context, resourceName string, TapePo func testAccCheckTapePoolDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_storagegateway_tape_pool" { @@ -193,10 +194,10 @@ func testAccCheckTapePoolDestroy(ctx context.Context) resource.TestCheckFunc { } input := &storagegateway.ListTapePoolsInput{ - PoolARNs: []*string{aws.String(rs.Primary.ID)}, + PoolARNs: []string{rs.Primary.ID}, } - output, err := conn.ListTapePoolsWithContext(ctx, input) + output, err := conn.ListTapePools(ctx, input) if err != nil { return err From 77f4b74dade557a000221300ffb430a1de90631d Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:56:55 +0200 Subject: [PATCH 14/39] feat: migrate d/local_disk to SDKv2 --- .../storagegateway/local_disk_data_source.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/internal/service/storagegateway/local_disk_data_source.go b/internal/service/storagegateway/local_disk_data_source.go index fc52844af965..f449313be000 100644 --- a/internal/service/storagegateway/local_disk_data_source.go +++ b/internal/service/storagegateway/local_disk_data_source.go @@ -7,8 +7,9 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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" @@ -47,14 +48,14 @@ func dataSourceLocalDisk() *schema.Resource { func dataSourceLocalDiskRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).StorageGatewayConn(ctx) + conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) input := &storagegateway.ListLocalDisksInput{ GatewayARN: aws.String(d.Get("gateway_arn").(string)), } - log.Printf("[DEBUG] Reading Storage Gateway Local Disk: %s", input) - output, err := conn.ListLocalDisksWithContext(ctx, input) + log.Printf("[DEBUG] Reading Storage Gateway Local Disk: %#v", input) + output, err := conn.ListLocalDisks(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Local Disk: %s", err) } @@ -63,14 +64,14 @@ func dataSourceLocalDiskRead(ctx context.Context, d *schema.ResourceData, meta i return sdkdiag.AppendErrorf(diags, "no results found for query, try adjusting your search criteria") } - var matchingDisks []*storagegateway.Disk + var matchingDisks []awstypes.Disk for _, disk := range output.Disks { - if v, ok := d.GetOk("disk_node"); ok && v.(string) == aws.StringValue(disk.DiskNode) { + if v, ok := d.GetOk("disk_node"); ok && v.(string) == aws.ToString(disk.DiskNode) { matchingDisks = append(matchingDisks, disk) continue } - if v, ok := d.GetOk("disk_path"); ok && v.(string) == aws.StringValue(disk.DiskPath) { + if v, ok := d.GetOk("disk_path"); ok && v.(string) == aws.ToString(disk.DiskPath) { matchingDisks = append(matchingDisks, disk) continue } @@ -86,7 +87,7 @@ func dataSourceLocalDiskRead(ctx context.Context, d *schema.ResourceData, meta i disk := matchingDisks[0] - d.SetId(aws.StringValue(disk.DiskId)) + d.SetId(aws.ToString(disk.DiskId)) d.Set("disk_id", disk.DiskId) d.Set("disk_node", disk.DiskNode) d.Set("disk_path", disk.DiskPath) From 07b9973f997e906f457382bb98f1ea8d292fea49 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:57:15 +0200 Subject: [PATCH 15/39] chore: reduce visibility --- internal/service/storagegateway/cache.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/storagegateway/cache.go b/internal/service/storagegateway/cache.go index 263dc9ffd9bb..3b1dbaada4bb 100644 --- a/internal/service/storagegateway/cache.go +++ b/internal/service/storagegateway/cache.go @@ -108,7 +108,7 @@ func resourceCacheRead(ctx context.Context, d *schema.ResourceData, meta interfa output, err := conn.DescribeCache(ctx, input) if err != nil { - if IsErrGatewayNotFound(err) { + if isErrGatewayNotFound(err) { log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) d.SetId("") return diags From 93b918fea6dd13475894e395faa4eca72a7f27e5 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:57:31 +0200 Subject: [PATCH 16/39] feat: migrate `find` functions --- internal/service/storagegateway/find.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go index 7cf71de6f5e2..931b38f786c1 100644 --- a/internal/service/storagegateway/find.go +++ b/internal/service/storagegateway/find.go @@ -59,7 +59,7 @@ func findLocalDiskByGatewayARNAndDiskPath(ctx context.Context, conn *storagegate }) } -func FindUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gatewayARN string, diskID string) (*string, error) { +func findUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gatewayARN string, diskID string) (*string, error) { input := &storagegateway.DescribeUploadBufferInput{ GatewayARN: aws.String(gatewayARN), } @@ -86,7 +86,7 @@ func FindUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gate return &result, err } -func FindGatewayByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*storagegateway.DescribeGatewayInformationOutput, error) { +func findGatewayByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*storagegateway.DescribeGatewayInformationOutput, error) { input := &storagegateway.DescribeGatewayInformationInput{ GatewayARN: aws.String(arn), } @@ -111,7 +111,7 @@ func FindGatewayByARN(ctx context.Context, conn *storagegateway.Client, arn stri return output, nil } -func FindNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.NFSFileShareInfo, error) { +func findNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.NFSFileShareInfo, error) { input := &storagegateway.DescribeNFSFileSharesInput{ FileShareARNList: []string{arn}, } @@ -140,7 +140,7 @@ func FindNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn return &output.NFSFileShareInfoList[0], nil } -func FindSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.SMBFileShareInfo, error) { +func findSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.SMBFileShareInfo, error) { input := &storagegateway.DescribeSMBFileSharesInput{ FileShareARNList: []string{arn}, } @@ -169,7 +169,7 @@ func FindSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn return &output.SMBFileShareInfoList[0], nil } -func FindFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.FileSystemAssociationInfo, error) { +func findFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.FileSystemAssociationInfo, error) { input := &storagegateway.DescribeFileSystemAssociationsInput{ FileSystemAssociationARNList: []string{arn}, } From 2fe6a86876c0bfbc227134202bb2239104e9272e Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:57:54 +0200 Subject: [PATCH 17/39] feat: migrate `status` functions to SDKv2 --- internal/service/storagegateway/status.go | 58 ++++++++++++----------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/internal/service/storagegateway/status.go b/internal/service/storagegateway/status.go index c2cd9a1b339c..4d55a504d69c 100644 --- a/internal/service/storagegateway/status.go +++ b/internal/service/storagegateway/status.go @@ -6,10 +6,12 @@ package storagegateway import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/storagegateway" - "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/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -18,16 +20,16 @@ const ( storediSCSIVolumeStatusNotFound = "NotFound" ) -func statusGateway(ctx context.Context, conn *storagegateway.StorageGateway, gatewayARN string) retry.StateRefreshFunc { +func statusGateway(ctx context.Context, conn *storagegateway.Client, gatewayARN string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &storagegateway.DescribeGatewayInformationInput{ GatewayARN: aws.String(gatewayARN), } - output, err := conn.DescribeGatewayInformationWithContext(ctx, input) + output, err := conn.DescribeGatewayInformation(ctx, input) - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified gateway is not connected") { - return output, storagegateway.ErrorCodeGatewayNotConnected, nil + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { + return output, string(awstypes.ErrorCodeGatewayNotConnected), nil } if err != nil { @@ -38,37 +40,37 @@ func statusGateway(ctx context.Context, conn *storagegateway.StorageGateway, gat } } -func statusGatewayJoinDomain(ctx context.Context, conn *storagegateway.StorageGateway, gatewayARN string) retry.StateRefreshFunc { +func statusGatewayJoinDomain(ctx context.Context, conn *storagegateway.Client, gatewayARN string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &storagegateway.DescribeSMBSettingsInput{ GatewayARN: aws.String(gatewayARN), } - output, err := conn.DescribeSMBSettingsWithContext(ctx, input) + output, err := conn.DescribeSMBSettings(ctx, input) - if tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified gateway is not connected") { - return output, storagegateway.ActiveDirectoryStatusUnknownError, nil + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { + return output, string(awstypes.ActiveDirectoryStatusUnknownError), nil } if err != nil { - return output, storagegateway.ActiveDirectoryStatusUnknownError, err + return output, string(awstypes.ActiveDirectoryStatusUnknownError), err } - return output, aws.StringValue(output.ActiveDirectoryStatus), nil + return output, string(output.ActiveDirectoryStatus), nil } } // statusStorediSCSIVolume fetches the Volume and its Status -func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.StorageGateway, volumeARN string) retry.StateRefreshFunc { +func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, volumeARN string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []*string{aws.String(volumeARN)}, + VolumeARNs: []string{volumeARN}, } - output, err := conn.DescribeStorediSCSIVolumesWithContext(ctx, input) + output, err := conn.DescribeStorediSCSIVolumes(ctx, input) - if tfawserr.ErrCodeEquals(err, storagegateway.ErrorCodeVolumeNotFound) || - tfawserr.ErrMessageContains(err, storagegateway.ErrCodeInvalidGatewayRequestException, "The specified volume was not found") { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) || + errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { return nil, storediSCSIVolumeStatusNotFound, nil } @@ -80,13 +82,13 @@ func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.StorageGa return nil, storediSCSIVolumeStatusNotFound, nil } - return output, aws.StringValue(output.StorediSCSIVolumes[0].VolumeStatus), nil + return output, aws.ToString(output.StorediSCSIVolumes[0].VolumeStatus), nil } } -func statusNFSFileShare(ctx context.Context, conn *storagegateway.StorageGateway, arn string) retry.StateRefreshFunc { +func statusNFSFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindNFSFileShareByARN(ctx, conn, arn) + output, err := findNFSFileShareByARN(ctx, conn, arn) if tfresource.NotFound(err) { return nil, "", nil @@ -96,13 +98,13 @@ func statusNFSFileShare(ctx context.Context, conn *storagegateway.StorageGateway return nil, "", err } - return output, aws.StringValue(output.FileShareStatus), nil + return output, aws.ToString(output.FileShareStatus), nil } } -func statusSMBFileShare(ctx context.Context, conn *storagegateway.StorageGateway, arn string) retry.StateRefreshFunc { +func statusSMBFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSMBFileShareByARN(ctx, conn, arn) + output, err := findSMBFileShareByARN(ctx, conn, arn) if tfresource.NotFound(err) { return nil, "", nil @@ -112,13 +114,13 @@ func statusSMBFileShare(ctx context.Context, conn *storagegateway.StorageGateway return nil, "", err } - return output, aws.StringValue(output.FileShareStatus), nil + return output, aws.ToString(output.FileShareStatus), nil } } -func statusFileSystemAssociation(ctx context.Context, conn *storagegateway.StorageGateway, arn string) retry.StateRefreshFunc { +func statusFileSystemAssociation(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindFileSystemAssociationByARN(ctx, conn, arn) + output, err := findFileSystemAssociationByARN(ctx, conn, arn) if tfresource.NotFound(err) { return nil, "", nil @@ -128,6 +130,6 @@ func statusFileSystemAssociation(ctx context.Context, conn *storagegateway.Stora return nil, "", err } - return output, aws.StringValue(output.FileSystemAssociationStatus), nil + return output, aws.ToString(output.FileSystemAssociationStatus), nil } } From 60ba820fd244722236ecb0120e86ddc990564aa7 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:58:01 +0200 Subject: [PATCH 18/39] feat: migrate `wait` functions to SDKv2 --- internal/service/storagegateway/wait.go | 48 +++++++++++++------------ 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/internal/service/storagegateway/wait.go b/internal/service/storagegateway/wait.go index 4ecd5eecce93..aed236d0e544 100644 --- a/internal/service/storagegateway/wait.go +++ b/internal/service/storagegateway/wait.go @@ -7,8 +7,10 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/service/storagegateway" + "github.com/aws/aws-sdk-go-v2/service/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" ) const ( @@ -24,9 +26,9 @@ const ( fileSystemAssociationDeletedDelay = 5 * time.Second ) -func waitGatewayConnected(ctx context.Context, conn *storagegateway.StorageGateway, gatewayARN string, timeout time.Duration) (*storagegateway.DescribeGatewayInformationOutput, error) { +func waitGatewayConnected(ctx context.Context, conn *storagegateway.Client, gatewayARN string, timeout time.Duration) (*storagegateway.DescribeGatewayInformationOutput, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{storagegateway.ErrorCodeGatewayNotConnected}, + Pending: enum.Slice(awstypes.ErrorCodeGatewayNotConnected), Target: []string{gatewayStatusConnected}, Refresh: statusGateway(ctx, conn, gatewayARN), Timeout: timeout, @@ -44,10 +46,10 @@ func waitGatewayConnected(ctx context.Context, conn *storagegateway.StorageGatew } } -func waitGatewayJoinDomainJoined(ctx context.Context, conn *storagegateway.StorageGateway, volumeARN string) (*storagegateway.DescribeSMBSettingsOutput, error) { //nolint:unparam +func waitGatewayJoinDomainJoined(ctx context.Context, conn *storagegateway.Client, volumeARN string) (*storagegateway.DescribeSMBSettingsOutput, error) { //nolint:unparam stateConf := &retry.StateChangeConf{ - Pending: []string{storagegateway.ActiveDirectoryStatusJoining}, - Target: []string{storagegateway.ActiveDirectoryStatusJoined}, + Pending: enum.Slice(awstypes.ActiveDirectoryStatusJoining), + Target: enum.Slice(awstypes.ActiveDirectoryStatusJoined), Refresh: statusGatewayJoinDomain(ctx, conn, volumeARN), Timeout: gatewayJoinDomainJoinedTimeout, } @@ -62,7 +64,7 @@ func waitGatewayJoinDomainJoined(ctx context.Context, conn *storagegateway.Stora } // waitStorediSCSIVolumeAvailable waits for a StoredIscsiVolume to return Available -func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.StorageGateway, volumeARN string) (*storagegateway.DescribeStorediSCSIVolumesOutput, error) { +func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.Client, volumeARN string) (*storagegateway.DescribeStorediSCSIVolumesOutput, error) { stateConf := &retry.StateChangeConf{ Pending: []string{"BOOTSTRAPPING", "CREATING", "RESTORING"}, Target: []string{"AVAILABLE"}, @@ -79,7 +81,7 @@ func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.St return nil, err } -func waitNFSFileShareCreated(ctx context.Context, conn *storagegateway.StorageGateway, arn string, timeout time.Duration) (*storagegateway.NFSFileShareInfo, error) { +func waitNFSFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusCreating}, Target: []string{fileShareStatusAvailable}, @@ -90,14 +92,14 @@ func waitNFSFileShareCreated(ctx context.Context, conn *storagegateway.StorageGa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.NFSFileShareInfo); ok { + if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { return output, err } return nil, err } -func waitNFSFileShareDeleted(ctx context.Context, conn *storagegateway.StorageGateway, arn string, timeout time.Duration) (*storagegateway.NFSFileShareInfo, error) { +func waitNFSFileShareDeleted(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusAvailable, fileShareStatusDeleting, fileShareStatusForceDeleting}, Target: []string{}, @@ -109,14 +111,14 @@ func waitNFSFileShareDeleted(ctx context.Context, conn *storagegateway.StorageGa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.NFSFileShareInfo); ok { + if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { return output, err } return nil, err } -func waitNFSFileShareUpdated(ctx context.Context, conn *storagegateway.StorageGateway, arn string, timeout time.Duration) (*storagegateway.NFSFileShareInfo, error) { +func waitNFSFileShareUpdated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusUpdating}, Target: []string{fileShareStatusAvailable}, @@ -127,14 +129,14 @@ func waitNFSFileShareUpdated(ctx context.Context, conn *storagegateway.StorageGa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.NFSFileShareInfo); ok { + if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { return output, err } return nil, err } -func waitSMBFileShareCreated(ctx context.Context, conn *storagegateway.StorageGateway, arn string, timeout time.Duration) (*storagegateway.SMBFileShareInfo, error) { +func waitSMBFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusCreating}, Target: []string{fileShareStatusAvailable}, @@ -145,14 +147,14 @@ func waitSMBFileShareCreated(ctx context.Context, conn *storagegateway.StorageGa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.SMBFileShareInfo); ok { + if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { return output, err } return nil, err } -func waitSMBFileShareDeleted(ctx context.Context, conn *storagegateway.StorageGateway, arn string, timeout time.Duration) (*storagegateway.SMBFileShareInfo, error) { +func waitSMBFileShareDeleted(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusAvailable, fileShareStatusDeleting, fileShareStatusForceDeleting}, Target: []string{}, @@ -164,14 +166,14 @@ func waitSMBFileShareDeleted(ctx context.Context, conn *storagegateway.StorageGa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.SMBFileShareInfo); ok { + if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { return output, err } return nil, err } -func waitSMBFileShareUpdated(ctx context.Context, conn *storagegateway.StorageGateway, arn string, timeout time.Duration) (*storagegateway.SMBFileShareInfo, error) { +func waitSMBFileShareUpdated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusUpdating}, Target: []string{fileShareStatusAvailable}, @@ -182,14 +184,14 @@ func waitSMBFileShareUpdated(ctx context.Context, conn *storagegateway.StorageGa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.SMBFileShareInfo); ok { + if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { return output, err } return nil, err } -func waitFileSystemAssociationAvailable(ctx context.Context, conn *storagegateway.StorageGateway, fileSystemArn string, timeout time.Duration) (*storagegateway.FileSystemAssociationInfo, error) { //nolint:unparam +func waitFileSystemAssociationAvailable(ctx context.Context, conn *storagegateway.Client, fileSystemArn string, timeout time.Duration) (*awstypes.FileSystemAssociationInfo, error) { //nolint:unparam stateConf := &retry.StateChangeConf{ Pending: []string{fileSystemAssociationStatusCreating, fileSystemAssociationStatusUpdating}, Target: []string{fileSystemAssociationStatusAvailable}, @@ -200,14 +202,14 @@ func waitFileSystemAssociationAvailable(ctx context.Context, conn *storagegatewa outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.FileSystemAssociationInfo); ok { + if output, ok := outputRaw.(*awstypes.FileSystemAssociationInfo); ok { return output, err } return nil, err } -func waitFileSystemAssociationDeleted(ctx context.Context, conn *storagegateway.StorageGateway, fileSystemArn string, timeout time.Duration) (*storagegateway.FileSystemAssociationInfo, error) { +func waitFileSystemAssociationDeleted(ctx context.Context, conn *storagegateway.Client, fileSystemArn string, timeout time.Duration) (*awstypes.FileSystemAssociationInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileSystemAssociationStatusAvailable, fileSystemAssociationStatusDeleting, fileSystemAssociationStatusForceDeleting}, Target: []string{}, @@ -219,7 +221,7 @@ func waitFileSystemAssociationDeleted(ctx context.Context, conn *storagegateway. outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*storagegateway.FileSystemAssociationInfo); ok { + if output, ok := outputRaw.(*awstypes.FileSystemAssociationInfo); ok { return output, err } From 3755e475d92ba3963eb3fc2fc3840d1351f09d23 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 14:58:10 +0200 Subject: [PATCH 19/39] chore: fix exports --- internal/service/storagegateway/exports_test.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index 9dc7e02ad9d3..040183c96dfc 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -15,5 +15,15 @@ var ( ResourceTapePool = resourceTapePool ResourceUploadBuffer = resourceUploadBuffer - CacheParseResourceID = cacheParseResourceID + FindFileSystemAssociationByARN = findFileSystemAssociationByARN + FindGatewayByARN = findGatewayByARN + FindNFSFileShareByARN = findNFSFileShareByARN + FindSMBFileShareByARN = findSMBFileShareByARN + FindUploadBufferDisk = findUploadBufferDisk + + CacheParseResourceID = cacheParseResourceID + DecodeUploadBufferID = decodeUploadBufferID + DecodeWorkingStorageID = decodeWorkingStorageID + IsErrGatewayNotFound = isErrGatewayNotFound + ParseVolumeGatewayARNAndTargetNameFromARN = parseVolumeGatewayARNAndTargetNameFromARN ) From 5b18c41ccd56b35fa4c1aa0a202670a5eb332c9a Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 15:54:43 +0200 Subject: [PATCH 20/39] fix: nil exception --- internal/service/storagegateway/gateway.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/service/storagegateway/gateway.go b/internal/service/storagegateway/gateway.go index 35e90d634f22..c24fe8716746 100644 --- a/internal/service/storagegateway/gateway.go +++ b/internal/service/storagegateway/gateway.go @@ -591,8 +591,12 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter // We allow Terraform to passthrough the configuration value into the state d.Set("tape_drive_type", d.Get("tape_drive_type").(string)) d.Set(names.AttrCloudWatchLogGroupARN, output.CloudWatchLogGroupARN) - d.Set("smb_security_strategy", smbSettingsOutput.SMBSecurityStrategy) - d.Set("smb_file_share_visibility", smbSettingsOutput.FileSharesVisible) + + if smbSettingsOutput != nil { + d.Set("smb_security_strategy", smbSettingsOutput.SMBSecurityStrategy) + d.Set("smb_file_share_visibility", smbSettingsOutput.FileSharesVisible) + } + d.Set("ec2_instance_id", output.Ec2InstanceId) d.Set(names.AttrEndpointType, output.EndpointType) d.Set("host_environment", output.HostEnvironment) From c65609a739e9c16cd6a22229d12b2d824e212d6f Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 15:55:48 +0200 Subject: [PATCH 21/39] fix: fix `TestAccStorageGatewayTapePool_disappears` --- internal/service/storagegateway/tape_pool.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/service/storagegateway/tape_pool.go b/internal/service/storagegateway/tape_pool.go index 8f88aa0fc285..c16ebb2df6ae 100644 --- a/internal/service/storagegateway/tape_pool.go +++ b/internal/service/storagegateway/tape_pool.go @@ -15,6 +15,7 @@ import ( "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" @@ -147,6 +148,11 @@ func resourceTapePoolDelete(ctx context.Context, d *schema.ResourceData, meta in log.Printf("[DEBUG] Deleting Storage Gateway Tape Pool: %#v", input) _, err := conn.DeleteTapePool(ctx, input) + + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified po was not found") { + return diags + } + if err != nil { return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Tape Pool %q: %s", d.Id(), err) } From b62214d071170982bacd41df3e78bc4c2139b077 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 26 Jul 2024 15:57:57 +0200 Subject: [PATCH 22/39] fix: spelling mistake in error message --- internal/service/storagegateway/tape_pool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/storagegateway/tape_pool.go b/internal/service/storagegateway/tape_pool.go index c16ebb2df6ae..dca2ed671ec0 100644 --- a/internal/service/storagegateway/tape_pool.go +++ b/internal/service/storagegateway/tape_pool.go @@ -149,7 +149,7 @@ func resourceTapePoolDelete(ctx context.Context, d *schema.ResourceData, meta in log.Printf("[DEBUG] Deleting Storage Gateway Tape Pool: %#v", input) _, err := conn.DeleteTapePool(ctx, input) - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified po was not found") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified pool was not found") { return diags } From 0070e3f3bd113878dc447acadb6f50606505d778 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 27 Jul 2024 14:46:30 +0200 Subject: [PATCH 23/39] fix: fix `TestAccStorageGatewayGateway_GatewayType_cached` --- internal/service/storagegateway/gateway_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/service/storagegateway/gateway_test.go b/internal/service/storagegateway/gateway_test.go index 89d0426b8361..2ff867838c29 100644 --- a/internal/service/storagegateway/gateway_test.go +++ b/internal/service/storagegateway/gateway_test.go @@ -51,7 +51,6 @@ func TestAccStorageGatewayGateway_GatewayType_cached(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "medium_changer_type", ""), resource.TestCheckResourceAttr(resourceName, "smb_active_directory_settings.#", acctest.Ct0), resource.TestCheckResourceAttr(resourceName, "smb_guest_password", ""), - resource.TestCheckResourceAttr(resourceName, "smb_security_strategy", ""), resource.TestCheckResourceAttr(resourceName, "tape_drive_type", ""), ), }, From 703b349500262cb6d71a6b7102dcb58ddb6643b1 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sat, 27 Jul 2024 17:54:04 -0400 Subject: [PATCH 24/39] Run 'go mod tidy'. --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 4dd1bb445e59..558b91056cee 100644 --- a/go.mod +++ b/go.mod @@ -206,6 +206,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/ssmsap v1.15.3 github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 github.com/aws/aws-sdk-go-v2/service/ssoadmin v1.27.3 + github.com/aws/aws-sdk-go-v2/service/storagegateway v1.31.3 github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 github.com/aws/aws-sdk-go-v2/service/swf v1.25.3 github.com/aws/aws-sdk-go-v2/service/synthetics v1.26.3 @@ -286,7 +287,6 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect - github.com/aws/aws-sdk-go-v2/service/storagegateway v1.31.3 // indirect github.com/bgentry/speakeasy v0.1.0 // indirect github.com/boombuler/barcode v1.0.1 // indirect github.com/bufbuild/protocompile v0.6.0 // indirect From 29fa2987a729c843fc37e17ff1056b30a7f03c81 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sat, 27 Jul 2024 18:22:33 -0400 Subject: [PATCH 25/39] Add 'findCacheByTwoPartKey'. --- internal/service/storagegateway/cache.go | 70 ++++++++++++------- internal/service/storagegateway/cache_test.go | 51 ++++---------- .../cached_iscsi_volume_test.go | 2 +- .../storagegateway/{enum.go => consts.go} | 0 internal/service/storagegateway/errors.go | 14 ++++ .../service/storagegateway/exports_test.go | 3 +- internal/service/storagegateway/gateway.go | 13 +--- .../stored_iscsi_volume_test.go | 2 +- .../service/storagegateway/upload_buffer.go | 2 +- .../service/storagegateway/working_storage.go | 2 +- 10 files changed, 78 insertions(+), 81 deletions(-) rename internal/service/storagegateway/{enum.go => consts.go} (100%) diff --git a/internal/service/storagegateway/cache.go b/internal/service/storagegateway/cache.go index 3b1dbaada4bb..c2194fb30bf7 100644 --- a/internal/service/storagegateway/cache.go +++ b/internal/service/storagegateway/cache.go @@ -14,9 +14,11 @@ import ( "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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/sdkdiag" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -102,38 +104,16 @@ func resourceCacheRead(ctx context.Context, d *schema.ResourceData, meta interfa return sdkdiag.AppendFromErr(diags, err) } - input := &storagegateway.DescribeCacheInput{ - GatewayARN: aws.String(gatewayARN), - } - - output, err := conn.DescribeCache(ctx, input) - if err != nil { - if isErrGatewayNotFound(err) { - log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags - } - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Cache (%s): %s", d.Id(), err) - } + err = findCacheByTwoPartKey(ctx, conn, gatewayARN, diskID) - if output == nil || len(output.DiskIds) == 0 { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) d.SetId("") return diags } - found := false - for _, existingDiskID := range output.DiskIds { - if existingDiskID == diskID { - found = true - break - } - } - - if !found { - log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Cache (%s): %s", d.Id(), err) } d.Set("disk_id", diskID) @@ -173,3 +153,41 @@ func cacheParseResourceID(id string) (string, string, error) { } return gatewayARN.String(), resourceParts[1], nil } + +func findCacheByTwoPartKey(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskID string) error { + input := &storagegateway.DescribeCacheInput{ + GatewayARN: aws.String(gatewayARN), + } + output, err := findCache(ctx, conn, input) + + if err != nil { + return err + } + + _, err = tfresource.AssertSingleValueResult(tfslices.Filter(output.DiskIds, func(v string) bool { + return v == diskID + })) + + return err +} + +func findCache(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeCacheInput) (*storagegateway.DescribeCacheOutput, error) { + output, err := conn.DescribeCache(ctx, input) + + if isGatewayNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, err +} diff --git a/internal/service/storagegateway/cache_test.go b/internal/service/storagegateway/cache_test.go index 21c24f4fd251..b4ea71e6f0b4 100644 --- a/internal/service/storagegateway/cache_test.go +++ b/internal/service/storagegateway/cache_test.go @@ -8,8 +8,6 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -87,9 +85,8 @@ func TestAccStorageGatewayCache_fileGateway(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - // Storage Gateway API does not support removing caches, - // but we want to ensure other resources are removed. - CheckDestroy: testAccCheckGatewayDestroy(ctx), + // Storage Gateway API does not support removing caches. + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccCacheConfig_fileGateway(rName), @@ -118,9 +115,7 @@ func TestAccStorageGatewayCache_tapeAndVolumeGateway(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - // Storage Gateway API does not support removing caches, - // but we want to ensure other resources are removed. - CheckDestroy: testAccCheckGatewayDestroy(ctx), + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccCacheConfig_tapeAndVolumeGateway(rName), @@ -139,11 +134,11 @@ func TestAccStorageGatewayCache_tapeAndVolumeGateway(t *testing.T) { }) } -func testAccCheckCacheExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckCacheExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) @@ -153,39 +148,19 @@ func testAccCheckCacheExists(ctx context.Context, resourceName string) resource. return err } - input := &storagegateway.DescribeCacheInput{ - GatewayARN: aws.String(gatewayARN), - } - - output, err := conn.DescribeCache(ctx, input) - - if err != nil { - return fmt.Errorf("error reading Storage Gateway cache: %s", err) - } - - if output == nil || len(output.DiskIds) == 0 { - return fmt.Errorf("Storage Gateway cache %q not found", rs.Primary.ID) - } - - for _, existingDiskID := range output.DiskIds { - if existingDiskID == diskID { - return nil - } - } - - return fmt.Errorf("Storage Gateway cache %q not found", rs.Primary.ID) + return tfstoragegateway.FindCacheByTwoPartKey(ctx, conn, gatewayARN, diskID) } } func testAccCacheConfig_fileGateway(rName string) string { - return testAccGatewayConfig_typeFileS3(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_typeFileS3(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" type = "gp2" tags = { - Name = %q + Name = %[1]q } } @@ -215,18 +190,18 @@ resource "aws_storagegateway_cache" "test" { disk_id = data.aws_storagegateway_local_disk.test.id gateway_arn = aws_storagegateway_gateway.test.arn } -`, rName) +`, rName)) } func testAccCacheConfig_tapeAndVolumeGateway(rName string) string { - return testAccGatewayConfig_typeCached(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_typeCached(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" type = "gp2" tags = { - Name = %q + Name = %[1]q } } @@ -256,5 +231,5 @@ resource "aws_storagegateway_cache" "test" { disk_id = data.aws_storagegateway_local_disk.test.id gateway_arn = aws_storagegateway_gateway.test.arn } -`, rName) +`, rName)) } diff --git a/internal/service/storagegateway/cached_iscsi_volume_test.go b/internal/service/storagegateway/cached_iscsi_volume_test.go index 83b7e53006de..d401b97789da 100644 --- a/internal/service/storagegateway/cached_iscsi_volume_test.go +++ b/internal/service/storagegateway/cached_iscsi_volume_test.go @@ -348,7 +348,7 @@ func testAccCheckCachediSCSIVolumeDestroy(ctx context.Context) resource.TestChec output, err := conn.DescribeCachediSCSIVolumes(ctx, input) if err != nil { - if tfstoragegateway.IsErrGatewayNotFound(err) { + if tfstoragegateway.IsGatewayNotFoundErr(err) { return nil } if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { diff --git a/internal/service/storagegateway/enum.go b/internal/service/storagegateway/consts.go similarity index 100% rename from internal/service/storagegateway/enum.go rename to internal/service/storagegateway/consts.go diff --git a/internal/service/storagegateway/errors.go b/internal/service/storagegateway/errors.go index 0ea5de3704e8..2cef28daf739 100644 --- a/internal/service/storagegateway/errors.go +++ b/internal/service/storagegateway/errors.go @@ -5,6 +5,7 @@ package storagegateway import ( awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) @@ -32,3 +33,16 @@ func operationErrorCode(err error) string { return "" } + +// The API returns multiple responses for a missing gateway. +func isGatewayNotFoundErr(err error) bool { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found.") { + return true + } + + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { + return true + } + + return false +} diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index 040183c96dfc..7cde4b55143b 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -15,6 +15,7 @@ var ( ResourceTapePool = resourceTapePool ResourceUploadBuffer = resourceUploadBuffer + FindCacheByTwoPartKey = findCacheByTwoPartKey FindFileSystemAssociationByARN = findFileSystemAssociationByARN FindGatewayByARN = findGatewayByARN FindNFSFileShareByARN = findNFSFileShareByARN @@ -24,6 +25,6 @@ var ( CacheParseResourceID = cacheParseResourceID DecodeUploadBufferID = decodeUploadBufferID DecodeWorkingStorageID = decodeWorkingStorageID - IsErrGatewayNotFound = isErrGatewayNotFound + IsGatewayNotFoundErr = isGatewayNotFoundErr ParseVolumeGatewayARNAndTargetNameFromARN = parseVolumeGatewayARNAndTargetNameFromARN ) diff --git a/internal/service/storagegateway/gateway.go b/internal/service/storagegateway/gateway.go index c24fe8716746..0a7972de5a7d 100644 --- a/internal/service/storagegateway/gateway.go +++ b/internal/service/storagegateway/gateway.go @@ -512,7 +512,7 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter log.Printf("[DEBUG] Reading Storage Gateway SMB Settings: %#v", smbSettingsInput) smbSettingsOutput, err := conn.DescribeSMBSettings(ctx, smbSettingsInput) if err != nil && !errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway") { - if isErrGatewayNotFound(err) { + if isGatewayNotFoundErr(err) { log.Printf("[WARN] Storage Gateway Gateway %q not found - removing from state", d.Id()) d.SetId("") return diags @@ -910,14 +910,3 @@ func flattenDescribeMaintenanceStartTimeOutput(apiObject *storagegateway.Describ return tfMap } - -// The API returns multiple responses for a missing gateway -func isErrGatewayNotFound(err error) bool { - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found.") { - return true - } - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { - return true - } - return false -} diff --git a/internal/service/storagegateway/stored_iscsi_volume_test.go b/internal/service/storagegateway/stored_iscsi_volume_test.go index 9f897e89a3bc..9c32c6a09743 100644 --- a/internal/service/storagegateway/stored_iscsi_volume_test.go +++ b/internal/service/storagegateway/stored_iscsi_volume_test.go @@ -251,7 +251,7 @@ func testAccCheckStorediSCSIVolumeDestroy(ctx context.Context) resource.TestChec output, err := conn.DescribeStorediSCSIVolumes(ctx, input) if err != nil { - if tfstoragegateway.IsErrGatewayNotFound(err) { + if tfstoragegateway.IsGatewayNotFoundErr(err) { return nil } if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { diff --git a/internal/service/storagegateway/upload_buffer.go b/internal/service/storagegateway/upload_buffer.go index ab25d82d56ac..42de03b232d3 100644 --- a/internal/service/storagegateway/upload_buffer.go +++ b/internal/service/storagegateway/upload_buffer.go @@ -116,7 +116,7 @@ func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta foundDiskID, err := findUploadBufferDisk(ctx, conn, gatewayARN, diskID) - if !d.IsNewResource() && isErrGatewayNotFound(err) { + if !d.IsNewResource() && isGatewayNotFoundErr(err) { log.Printf("[WARN] Storage Gateway Upload Buffer (%s) not found, removing from state", d.Id()) d.SetId("") return diags diff --git a/internal/service/storagegateway/working_storage.go b/internal/service/storagegateway/working_storage.go index 4b63e318c7e4..4e0bf298764a 100644 --- a/internal/service/storagegateway/working_storage.go +++ b/internal/service/storagegateway/working_storage.go @@ -84,7 +84,7 @@ func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, met output, err := conn.DescribeWorkingStorage(ctx, input) if err != nil { - if isErrGatewayNotFound(err) { + if isGatewayNotFoundErr(err) { log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) d.SetId("") return diags From 9077e79fcc0ec26f4cadb2b3a2f44bcd10109265 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 28 Jul 2024 18:22:09 -0400 Subject: [PATCH 26/39] Add 'findCachediSCSIVolumeByARN'. --- .../storagegateway/cached_iscsi_volume.go | 172 ++++++++++-------- .../cached_iscsi_volume_test.go | 46 ++--- internal/service/storagegateway/errors.go | 17 +- .../service/storagegateway/exports_test.go | 1 + 4 files changed, 127 insertions(+), 109 deletions(-) diff --git a/internal/service/storagegateway/cached_iscsi_volume.go b/internal/service/storagegateway/cached_iscsi_volume.go index ad119c092321..fd883e242831 100644 --- a/internal/service/storagegateway/cached_iscsi_volume.go +++ b/internal/service/storagegateway/cached_iscsi_volume.go @@ -14,13 +14,11 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/arn" "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "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" @@ -56,6 +54,18 @@ func resourceCachediSCSIVolume() *schema.Resource { ForceNew: true, ValidateFunc: verify.ValidARN, }, + "kms_encrypted": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + }, + names.AttrKMSKey: { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidARN, + RequiredWith: []string{"kms_encrypted"}, + }, "lun_number": { Type: schema.TypeInt, Computed: true, @@ -81,6 +91,8 @@ func resourceCachediSCSIVolume() *schema.Resource { ForceNew: true, ValidateFunc: verify.ValidARN, }, + names.AttrTags: tftags.TagsSchema(), + names.AttrTagsAll: tftags.TagsSchemaComputed(), names.AttrTargetARN: { Type: schema.TypeString, Computed: true, @@ -103,20 +115,6 @@ func resourceCachediSCSIVolume() *schema.Resource { Required: true, ForceNew: true, }, - names.AttrTags: tftags.TagsSchema(), - names.AttrTagsAll: tftags.TagsSchemaComputed(), - "kms_encrypted": { - Type: schema.TypeBool, - Optional: true, - ForceNew: true, - }, - names.AttrKMSKey: { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: verify.ValidARN, - RequiredWith: []string{"kms_encrypted"}, - }, }, CustomizeDiff: verify.SetTagsDiff, @@ -131,17 +129,9 @@ func resourceCachediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData ClientToken: aws.String(id.UniqueId()), GatewayARN: aws.String(d.Get("gateway_arn").(string)), NetworkInterfaceId: aws.String(d.Get(names.AttrNetworkInterfaceID).(string)), + Tags: getTagsIn(ctx), TargetName: aws.String(d.Get("target_name").(string)), VolumeSizeInBytes: int64(d.Get("volume_size_in_bytes").(int)), - Tags: getTagsIn(ctx), - } - - if v, ok := d.GetOk(names.AttrSnapshotID); ok { - input.SnapshotId = aws.String(v.(string)) - } - - if v, ok := d.GetOk("source_volume_arn"); ok { - input.SourceVolumeARN = aws.String(v.(string)) } if v, ok := d.GetOk(names.AttrKMSKey); ok { @@ -152,10 +142,18 @@ func resourceCachediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData input.KMSEncrypted = aws.Bool(v.(bool)) } - log.Printf("[DEBUG] Creating Storage Gateway cached iSCSI volume: %#v", input) + if v, ok := d.GetOk(names.AttrSnapshotID); ok { + input.SnapshotId = aws.String(v.(string)) + } + + if v, ok := d.GetOk("source_volume_arn"); ok { + input.SourceVolumeARN = aws.String(v.(string)) + } + output, err := conn.CreateCachediSCSIVolume(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "creating Storage Gateway cached iSCSI volume: %s", err) + return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Cached iSCSI Volume: %s", err) } d.SetId(aws.ToString(output.VolumeARN)) @@ -167,42 +165,30 @@ func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DescribeCachediSCSIVolumesInput{ - VolumeARNs: []string{d.Id()}, - } + volume, err := findCachediSCSIVolumeByARN(ctx, conn, d.Id()) - log.Printf("[DEBUG] Reading Storage Gateway cached iSCSI volume: %s", input) - output, err := conn.DescribeCachediSCSIVolumes(ctx, input) - - if err != nil { - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) || errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - log.Printf("[WARN] Storage Gateway cached iSCSI volume %q not found, removing from state", d.Id()) - d.SetId("") - return diags - } - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway cached iSCSI volume %q: %s", d.Id(), err) - } - - if output == nil || len(output.CachediSCSIVolumes) == 0 || aws.ToString(output.CachediSCSIVolumes[0].VolumeARN) != d.Id() { - log.Printf("[WARN] Storage Gateway cached iSCSI volume %q not found, removing from state", d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Storage Gateway Cached iSCSI Volume (%s) not found, removing from state", d.Id()) d.SetId("") return diags } - volume := output.CachediSCSIVolumes[0] + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Cached iSCSI Volume (%s): %s", d.Id(), err) + } arn := aws.ToString(volume.VolumeARN) d.Set(names.AttrARN, arn) - d.Set(names.AttrSnapshotID, volume.SourceSnapshotId) - d.Set("volume_arn", arn) - d.Set("volume_id", volume.VolumeId) - d.Set("volume_size_in_bytes", volume.VolumeSizeInBytes) d.Set(names.AttrKMSKey, volume.KMSKey) if volume.KMSKey != nil { d.Set("kms_encrypted", true) } else { d.Set("kms_encrypted", false) } + d.Set(names.AttrSnapshotID, volume.SourceSnapshotId) + d.Set("volume_arn", arn) + d.Set("volume_id", volume.VolumeId) + d.Set("volume_size_in_bytes", volume.VolumeSizeInBytes) if volume.VolumeiSCSIAttributes != nil { d.Set("chap_enabled", volume.VolumeiSCSIAttributes.ChapEnabled) @@ -215,7 +201,7 @@ func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, gatewayARN, targetName, err := parseVolumeGatewayARNAndTargetNameFromARN(targetARN) if err != nil { - return sdkdiag.AppendErrorf(diags, "parsing Storage Gateway volume gateway ARN and target name from target ARN %q: %s", targetARN, err) + return sdkdiag.AppendFromErr(diags, err) } d.Set("gateway_arn", gatewayARN) d.Set("target_name", targetName) @@ -236,37 +222,77 @@ func resourceCachediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DeleteVolumeInput{ - VolumeARN: aws.String(d.Id()), + log.Printf("[DEBUG] Deleting Storage Gateway Cached iSCSI Volume: %s", d.Id()) + const ( + timeout = 2 * time.Minute + ) + _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](ctx, timeout, func() (interface{}, error) { + return conn.DeleteVolume(ctx, &storagegateway.DeleteVolumeInput{ + VolumeARN: aws.String(d.Id()), + }) + }, "The specified gateway is not connected") + + if isVolumeNotFoundErr(err) { + return diags } - log.Printf("[DEBUG] Deleting Storage Gateway cached iSCSI volume: %#v", input) - err := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { - _, err := conn.DeleteVolume(ctx, input) - if err != nil { - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { - return nil - } - // InvalidGatewayRequestException: The specified gateway is not connected. - // Can occur during concurrent DeleteVolume operations - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { - return retry.RetryableError(err) - } - return retry.NonRetryableError(err) + if err != nil { + return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway cached iSCSI volume %q: %s", d.Id(), err) + } + + return diags +} + +func findCachediSCSIVolumeByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.CachediSCSIVolume, error) { + input := &storagegateway.DescribeCachediSCSIVolumesInput{ + VolumeARNs: []string{arn}, + } + output, err := findCachediSCSIVolume(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.VolumeARN) != arn { + return nil, &retry.NotFoundError{ + LastRequest: input, } - return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.DeleteVolume(ctx, input) } - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - return diags + + return output, nil + +} + +func findCachediSCSIVolume(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeCachediSCSIVolumesInput) (*awstypes.CachediSCSIVolume, error) { + output, err := findCachediSCSIVolumes(ctx, conn, input) + + if err != nil { + return nil, err } + + return tfresource.AssertSingleValueResult(output) +} + +func findCachediSCSIVolumes(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeCachediSCSIVolumesInput) ([]awstypes.CachediSCSIVolume, error) { + output, err := conn.DescribeCachediSCSIVolumes(ctx, input) + + if isVolumeNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway cached iSCSI volume %q: %s", d.Id(), err) + return nil, err } - return diags + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.CachediSCSIVolumes, err } func parseVolumeGatewayARNAndTargetNameFromARN(inputARN string) (string, string, error) { diff --git a/internal/service/storagegateway/cached_iscsi_volume_test.go b/internal/service/storagegateway/cached_iscsi_volume_test.go index d401b97789da..ac44748848b8 100644 --- a/internal/service/storagegateway/cached_iscsi_volume_test.go +++ b/internal/service/storagegateway/cached_iscsi_volume_test.go @@ -9,17 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" 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" tfstoragegateway "github.com/hashicorp/terraform-provider-aws/internal/service/storagegateway" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -303,30 +300,22 @@ func TestAccStorageGatewayCachediSCSIVolume_disappears(t *testing.T) { }) } -func testAccCheckCachediSCSIVolumeExists(ctx context.Context, resourceName string, cachedIscsiVolume *awstypes.CachediSCSIVolume) resource.TestCheckFunc { +func testAccCheckCachediSCSIVolumeExists(ctx context.Context, n string, v *awstypes.CachediSCSIVolume) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DescribeCachediSCSIVolumesInput{ - VolumeARNs: []string{rs.Primary.ID}, - } - - output, err := conn.DescribeCachediSCSIVolumes(ctx, input) + output, err := tfstoragegateway.FindCachediSCSIVolumeByARN(ctx, conn, rs.Primary.ID) if err != nil { - return fmt.Errorf("error reading Storage Gateway cached iSCSI volume: %s", err) - } - - if output == nil || len(output.CachediSCSIVolumes) == 0 || aws.ToString(output.CachediSCSIVolumes[0].VolumeARN) != rs.Primary.ID { - return fmt.Errorf("Storage Gateway cached iSCSI volume %q not found", rs.Primary.ID) + return err } - *cachedIscsiVolume = output.CachediSCSIVolumes[0] + *v = *output return nil } @@ -341,28 +330,17 @@ func testAccCheckCachediSCSIVolumeDestroy(ctx context.Context) resource.TestChec continue } - input := &storagegateway.DescribeCachediSCSIVolumesInput{ - VolumeARNs: []string{rs.Primary.ID}, - } + _, err := tfstoragegateway.FindCachediSCSIVolumeByARN(ctx, conn, rs.Primary.ID) - output, err := conn.DescribeCachediSCSIVolumes(ctx, input) + if tfresource.NotFound(err) { + continue + } if err != nil { - if tfstoragegateway.IsGatewayNotFoundErr(err) { - return nil - } - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { - return nil - } - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - return nil - } return err } - if output != nil && len(output.CachediSCSIVolumes) > 0 && aws.ToString(output.CachediSCSIVolumes[0].VolumeARN) == rs.Primary.ID { - return fmt.Errorf("Storage Gateway cached iSCSI volume %q still exists", rs.Primary.ID) - } + return fmt.Errorf("Storage Gateway Cached iSCSI Volume %s still exists", rs.Primary.ID) } return nil diff --git a/internal/service/storagegateway/errors.go b/internal/service/storagegateway/errors.go index 2cef28daf739..118592a3085b 100644 --- a/internal/service/storagegateway/errors.go +++ b/internal/service/storagegateway/errors.go @@ -18,7 +18,7 @@ const ( ) // operationErrorCode returns the operation error code from the specified error: -// - err is of type awserr.Error and represents a storagegateway.InternalServerError or storagegateway.InvalidGatewayRequestException +// - err represents an InternalServerError or InvalidGatewayRequestException // - Error_ is not nil // // See https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIErrorResponses for details. @@ -36,7 +36,7 @@ func operationErrorCode(err error) string { // The API returns multiple responses for a missing gateway. func isGatewayNotFoundErr(err error) bool { - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found.") { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found") { return true } @@ -46,3 +46,16 @@ func isGatewayNotFoundErr(err error) bool { return false } + +// The API returns multiple responses for a missing volume. +func isVolumeNotFoundErr(err error) bool { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { + return true + } + + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { + return true + } + + return false +} diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index 7cde4b55143b..772480d00687 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -16,6 +16,7 @@ var ( ResourceUploadBuffer = resourceUploadBuffer FindCacheByTwoPartKey = findCacheByTwoPartKey + FindCachediSCSIVolumeByARN = findCachediSCSIVolumeByARN FindFileSystemAssociationByARN = findFileSystemAssociationByARN FindGatewayByARN = findGatewayByARN FindNFSFileShareByARN = findNFSFileShareByARN From 6a680d5a2cb0ba5ef38eb75fd0a2186ce1c338d7 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sun, 28 Jul 2024 18:39:36 -0400 Subject: [PATCH 27/39] r/aws_storagegateway_file_system_association: Cosmetics. --- .../storagegateway/file_system_association.go | 141 +++++++++++++++--- .../file_system_association_test.go | 6 +- internal/service/storagegateway/find.go | 29 ---- internal/service/storagegateway/status.go | 16 -- internal/service/storagegateway/wait.go | 37 ----- 5 files changed, 124 insertions(+), 105 deletions(-) diff --git a/internal/service/storagegateway/file_system_association.go b/internal/service/storagegateway/file_system_association.go index c37d11f5bf79..4e6993f1edb6 100644 --- a/internal/service/storagegateway/file_system_association.go +++ b/internal/service/storagegateway/file_system_association.go @@ -5,7 +5,9 @@ package storagegateway import ( "context" + "errors" "log" + "time" "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" @@ -14,10 +16,12 @@ import ( "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/id" + "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/errs/sdkdiag" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -159,12 +163,11 @@ func resourceFileSystemAssociationRead(ctx context.Context, d *schema.ResourceDa d.Set(names.AttrARN, filesystem.FileSystemAssociationARN) d.Set("audit_destination_arn", filesystem.AuditDestinationARN) - d.Set("gateway_arn", filesystem.GatewayARN) - d.Set("location_arn", filesystem.LocationARN) - if err := d.Set("cache_attributes", flattenFileSystemAssociationCacheAttributes(filesystem.CacheAttributes)); err != nil { return sdkdiag.AppendErrorf(diags, "setting cache_attributes: %s", err) } + d.Set("gateway_arn", filesystem.GatewayARN) + d.Set("location_arn", filesystem.LocationARN) setTagsOut(ctx, filesystem.Tags) @@ -178,9 +181,9 @@ func resourceFileSystemAssociationUpdate(ctx context.Context, d *schema.Resource if d.HasChangesExcept(names.AttrTagsAll) { input := &storagegateway.UpdateFileSystemAssociationInput{ AuditDestinationARN: aws.String(d.Get("audit_destination_arn").(string)), + FileSystemAssociationARN: aws.String(d.Id()), Password: aws.String(d.Get(names.AttrPassword).(string)), UserName: aws.String(d.Get(names.AttrUsername).(string)), - FileSystemAssociationARN: aws.String(d.Id()), } if v, ok := d.GetOk("cache_attributes"); ok { @@ -205,12 +208,10 @@ func resourceFileSystemAssociationDelete(ctx context.Context, d *schema.Resource var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DisassociateFileSystemInput{ + log.Printf("[DEBUG] Deleting Storage Gateway File System Association: %s", d.Id()) + _, err := conn.DisassociateFileSystem(ctx, &storagegateway.DisassociateFileSystemInput{ FileSystemAssociationARN: aws.String(d.Id()), - } - - log.Printf("[DEBUG] Deleting Storage Gateway File System Association: %#v", input) - _, err := conn.DisassociateFileSystem(ctx, input) + }) if operationErrorCode(err) == operationErrCodeFileSystemAssociationNotFound { return diags @@ -227,28 +228,128 @@ func resourceFileSystemAssociationDelete(ctx context.Context, d *schema.Resource return diags } -func expandFileSystemAssociationCacheAttributes(l []interface{}) *awstypes.CacheAttributes { - if len(l) == 0 || l[0] == nil { +func findFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.FileSystemAssociationInfo, error) { + input := &storagegateway.DescribeFileSystemAssociationsInput{ + FileSystemAssociationARNList: []string{arn}, + } + + return findFileSystemAssociation(ctx, conn, input) +} + +func findFileSystemAssociation(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeFileSystemAssociationsInput) (*awstypes.FileSystemAssociationInfo, error) { + output, err := findFileSystemAssociations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findFileSystemAssociations(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeFileSystemAssociationsInput) ([]awstypes.FileSystemAssociationInfo, error) { + output, err := conn.DescribeFileSystemAssociations(ctx, input) + + if operationErrorCode(err) == operationErrCodeFileSystemAssociationNotFound { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.FileSystemAssociationInfoList, err +} + +func statusFileSystemAssociation(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findFileSystemAssociationByARN(ctx, conn, arn) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.ToString(output.FileSystemAssociationStatus), nil + } +} + +func waitFileSystemAssociationAvailable(ctx context.Context, conn *storagegateway.Client, fileSystemArn string, timeout time.Duration) (*awstypes.FileSystemAssociationInfo, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: []string{fileSystemAssociationStatusCreating, fileSystemAssociationStatusUpdating}, + Target: []string{fileSystemAssociationStatusAvailable}, + Refresh: statusFileSystemAssociation(ctx, conn, fileSystemArn), + Timeout: timeout, + Delay: fileSystemAssociationAvailableDelay, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.FileSystemAssociationInfo); ok { + tfresource.SetLastError(err, errors.Join(tfslices.ApplyToAll(output.FileSystemAssociationStatusDetails, fileSystemAssociationStatusDetailError)...)) + + return output, err + } + + return nil, err +} + +func waitFileSystemAssociationDeleted(ctx context.Context, conn *storagegateway.Client, fileSystemArn string, timeout time.Duration) (*awstypes.FileSystemAssociationInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileSystemAssociationStatusAvailable, fileSystemAssociationStatusDeleting, fileSystemAssociationStatusForceDeleting}, + Target: []string{}, + Refresh: statusFileSystemAssociation(ctx, conn, fileSystemArn), + Timeout: timeout, + Delay: fileSystemAssociationDeletedDelay, + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.FileSystemAssociationInfo); ok { + tfresource.SetLastError(err, errors.Join(tfslices.ApplyToAll(output.FileSystemAssociationStatusDetails, fileSystemAssociationStatusDetailError)...)) + + return output, err + } + + return nil, err +} + +func fileSystemAssociationStatusDetailError(v awstypes.FileSystemAssociationStatusDetail) error { + return errors.New(aws.ToString(v.ErrorCode)) +} + +func expandFileSystemAssociationCacheAttributes(tfList []interface{}) *awstypes.CacheAttributes { + if len(tfList) == 0 || tfList[0] == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := tfList[0].(map[string]interface{}) - ca := &awstypes.CacheAttributes{ - CacheStaleTimeoutInSeconds: aws.Int32(int32(m["cache_stale_timeout_in_seconds"].(int))), + apiObject := &awstypes.CacheAttributes{ + CacheStaleTimeoutInSeconds: aws.Int32(int32(tfMap["cache_stale_timeout_in_seconds"].(int))), } - return ca + return apiObject } -func flattenFileSystemAssociationCacheAttributes(ca *awstypes.CacheAttributes) []interface{} { - if ca == nil { +func flattenFileSystemAssociationCacheAttributes(apiObject *awstypes.CacheAttributes) []interface{} { + if apiObject == nil { return []interface{}{} } - m := map[string]interface{}{ - "cache_stale_timeout_in_seconds": aws.ToInt32(ca.CacheStaleTimeoutInSeconds), + tfMap := map[string]interface{}{ + "cache_stale_timeout_in_seconds": aws.ToInt32(apiObject.CacheStaleTimeoutInSeconds), } - return []interface{}{m} + return []interface{}{tfMap} } diff --git a/internal/service/storagegateway/file_system_association_test.go b/internal/service/storagegateway/file_system_association_test.go index 7c93b5857a7e..784cf8c6e894 100644 --- a/internal/service/storagegateway/file_system_association_test.go +++ b/internal/service/storagegateway/file_system_association_test.go @@ -304,11 +304,11 @@ func testAccCheckFileSystemAssociationDestroy(ctx context.Context) resource.Test } } -func testAccCheckFileSystemAssociationExists(ctx context.Context, resourceName string, v *awstypes.FileSystemAssociationInfo) resource.TestCheckFunc { +func testAccCheckFileSystemAssociationExists(ctx context.Context, n string, v *awstypes.FileSystemAssociationInfo) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go index 931b38f786c1..7f2029577a00 100644 --- a/internal/service/storagegateway/find.go +++ b/internal/service/storagegateway/find.go @@ -168,32 +168,3 @@ func findSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn return &output.SMBFileShareInfoList[0], nil } - -func findFileSystemAssociationByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.FileSystemAssociationInfo, error) { - input := &storagegateway.DescribeFileSystemAssociationsInput{ - FileSystemAssociationARNList: []string{arn}, - } - - output, err := conn.DescribeFileSystemAssociations(ctx, input) - - if operationErrorCode(err) == operationErrCodeFileSystemAssociationNotFound { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || len(output.FileSystemAssociationInfoList) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - if count := len(output.FileSystemAssociationInfoList); count > 1 { - return nil, tfresource.NewTooManyResultsError(count, input) - } - - return &output.FileSystemAssociationInfoList[0], nil -} diff --git a/internal/service/storagegateway/status.go b/internal/service/storagegateway/status.go index 4d55a504d69c..1a43b81d4971 100644 --- a/internal/service/storagegateway/status.go +++ b/internal/service/storagegateway/status.go @@ -117,19 +117,3 @@ func statusSMBFileShare(ctx context.Context, conn *storagegateway.Client, arn st return output, aws.ToString(output.FileShareStatus), nil } } - -func statusFileSystemAssociation(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findFileSystemAssociationByARN(ctx, conn, arn) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output.FileSystemAssociationStatus), nil - } -} diff --git a/internal/service/storagegateway/wait.go b/internal/service/storagegateway/wait.go index aed236d0e544..60c27f5dd8de 100644 --- a/internal/service/storagegateway/wait.go +++ b/internal/service/storagegateway/wait.go @@ -190,40 +190,3 @@ func waitSMBFileShareUpdated(ctx context.Context, conn *storagegateway.Client, a return nil, err } - -func waitFileSystemAssociationAvailable(ctx context.Context, conn *storagegateway.Client, fileSystemArn string, timeout time.Duration) (*awstypes.FileSystemAssociationInfo, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: []string{fileSystemAssociationStatusCreating, fileSystemAssociationStatusUpdating}, - Target: []string{fileSystemAssociationStatusAvailable}, - Refresh: statusFileSystemAssociation(ctx, conn, fileSystemArn), - Timeout: timeout, - Delay: fileSystemAssociationAvailableDelay, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.FileSystemAssociationInfo); ok { - return output, err - } - - return nil, err -} - -func waitFileSystemAssociationDeleted(ctx context.Context, conn *storagegateway.Client, fileSystemArn string, timeout time.Duration) (*awstypes.FileSystemAssociationInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileSystemAssociationStatusAvailable, fileSystemAssociationStatusDeleting, fileSystemAssociationStatusForceDeleting}, - Target: []string{}, - Refresh: statusFileSystemAssociation(ctx, conn, fileSystemArn), - Timeout: timeout, - Delay: fileSystemAssociationDeletedDelay, - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.FileSystemAssociationInfo); ok { - return output, err - } - - return nil, err -} From 450041e29ab339a17197779cb6ce2da3a0295757 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 29 Jul 2024 09:51:04 -0400 Subject: [PATCH 28/39] r/aws_storagegateway_gateway: Cosmetics. --- internal/service/storagegateway/errors.go | 6 +- .../storagegateway/file_system_association.go | 4 +- internal/service/storagegateway/find.go | 26 - internal/service/storagegateway/gateway.go | 454 +++++++++++------- .../service/storagegateway/gateway_test.go | 8 +- internal/service/storagegateway/status.go | 41 -- internal/service/storagegateway/wait.go | 53 +- 7 files changed, 289 insertions(+), 303 deletions(-) diff --git a/internal/service/storagegateway/errors.go b/internal/service/storagegateway/errors.go index 118592a3085b..4748a913f570 100644 --- a/internal/service/storagegateway/errors.go +++ b/internal/service/storagegateway/errors.go @@ -36,7 +36,7 @@ func operationErrorCode(err error) string { // The API returns multiple responses for a missing gateway. func isGatewayNotFoundErr(err error) bool { - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found") { + if operationErrorCode(err) == operationErrCodeGatewayNotFound { return true } @@ -44,6 +44,10 @@ func isGatewayNotFoundErr(err error) bool { return true } + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway was not found") { + return true + } + return false } diff --git a/internal/service/storagegateway/file_system_association.go b/internal/service/storagegateway/file_system_association.go index 4e6993f1edb6..edcb2733e966 100644 --- a/internal/service/storagegateway/file_system_association.go +++ b/internal/service/storagegateway/file_system_association.go @@ -289,7 +289,7 @@ func waitFileSystemAssociationAvailable(ctx context.Context, conn *storagegatewa Target: []string{fileSystemAssociationStatusAvailable}, Refresh: statusFileSystemAssociation(ctx, conn, fileSystemArn), Timeout: timeout, - Delay: fileSystemAssociationAvailableDelay, + Delay: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) @@ -309,7 +309,7 @@ func waitFileSystemAssociationDeleted(ctx context.Context, conn *storagegateway. Target: []string{}, Refresh: statusFileSystemAssociation(ctx, conn, fileSystemArn), Timeout: timeout, - Delay: fileSystemAssociationDeletedDelay, + Delay: 5 * time.Second, NotFoundChecks: 1, } diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go index 7f2029577a00..b2651710f75e 100644 --- a/internal/service/storagegateway/find.go +++ b/internal/service/storagegateway/find.go @@ -9,7 +9,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -86,31 +85,6 @@ func findUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gate return &result, err } -func findGatewayByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*storagegateway.DescribeGatewayInformationOutput, error) { - input := &storagegateway.DescribeGatewayInformationInput{ - GatewayARN: aws.String(arn), - } - - output, err := conn.DescribeGatewayInformation(ctx, input) - - if operationErrorCode(err) == operationErrCodeGatewayNotFound || tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output, nil -} - func findNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.NFSFileShareInfo, error) { input := &storagegateway.DescribeNFSFileSharesInput{ FileShareARNList: []string{arn}, diff --git a/internal/service/storagegateway/gateway.go b/internal/service/storagegateway/gateway.go index 0a7972de5a7d..f3f52957fa91 100644 --- a/internal/service/storagegateway/gateway.go +++ b/internal/service/storagegateway/gateway.go @@ -9,14 +9,12 @@ import ( "log" "net" "net/http" - "strconv" "time" "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -294,15 +292,15 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int Timeout: time.Second * 10, } - requestURL := fmt.Sprintf("http://%s/?activationRegion=%s", gatewayIPAddress, region) + requestURL := fmt.Sprintf("http://%[1]s/?activationRegion=%[2]s", gatewayIPAddress, region) if v, ok := d.GetOk("gateway_vpc_endpoint"); ok { - requestURL = fmt.Sprintf("%s&vpcEndpoint=%s", requestURL, v.(string)) + requestURL = fmt.Sprintf("%[1]s&vpcEndpoint=%[2]s", requestURL, v.(string)) } - log.Printf("[DEBUG] Creating HTTP request: %s", requestURL) request, err := http.NewRequest(http.MethodGet, requestURL, nil) + if err != nil { - return sdkdiag.AppendErrorf(diags, "creating HTTP request: %s", err) + return sdkdiag.AppendFromErr(diags, err) } var response *http.Response @@ -311,7 +309,7 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int if err != nil { if errs.IsA[net.Error](err) { - errMessage := fmt.Errorf("making HTTP request: %s", err) + errMessage := fmt.Errorf("making HTTP request: %w", err) log.Printf("[DEBUG] retryable %s", errMessage) return retry.RetryableError(errMessage) } @@ -329,21 +327,23 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int return nil }) + if tfresource.TimedOut(err) { response, err = client.Do(request) } + if err != nil { return sdkdiag.AppendErrorf(diags, "retrieving activation key from IP Address (%s): %s", gatewayIPAddress, err) } - log.Printf("[DEBUG] Received HTTP response: %#v", response) if response.StatusCode != http.StatusFound { return sdkdiag.AppendErrorf(diags, "expected HTTP status code 302, received: %d", response.StatusCode) } redirectURL, err := response.Location() + if err != nil { - return sdkdiag.AppendErrorf(diags, "extracting HTTP Location header: %s", err) + return sdkdiag.AppendFromErr(diags, err) } activationKey = redirectURL.Query().Get("activationKey") @@ -352,10 +352,11 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int } } + name := d.Get("gateway_name").(string) input := &storagegateway.ActivateGatewayInput{ ActivationKey: aws.String(activationKey), GatewayRegion: aws.String(region), - GatewayName: aws.String(d.Get("gateway_name").(string)), + GatewayName: aws.String(name), GatewayTimezone: aws.String(d.Get("gateway_timezone").(string)), GatewayType: aws.String(d.Get("gateway_type").(string)), Tags: getTagsIn(ctx), @@ -369,31 +370,28 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int input.TapeDriveType = aws.String(v.(string)) } - log.Printf("[DEBUG] Activating Storage Gateway Gateway: %#v", input) output, err := conn.ActivateGateway(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "activating Storage Gateway Gateway: %s", err) + return sdkdiag.AppendErrorf(diags, "activating Storage Gateway Gateway (%s): %s", name, err) } d.SetId(aws.ToString(output.GatewayARN)) - log.Printf("[INFO] Storage Gateway Gateway ID: %s", d.Id()) - - log.Printf("[DEBUG] Waiting for Storage Gateway Gateway (%s) to be connected", d.Id()) if _, err = waitGatewayConnected(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%q) to be Connected: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%s) connect: %s", d.Id(), err) } if v, ok := d.GetOk(names.AttrCloudWatchLogGroupARN); ok && v.(string) != "" { input := &storagegateway.UpdateGatewayInformationInput{ - GatewayARN: aws.String(d.Id()), CloudWatchLogGroupARN: aws.String(v.(string)), + GatewayARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Storage Gateway Gateway %#v setting CloudWatch Log Group", input) _, err := conn.UpdateGatewayInformation(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "setting CloudWatch Log Group: %s", err) + return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) CloudWatch log group: %s", d.Id(), err) } } @@ -401,24 +399,24 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int input := expandUpdateMaintenanceStartTimeInput(v.([]interface{})[0].(map[string]interface{})) input.GatewayARN = aws.String(d.Id()) - log.Printf("[DEBUG] Storage Gateway Gateway %q updating maintenance start time", d.Id()) _, err := conn.UpdateMaintenanceStartTime(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "updating maintenance start time: %s", err) + return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) maintenance start time: %s", d.Id(), err) } } if v, ok := d.GetOk("smb_active_directory_settings"); ok && len(v.([]interface{})) > 0 { - input := expandGatewayDomain(v.([]interface{}), d.Id()) - log.Printf("[DEBUG] Storage Gateway Gateway %q joining Active Directory domain: %s", d.Id(), aws.ToString(input.DomainName)) + input := expandJoinDomainInput(v.([]interface{}), d.Id()) + _, err := conn.JoinDomain(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "joining Active Directory domain: %s", err) + return sdkdiag.AppendErrorf(diags, "joining Storage Gateway Gateway (%s) to Active Directory domain (%s): %s", d.Id(), aws.ToString(input.DomainName), err) } - log.Printf("[DEBUG] Waiting for Storage Gateway Gateway (%s) to be connected", d.Id()) + if _, err = waitGatewayJoinDomainJoined(ctx, conn, d.Id()); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%q) to join domain (%s): %s", d.Id(), aws.ToString(input.DomainName), err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%s) domain join: %s", d.Id(), err) } } @@ -428,10 +426,10 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int Password: aws.String(v.(string)), } - log.Printf("[DEBUG] Storage Gateway Gateway %q setting SMB guest password", d.Id()) _, err := conn.SetSMBGuestPassword(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "setting SMB guest password: %s", err) + return sdkdiag.AppendErrorf(diags, "setting Storage Gateway Gateway (%s) SMB guest password: %s", d.Id(), err) } } @@ -441,21 +439,21 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int SMBSecurityStrategy: awstypes.SMBSecurityStrategy(v.(string)), } - log.Printf("[DEBUG] Storage Gateway Gateway %#v setting SMB Security Strategy", input) _, err := conn.UpdateSMBSecurityStrategy(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "setting SMB Security Strategy: %s", err) + return sdkdiag.AppendErrorf(diags, "setting Storage Gateway Gateway (%s) SMB security strategy: %s", d.Id(), err) } } if v, ok := d.GetOk("smb_file_share_visibility"); ok { input := &storagegateway.UpdateSMBFileShareVisibilityInput{ - GatewayARN: aws.String(d.Id()), FileSharesVisible: aws.Bool(v.(bool)), + GatewayARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Storage Gateway Gateway %#v setting SMB File Share Visibility", input) _, err := conn.UpdateSMBFileShareVisibility(ctx, input) + if err != nil { return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) SMB file share visibility: %s", d.Id(), err) } @@ -463,23 +461,23 @@ func resourceGatewayCreate(ctx context.Context, d *schema.ResourceData, meta int switch d.Get("gateway_type").(string) { case gatewayTypeCached, gatewayTypeStored, gatewayTypeVTL, gatewayTypeVTLSnow: - bandwidthInput := &storagegateway.UpdateBandwidthRateLimitInput{ + input := &storagegateway.UpdateBandwidthRateLimitInput{ GatewayARN: aws.String(d.Id()), } if v, ok := d.GetOk("average_download_rate_limit_in_bits_per_sec"); ok { - bandwidthInput.AverageDownloadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) + input.AverageDownloadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) } if v, ok := d.GetOk("average_upload_rate_limit_in_bits_per_sec"); ok { - bandwidthInput.AverageUploadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) + input.AverageUploadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) } - if bandwidthInput.AverageDownloadRateLimitInBitsPerSec != nil || bandwidthInput.AverageUploadRateLimitInBitsPerSec != nil { - log.Printf("[DEBUG] Storage Gateway Gateway %q setting Bandwidth Rate Limit: %#v", d.Id(), bandwidthInput) - _, err := conn.UpdateBandwidthRateLimit(ctx, bandwidthInput) + if input.AverageDownloadRateLimitInBitsPerSec != nil || input.AverageUploadRateLimitInBitsPerSec != nil { + _, err := conn.UpdateBandwidthRateLimit(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "setting Bandwidth Rate Limit: %s", err) + return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) bandwidth rate limits: %s", d.Id(), err) } } } @@ -491,7 +489,7 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - output, err := findGatewayByARN(ctx, conn, d.Id()) + outputDGI, err := findGatewayByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway Gateway (%s) not found, removing from state", d.Id()) @@ -503,148 +501,111 @@ func resourceGatewayRead(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Gateway (%s): %s", d.Id(), err) } - setTagsOut(ctx, output.Tags) + outputDSS, err := findSMBSettingsByARN(ctx, conn, d.Id()) - smbSettingsInput := &storagegateway.DescribeSMBSettingsInput{ - GatewayARN: aws.String(d.Id()), - } - - log.Printf("[DEBUG] Reading Storage Gateway SMB Settings: %#v", smbSettingsInput) - smbSettingsOutput, err := conn.DescribeSMBSettings(ctx, smbSettingsInput) - if err != nil && !errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway") { - if isGatewayNotFoundErr(err) { - log.Printf("[WARN] Storage Gateway Gateway %q not found - removing from state", d.Id()) - d.SetId("") - return diags - } - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway SMB Settings: %s", err) + switch { + case errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway"): + case err != nil: + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Gateway (%s) SMB settings: %s", d.Id(), err) } - // The Storage Gateway API currently provides no way to read this value - // We allow Terraform to passthrough the configuration value into the state d.Set("activation_key", d.Get("activation_key").(string)) - - d.Set(names.AttrARN, output.GatewayARN) - d.Set("gateway_id", output.GatewayId) - - // The Storage Gateway API currently provides no way to read this value - // We allow Terraform to passthrough the configuration value into the state + d.Set(names.AttrARN, outputDGI.GatewayARN) + d.Set(names.AttrCloudWatchLogGroupARN, outputDGI.CloudWatchLogGroupARN) + d.Set("ec2_instance_id", outputDGI.Ec2InstanceId) + d.Set(names.AttrEndpointType, outputDGI.EndpointType) + d.Set("gateway_id", outputDGI.GatewayId) d.Set("gateway_ip_address", d.Get("gateway_ip_address").(string)) - - d.Set("gateway_name", output.GatewayName) - d.Set("gateway_timezone", output.GatewayTimezone) - d.Set("gateway_type", output.GatewayType) - d.Set("gateway_vpc_endpoint", output.VPCEndpoint) - - // The Storage Gateway API currently provides no way to read this value - // We allow Terraform to passthrough the configuration value into the state + d.Set("gateway_name", outputDGI.GatewayName) + if err := d.Set("gateway_network_interface", flattenNetworkInterfaces(outputDGI.GatewayNetworkInterfaces)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting gateway_network_interface: %s", err) + } + d.Set("gateway_timezone", outputDGI.GatewayTimezone) + d.Set("gateway_type", outputDGI.GatewayType) + d.Set("gateway_vpc_endpoint", outputDGI.VPCEndpoint) + d.Set("host_environment", outputDGI.HostEnvironment) d.Set("medium_changer_type", d.Get("medium_changer_type").(string)) - - // Treat the entire nested argument as a whole, based on domain name - // to simplify schema and difference logic - if smbSettingsOutput == nil || aws.ToString(smbSettingsOutput.DomainName) == "" { + if outputDSS == nil || aws.ToString(outputDSS.DomainName) == "" { if err := d.Set("smb_active_directory_settings", []interface{}{}); err != nil { return sdkdiag.AppendErrorf(diags, "setting smb_active_directory_settings: %s", err) } } else { - m := map[string]interface{}{ - names.AttrDomainName: aws.ToString(smbSettingsOutput.DomainName), - "active_directory_status": smbSettingsOutput.ActiveDirectoryStatus, - // The Storage Gateway API currently provides no way to read these values - // "password": ..., - // "username": ..., - } - // We must assemble these into the map from configuration or Terraform will enter "" - // into state and constantly show a difference (also breaking downstream references) - // UPDATE: aws_storagegateway_gateway.test - // smb_active_directory_settings.0.password: "" => "" (attribute changed) - // smb_active_directory_settings.0.username: "" => "Administrator" + tfMap := map[string]interface{}{ + "active_directory_status": outputDSS.ActiveDirectoryStatus, + names.AttrDomainName: aws.ToString(outputDSS.DomainName), + } + if v, ok := d.GetOk("smb_active_directory_settings"); ok && len(v.([]interface{})) > 0 { configM := v.([]interface{})[0].(map[string]interface{}) - m[names.AttrPassword] = configM[names.AttrPassword] - m[names.AttrUsername] = configM[names.AttrUsername] - m["timeout_in_seconds"] = configM["timeout_in_seconds"] + tfMap[names.AttrPassword] = configM[names.AttrPassword] + tfMap["timeout_in_seconds"] = configM["timeout_in_seconds"] + tfMap[names.AttrUsername] = configM[names.AttrUsername] - if v, ok := configM["organizational_unit"]; ok { - m["organizational_unit"] = v + if v, ok := configM["domain_controllers"]; ok { + tfMap["domain_controllers"] = v } - if v, ok := configM["domain_controllers"]; ok { - m["domain_controllers"] = v + if v, ok := configM["organizational_unit"]; ok { + tfMap["organizational_unit"] = v } } - if err := d.Set("smb_active_directory_settings", []map[string]interface{}{m}); err != nil { + + if err := d.Set("smb_active_directory_settings", []map[string]interface{}{tfMap}); err != nil { return sdkdiag.AppendErrorf(diags, "setting smb_active_directory_settings: %s", err) } } - // The Storage Gateway API currently provides no way to read this value // We allow Terraform to _automatically_ passthrough the configuration value into the state here // as the API does clue us in whether or not its actually set at all, // which can be used to tell Terraform to show a difference in this case - // as well as ensuring there is some sort of attribute value (unlike the others) - if smbSettingsOutput == nil || !aws.ToBool(smbSettingsOutput.SMBGuestPasswordSet) { + // as well as ensuring there is some sort of attribute value (unlike the others). + if outputDSS == nil || !aws.ToBool(outputDSS.SMBGuestPasswordSet) { d.Set("smb_guest_password", "") } - - // The Storage Gateway API currently provides no way to read this value - // We allow Terraform to passthrough the configuration value into the state - d.Set("tape_drive_type", d.Get("tape_drive_type").(string)) - d.Set(names.AttrCloudWatchLogGroupARN, output.CloudWatchLogGroupARN) - - if smbSettingsOutput != nil { - d.Set("smb_security_strategy", smbSettingsOutput.SMBSecurityStrategy) - d.Set("smb_file_share_visibility", smbSettingsOutput.FileSharesVisible) + if outputDSS != nil { + d.Set("smb_file_share_visibility", outputDSS.FileSharesVisible) + d.Set("smb_security_strategy", outputDSS.SMBSecurityStrategy) } + d.Set("tape_drive_type", d.Get("tape_drive_type").(string)) - d.Set("ec2_instance_id", output.Ec2InstanceId) - d.Set(names.AttrEndpointType, output.EndpointType) - d.Set("host_environment", output.HostEnvironment) - - if err := d.Set("gateway_network_interface", flattenGatewayNetworkInterfaces(output.GatewayNetworkInterfaces)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting gateway_network_interface: %s", err) - } + setTagsOut(ctx, outputDGI.Tags) - switch aws.ToString(output.GatewayType) { + switch aws.ToString(outputDGI.GatewayType) { case gatewayTypeCached, gatewayTypeStored, gatewayTypeVTL, gatewayTypeVTLSnow: - bandwidthOutput, err := conn.DescribeBandwidthRateLimit(ctx, &storagegateway.DescribeBandwidthRateLimitInput{ + input := &storagegateway.DescribeBandwidthRateLimitInput{ GatewayARN: aws.String(d.Id()), - }) - - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "not supported") || - errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "not valid") { - err = nil } - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Bandwidth rate limit: %s", err) - } + outputDBRL, err := conn.DescribeBandwidthRateLimit(ctx, input) - if bandwidthOutput != nil { - d.Set("average_download_rate_limit_in_bits_per_sec", bandwidthOutput.AverageDownloadRateLimitInBitsPerSec) - d.Set("average_upload_rate_limit_in_bits_per_sec", bandwidthOutput.AverageUploadRateLimitInBitsPerSec) + switch { + case errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "not supported"): + case errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "not valid"): + case err != nil: + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Gateway (%s) bandwidth rate limits: %s", d.Id(), err) + default: + d.Set("average_download_rate_limit_in_bits_per_sec", outputDBRL.AverageDownloadRateLimitInBitsPerSec) + d.Set("average_upload_rate_limit_in_bits_per_sec", outputDBRL.AverageUploadRateLimitInBitsPerSec) } } - maintenanceStartTimeOutput, err := conn.DescribeMaintenanceStartTime(ctx, &storagegateway.DescribeMaintenanceStartTimeInput{ + input := &storagegateway.DescribeMaintenanceStartTimeInput{ GatewayARN: aws.String(d.Id()), - }) - - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified operation is not supported") || - errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway") { - err = nil } - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway maintenance start time: %s", err) - } + outputDMST, err := conn.DescribeMaintenanceStartTime(ctx, input) - if maintenanceStartTimeOutput != nil { - if err := d.Set("maintenance_start_time", []map[string]interface{}{flattenDescribeMaintenanceStartTimeOutput(maintenanceStartTimeOutput)}); err != nil { + switch { + case errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified operation is not supported"): + fallthrough + case errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "This operation is not valid for the specified gateway"): + d.Set("maintenance_start_time", nil) + case err != nil: + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Gateway (%s) maintenance start time: %s", d.Id(), err) + default: + if err := d.Set("maintenance_start_time", []map[string]interface{}{flattenDescribeMaintenanceStartTimeOutput(outputDMST)}); err != nil { return sdkdiag.AppendErrorf(diags, "setting maintenance_start_time: %s", err) } - } else { - d.Set("maintenance_start_time", nil) } return diags @@ -654,7 +615,7 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - if d.HasChanges("gateway_name", "gateway_timezone", names.AttrCloudWatchLogGroupARN) { + if d.HasChanges(names.AttrCloudWatchLogGroupARN, "gateway_name", "gateway_timezone") { input := &storagegateway.UpdateGatewayInformationInput{ CloudWatchLogGroupARN: aws.String(d.Get(names.AttrCloudWatchLogGroupARN).(string)), GatewayARN: aws.String(d.Id()), @@ -662,7 +623,6 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int GatewayTimezone: aws.String(d.Get("gateway_timezone").(string)), } - log.Printf("[DEBUG] Updating Storage Gateway Gateway: %#v", input) _, err := conn.UpdateGatewayInformation(ctx, input) if err != nil { @@ -675,7 +635,6 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int input := expandUpdateMaintenanceStartTimeInput(v.([]interface{})[0].(map[string]interface{})) input.GatewayARN = aws.String(d.Id()) - log.Printf("[DEBUG] Updating Storage Gateway maintenance start time: %#v", input) _, err := conn.UpdateMaintenanceStartTime(ctx, input) if err != nil { @@ -685,17 +644,16 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int } if d.HasChange("smb_active_directory_settings") { - input := expandGatewayDomain(d.Get("smb_active_directory_settings").([]interface{}), d.Id()) - domainName := aws.ToString(input.DomainName) + input := expandJoinDomainInput(d.Get("smb_active_directory_settings").([]interface{}), d.Id()) _, err := conn.JoinDomain(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "joining Storage Gateway Gateway (%s) to Active Directory domain (%s): %s", d.Id(), domainName, err) + return sdkdiag.AppendErrorf(diags, "joining Storage Gateway Gateway (%s) to Active Directory domain (%s): %s", d.Id(), aws.ToString(input.DomainName), err) } if _, err = waitGatewayJoinDomainJoined(ctx, conn, d.Id()); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%s) to join Active Directory domain (%s): %s", d.Id(), domainName, err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Gateway (%s) domain join: %s", d.Id(), err) } } @@ -708,7 +666,7 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int _, err := conn.SetSMBGuestPassword(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) SMB guest password: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "setting Storage Gateway Gateway (%s) SMB guest password: %s", d.Id(), err) } } @@ -718,7 +676,6 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int SMBSecurityStrategy: awstypes.SMBSecurityStrategy(d.Get("smb_security_strategy").(string)), } - log.Printf("[DEBUG] Updating Storage Gateway SMB security strategy: %#v", input) _, err := conn.UpdateSMBSecurityStrategy(ctx, input) if err != nil { @@ -732,7 +689,6 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int GatewayARN: aws.String(d.Id()), } - log.Printf("[DEBUG] Updating Storage Gateway SMB file share visibility: %#v", input) _, err := conn.UpdateSMBFileShareVisibility(ctx, input) if err != nil { @@ -741,50 +697,48 @@ func resourceGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta int } if d.HasChanges("average_download_rate_limit_in_bits_per_sec", "average_upload_rate_limit_in_bits_per_sec") { - deleteInput := &storagegateway.DeleteBandwidthRateLimitInput{ + inputD := &storagegateway.DeleteBandwidthRateLimitInput{ GatewayARN: aws.String(d.Id()), } - updateInput := &storagegateway.UpdateBandwidthRateLimitInput{ + needsDelete := false + inputU := &storagegateway.UpdateBandwidthRateLimitInput{ GatewayARN: aws.String(d.Id()), } - needsDelete := false needsUpdate := false if v, ok := d.GetOk("average_download_rate_limit_in_bits_per_sec"); ok { - updateInput.AverageDownloadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) + inputU.AverageDownloadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) needsUpdate = true } else if d.HasChange("average_download_rate_limit_in_bits_per_sec") { - deleteInput.BandwidthType = aws.String(bandwidthTypeDownload) + inputD.BandwidthType = aws.String(bandwidthTypeDownload) needsDelete = true } if v, ok := d.GetOk("average_upload_rate_limit_in_bits_per_sec"); ok { - updateInput.AverageUploadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) + inputU.AverageUploadRateLimitInBitsPerSec = aws.Int64(int64(v.(int))) needsUpdate = true } else if d.HasChange("average_upload_rate_limit_in_bits_per_sec") { if needsDelete { - deleteInput.BandwidthType = aws.String(bandwidthTypeAll) + inputD.BandwidthType = aws.String(bandwidthTypeAll) } else { - deleteInput.BandwidthType = aws.String(bandwidthTypeUpload) + inputD.BandwidthType = aws.String(bandwidthTypeUpload) needsDelete = true } } if needsUpdate { - log.Printf("[DEBUG] Updating Storage Gateway bandwidth rate limit: %#v", updateInput) - _, err := conn.UpdateBandwidthRateLimit(ctx, updateInput) + _, err := conn.UpdateBandwidthRateLimit(ctx, inputU) if err != nil { - return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) bandwidth rate limit: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "updating Storage Gateway Gateway (%s) bandwidth rate limits: %s", d.Id(), err) } } if needsDelete { - log.Printf("[DEBUG] Deleting Storage Gateway bandwidth rate limit: %#v", deleteInput) - _, err := conn.DeleteBandwidthRateLimit(ctx, deleteInput) + _, err := conn.DeleteBandwidthRateLimit(ctx, inputD) if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Gateway (%s) bandwidth rate limit: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Gateway (%s) bandwidth rate limits: %s", d.Id(), err) } } } @@ -801,7 +755,7 @@ func resourceGatewayDelete(ctx context.Context, d *schema.ResourceData, meta int GatewayARN: aws.String(d.Id()), }) - if operationErrorCode(err) == operationErrCodeGatewayNotFound || tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeGatewayNotFound)) { + if isGatewayNotFoundErr(err) { return diags } @@ -812,45 +766,183 @@ func resourceGatewayDelete(ctx context.Context, d *schema.ResourceData, meta int return diags } -func expandGatewayDomain(l []interface{}, gatewayArn string) *storagegateway.JoinDomainInput { - if l == nil || l[0] == nil { +func findGatewayByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*storagegateway.DescribeGatewayInformationOutput, error) { + input := &storagegateway.DescribeGatewayInformationInput{ + GatewayARN: aws.String(arn), + } + + return findGateway(ctx, conn, input) +} + +func findGateway(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeGatewayInformationInput) (*storagegateway.DescribeGatewayInformationOutput, error) { + output, err := conn.DescribeGatewayInformation(ctx, input) + + if isGatewayNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +func findSMBSettingsByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*storagegateway.DescribeSMBSettingsOutput, error) { + input := &storagegateway.DescribeSMBSettingsInput{ + GatewayARN: aws.String(arn), + } + + return findSMBSettings(ctx, conn, input) +} + +func findSMBSettings(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeSMBSettingsInput) (*storagegateway.DescribeSMBSettingsOutput, error) { + output, err := conn.DescribeSMBSettings(ctx, input) + + if isGatewayNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +const ( + gatewayStatusConnected = "GatewayConnected" + gatewayStatusNotConnected = "GatewayNotConnected" +) + +func statusGatewayConnected(ctx context.Context, conn *storagegateway.Client, gatewayARN string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findGatewayByARN(ctx, conn, gatewayARN) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { + return output, gatewayStatusNotConnected, nil + } + + if err != nil { + return output, "", err + } + + return output, gatewayStatusConnected, nil + } +} + +func statusGatewayJoinDomain(ctx context.Context, conn *storagegateway.Client, gatewayARN string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findSMBSettingsByARN(ctx, conn, gatewayARN) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return output, "", err + } + + return output, string(output.ActiveDirectoryStatus), nil + } +} + +func waitGatewayConnected(ctx context.Context, conn *storagegateway.Client, gatewayARN string, timeout time.Duration) (*storagegateway.DescribeGatewayInformationOutput, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{gatewayStatusNotConnected}, + Target: []string{gatewayStatusConnected}, + Refresh: statusGatewayConnected(ctx, conn, gatewayARN), + Timeout: timeout, + MinTimeout: 10 * time.Second, + ContinuousTargetOccurence: 6, // Gateway activations can take a few seconds and can trigger a reboot of the Gateway. + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*storagegateway.DescribeGatewayInformationOutput); ok { + return output, err + } + + return nil, err +} + +func waitGatewayJoinDomainJoined(ctx context.Context, conn *storagegateway.Client, gatewayARN string) (*storagegateway.DescribeSMBSettingsOutput, error) { //nolint:unparam + const ( + timeout = 5 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ActiveDirectoryStatusJoining), + Target: enum.Slice(awstypes.ActiveDirectoryStatusJoined), + Refresh: statusGatewayJoinDomain(ctx, conn, gatewayARN), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*storagegateway.DescribeSMBSettingsOutput); ok { + return output, err + } + + return nil, err +} + +func expandJoinDomainInput(tfList []interface{}, gatewayARN string) *storagegateway.JoinDomainInput { + if tfList == nil || tfList[0] == nil { return nil } - tfMap, ok := l[0].(map[string]interface{}) + tfMap, ok := tfList[0].(map[string]interface{}) if !ok { return nil } - domain := &storagegateway.JoinDomainInput{ + apiObject := &storagegateway.JoinDomainInput{ DomainName: aws.String(tfMap[names.AttrDomainName].(string)), - GatewayARN: aws.String(gatewayArn), + GatewayARN: aws.String(gatewayARN), Password: aws.String(tfMap[names.AttrPassword].(string)), - UserName: aws.String(tfMap[names.AttrUsername].(string)), TimeoutInSeconds: aws.Int32(int32(tfMap["timeout_in_seconds"].(int))), + UserName: aws.String(tfMap[names.AttrUsername].(string)), } - if v, ok := tfMap["organizational_unit"].(string); ok && v != "" { - domain.OrganizationalUnit = aws.String(v) + if v, ok := tfMap["domain_controllers"].(*schema.Set); ok && v.Len() > 0 { + apiObject.DomainControllers = flex.ExpandStringValueSet(v) } - if v, ok := tfMap["domain_controllers"].(*schema.Set); ok && v.Len() > 0 { - domain.DomainControllers = flex.ExpandStringValueSet(v) + if v, ok := tfMap["organizational_unit"].(string); ok && v != "" { + apiObject.OrganizationalUnit = aws.String(v) } - return domain + return apiObject } -func flattenGatewayNetworkInterfaces(nis []awstypes.NetworkInterface) []interface{} { - if len(nis) == 0 { +func flattenNetworkInterfaces(apiObjects []awstypes.NetworkInterface) []interface{} { + if len(apiObjects) == 0 { return nil } var tfList []interface{} - for _, ni := range nis { + for _, apiObject := range apiObjects { tfMap := map[string]interface{}{ - "ipv4_address": aws.ToString(ni.Ipv4Address), + "ipv4_address": aws.ToString(apiObject.Ipv4Address), } tfList = append(tfList, tfMap) @@ -893,11 +985,11 @@ func flattenDescribeMaintenanceStartTimeOutput(apiObject *storagegateway.Describ tfMap := map[string]interface{}{} if v := apiObject.DayOfMonth; v != nil { - tfMap["day_of_month"] = strconv.FormatInt(int64(aws.ToInt32(v)), 10) + tfMap["day_of_month"] = flex.Int32ToStringValue(v) } if v := apiObject.DayOfWeek; v != nil { - tfMap["day_of_week"] = strconv.FormatInt(int64(aws.ToInt32(v)), 10) + tfMap["day_of_week"] = flex.Int32ToStringValue(v) } if v := apiObject.HourOfDay; v != nil { diff --git a/internal/service/storagegateway/gateway_test.go b/internal/service/storagegateway/gateway_test.go index 2ff867838c29..8b653bbc0499 100644 --- a/internal/service/storagegateway/gateway_test.go +++ b/internal/service/storagegateway/gateway_test.go @@ -897,11 +897,11 @@ func testAccCheckGatewayDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckGatewayExists(ctx context.Context, resourceName string, gateway *storagegateway.DescribeGatewayInformationOutput) resource.TestCheckFunc { +func testAccCheckGatewayExists(ctx context.Context, n string, v *storagegateway.DescribeGatewayInformationOutput) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) @@ -912,7 +912,7 @@ func testAccCheckGatewayExists(ctx context.Context, resourceName string, gateway return err } - *gateway = *output + *v = *output return nil } diff --git a/internal/service/storagegateway/status.go b/internal/service/storagegateway/status.go index 1a43b81d4971..e9762f734f9a 100644 --- a/internal/service/storagegateway/status.go +++ b/internal/service/storagegateway/status.go @@ -16,50 +16,9 @@ import ( ) const ( - gatewayStatusConnected = "GatewayConnected" storediSCSIVolumeStatusNotFound = "NotFound" ) -func statusGateway(ctx context.Context, conn *storagegateway.Client, gatewayARN string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - input := &storagegateway.DescribeGatewayInformationInput{ - GatewayARN: aws.String(gatewayARN), - } - - output, err := conn.DescribeGatewayInformation(ctx, input) - - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { - return output, string(awstypes.ErrorCodeGatewayNotConnected), nil - } - - if err != nil { - return output, "", err - } - - return output, gatewayStatusConnected, nil - } -} - -func statusGatewayJoinDomain(ctx context.Context, conn *storagegateway.Client, gatewayARN string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - input := &storagegateway.DescribeSMBSettingsInput{ - GatewayARN: aws.String(gatewayARN), - } - - output, err := conn.DescribeSMBSettings(ctx, input) - - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { - return output, string(awstypes.ActiveDirectoryStatusUnknownError), nil - } - - if err != nil { - return output, string(awstypes.ActiveDirectoryStatusUnknownError), err - } - - return output, string(output.ActiveDirectoryStatus), nil - } -} - // statusStorediSCSIVolume fetches the Volume and its Status func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, volumeARN string) retry.StateRefreshFunc { return func() (interface{}, string, error) { diff --git a/internal/service/storagegateway/wait.go b/internal/service/storagegateway/wait.go index 60c27f5dd8de..ade4797dc675 100644 --- a/internal/service/storagegateway/wait.go +++ b/internal/service/storagegateway/wait.go @@ -10,59 +10,16 @@ import ( "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/enum" ) const ( - gatewayConnectedMinTimeout = 10 * time.Second - gatewayConnectedContinuousTargetOccurence = 6 - gatewayJoinDomainJoinedTimeout = 5 * time.Minute - storediSCSIVolumeAvailableTimeout = 5 * time.Minute - nfsFileShareAvailableDelay = 5 * time.Second - nfsFileShareDeletedDelay = 5 * time.Second - smbFileShareAvailableDelay = 5 * time.Second - smbFileShareDeletedDelay = 5 * time.Second - fileSystemAssociationAvailableDelay = 5 * time.Second - fileSystemAssociationDeletedDelay = 5 * time.Second + storediSCSIVolumeAvailableTimeout = 5 * time.Minute + nfsFileShareAvailableDelay = 5 * time.Second + nfsFileShareDeletedDelay = 5 * time.Second + smbFileShareAvailableDelay = 5 * time.Second + smbFileShareDeletedDelay = 5 * time.Second ) -func waitGatewayConnected(ctx context.Context, conn *storagegateway.Client, gatewayARN string, timeout time.Duration) (*storagegateway.DescribeGatewayInformationOutput, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ErrorCodeGatewayNotConnected), - Target: []string{gatewayStatusConnected}, - Refresh: statusGateway(ctx, conn, gatewayARN), - Timeout: timeout, - MinTimeout: gatewayConnectedMinTimeout, - ContinuousTargetOccurence: gatewayConnectedContinuousTargetOccurence, // Gateway activations can take a few seconds and can trigger a reboot of the Gateway - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - switch output := outputRaw.(type) { - case *storagegateway.DescribeGatewayInformationOutput: - return output, err - default: - return nil, err - } -} - -func waitGatewayJoinDomainJoined(ctx context.Context, conn *storagegateway.Client, volumeARN string) (*storagegateway.DescribeSMBSettingsOutput, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ActiveDirectoryStatusJoining), - Target: enum.Slice(awstypes.ActiveDirectoryStatusJoined), - Refresh: statusGatewayJoinDomain(ctx, conn, volumeARN), - Timeout: gatewayJoinDomainJoinedTimeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*storagegateway.DescribeSMBSettingsOutput); ok { - return output, err - } - - return nil, err -} - // waitStorediSCSIVolumeAvailable waits for a StoredIscsiVolume to return Available func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.Client, volumeARN string) (*storagegateway.DescribeStorediSCSIVolumesOutput, error) { stateConf := &retry.StateChangeConf{ From 4963ecb8a7d938be037f4edb726dec4a732ea26d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 29 Jul 2024 10:15:04 -0400 Subject: [PATCH 29/39] d/aws_storagegateway_local_disk: Cosmetics. --- .../storagegateway/local_disk_data_source.go | 5 ++-- .../local_disk_data_source_test.go | 26 ++++--------------- 2 files changed, 7 insertions(+), 24 deletions(-) diff --git a/internal/service/storagegateway/local_disk_data_source.go b/internal/service/storagegateway/local_disk_data_source.go index f449313be000..4c9c4ca1699b 100644 --- a/internal/service/storagegateway/local_disk_data_source.go +++ b/internal/service/storagegateway/local_disk_data_source.go @@ -5,7 +5,6 @@ package storagegateway import ( "context" - "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/storagegateway" @@ -54,10 +53,10 @@ func dataSourceLocalDiskRead(ctx context.Context, d *schema.ResourceData, meta i GatewayARN: aws.String(d.Get("gateway_arn").(string)), } - log.Printf("[DEBUG] Reading Storage Gateway Local Disk: %#v", input) output, err := conn.ListLocalDisks(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Local Disk: %s", err) + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Local Disks: %s", err) } if output == nil || len(output.Disks) == 0 { diff --git a/internal/service/storagegateway/local_disk_data_source_test.go b/internal/service/storagegateway/local_disk_data_source_test.go index 47c97ea6212e..d4214794de9f 100644 --- a/internal/service/storagegateway/local_disk_data_source_test.go +++ b/internal/service/storagegateway/local_disk_data_source_test.go @@ -10,7 +10,6 @@ import ( "github.com/YakDriver/regexache" 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/names" ) @@ -24,7 +23,6 @@ func TestAccStorageGatewayLocalDiskDataSource_diskNode(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckGatewayDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccLocalDiskDataSourceConfig_nodeNonExistent(rName), @@ -33,7 +31,6 @@ func TestAccStorageGatewayLocalDiskDataSource_diskNode(t *testing.T) { { Config: testAccLocalDiskDataSourceConfig_node(rName), Check: resource.ComposeTestCheckFunc( - testAccLocalDiskExistsDataSource(dataSourceName), resource.TestMatchResourceAttr(dataSourceName, "disk_id", regexache.MustCompile(`.+`)), resource.TestMatchResourceAttr(dataSourceName, "disk_node", regexache.MustCompile(`.+`)), resource.TestMatchResourceAttr(dataSourceName, "disk_path", regexache.MustCompile(`.+`)), @@ -52,7 +49,6 @@ func TestAccStorageGatewayLocalDiskDataSource_diskPath(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckGatewayDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccLocalDiskDataSourceConfig_pathNonExistent(rName), @@ -61,7 +57,6 @@ func TestAccStorageGatewayLocalDiskDataSource_diskPath(t *testing.T) { { Config: testAccLocalDiskDataSourceConfig_path(rName), Check: resource.ComposeTestCheckFunc( - testAccLocalDiskExistsDataSource(dataSourceName), resource.TestMatchResourceAttr(dataSourceName, "disk_id", regexache.MustCompile(`.+`)), resource.TestMatchResourceAttr(dataSourceName, "disk_node", regexache.MustCompile(`.+`)), resource.TestMatchResourceAttr(dataSourceName, "disk_path", regexache.MustCompile(`.+`)), @@ -71,18 +66,7 @@ func TestAccStorageGatewayLocalDiskDataSource_diskPath(t *testing.T) { }) } -func testAccLocalDiskExistsDataSource(dataSourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - _, ok := s.RootModule().Resources[dataSourceName] - if !ok { - return fmt.Errorf("not found: %s", dataSourceName) - } - - return nil - } -} - -func testAccLocalDiskBaseDataSourceConfig(rName string) string { +func testAccLocalDiskDataSourceConfig_base(rName string) string { return acctest.ConfigCompose( testAccGatewayConfig_typeFileS3(rName), fmt.Sprintf(` @@ -107,7 +91,7 @@ resource "aws_volume_attachment" "test" { func testAccLocalDiskDataSourceConfig_node(rName string) string { return acctest.ConfigCompose( - testAccLocalDiskBaseDataSourceConfig(rName), + testAccLocalDiskDataSourceConfig_base(rName), ` data "aws_storagegateway_local_disk" "test" { disk_node = aws_volume_attachment.test.device_name @@ -118,7 +102,7 @@ data "aws_storagegateway_local_disk" "test" { func testAccLocalDiskDataSourceConfig_nodeNonExistent(rName string) string { return acctest.ConfigCompose( - testAccLocalDiskBaseDataSourceConfig(rName), + testAccLocalDiskDataSourceConfig_base(rName), ` data "aws_storagegateway_local_disk" "test" { disk_node = replace(aws_volume_attachment.test.device_name, "xvdb", "nonexistent") @@ -129,7 +113,7 @@ data "aws_storagegateway_local_disk" "test" { func testAccLocalDiskDataSourceConfig_path(rName string) string { return acctest.ConfigCompose( - testAccLocalDiskBaseDataSourceConfig(rName), + testAccLocalDiskDataSourceConfig_base(rName), ` data "aws_storagegateway_local_disk" "test" { disk_path = split(".", aws_instance.test.instance_type)[0] == "m4" ? aws_volume_attachment.test.device_name : replace(aws_volume_attachment.test.device_name, "xvdb", "nvme1n1") @@ -140,7 +124,7 @@ data "aws_storagegateway_local_disk" "test" { func testAccLocalDiskDataSourceConfig_pathNonExistent(rName string) string { return acctest.ConfigCompose( - testAccLocalDiskBaseDataSourceConfig(rName), + testAccLocalDiskDataSourceConfig_base(rName), ` data "aws_storagegateway_local_disk" "test" { disk_path = replace(aws_volume_attachment.test.device_name, "xvdb", "nonexistent") From ea20d02f86091e1488172927e2cba3bc356dd8d6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 29 Jul 2024 14:40:34 -0400 Subject: [PATCH 30/39] r/aws_storagegateway_nfs_file_share: Cosmetics. --- internal/service/storagegateway/find.go | 29 --- .../service/storagegateway/nfs_file_share.go | 175 ++++++++++++++---- .../storagegateway/nfs_file_share_test.go | 8 +- internal/service/storagegateway/status.go | 16 -- internal/service/storagegateway/wait.go | 57 ------ 5 files changed, 145 insertions(+), 140 deletions(-) diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go index b2651710f75e..847c2605e970 100644 --- a/internal/service/storagegateway/find.go +++ b/internal/service/storagegateway/find.go @@ -85,35 +85,6 @@ func findUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gate return &result, err } -func findNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.NFSFileShareInfo, error) { - input := &storagegateway.DescribeNFSFileSharesInput{ - FileShareARNList: []string{arn}, - } - - output, err := conn.DescribeNFSFileShares(ctx, input) - - if operationErrorCode(err) == operationErrCodeFileShareNotFound { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || len(output.NFSFileShareInfoList) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - if count := len(output.NFSFileShareInfoList); count > 1 { - return nil, tfresource.NewTooManyResultsError(count, input) - } - - return &output.NFSFileShareInfoList[0], nil -} - func findSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.SMBFileShareInfo, error) { input := &storagegateway.DescribeSMBFileSharesInput{ FileShareARNList: []string{arn}, diff --git a/internal/service/storagegateway/nfs_file_share.go b/internal/service/storagegateway/nfs_file_share.go index 3acce16797d1..75ca48b4c30b 100644 --- a/internal/service/storagegateway/nfs_file_share.go +++ b/internal/service/storagegateway/nfs_file_share.go @@ -15,6 +15,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "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" @@ -224,9 +225,8 @@ func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, met conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) fileShareDefaults, err := expandNFSFileShareDefaults(d.Get("nfs_file_share_defaults").([]interface{})) - if err != nil { - return sdkdiag.AppendErrorf(diags, "creating Storage Gateway NFS File Share: %s", err) + return sdkdiag.AppendFromErr(diags, err) } input := &storagegateway.CreateNFSFileShareInput{ @@ -274,7 +274,6 @@ func resourceNFSFileShareCreate(ctx context.Context, d *schema.ResourceData, met input.VPCEndpointDNSName = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating Storage Gateway NFS File Share: %#v", input) output, err := conn.CreateNFSFileShare(ctx, input) if err != nil { @@ -346,9 +345,8 @@ func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, met if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) { fileShareDefaults, err := expandNFSFileShareDefaults(d.Get("nfs_file_share_defaults").([]interface{})) - if err != nil { - return sdkdiag.AppendErrorf(diags, "updating Storage Gateway NFS File Share (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } input := &storagegateway.UpdateNFSFileShareInput{ @@ -384,7 +382,6 @@ func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, met input.NotificationPolicy = aws.String(v.(string)) } - log.Printf("[DEBUG] Updating Storage Gateway NFS File Share: %#v", input) _, err = conn.UpdateNFSFileShare(ctx, input) if err != nil { @@ -399,6 +396,116 @@ func resourceNFSFileShareUpdate(ctx context.Context, d *schema.ResourceData, met return append(diags, resourceNFSFileShareRead(ctx, d, meta)...) } +func findNFSFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.NFSFileShareInfo, error) { + input := &storagegateway.DescribeNFSFileSharesInput{ + FileShareARNList: []string{arn}, + } + + return findNFSFileShare(ctx, conn, input) +} + +func findNFSFileShare(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeNFSFileSharesInput) (*awstypes.NFSFileShareInfo, error) { + output, err := findNFSFileShares(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findNFSFileShares(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeNFSFileSharesInput) ([]awstypes.NFSFileShareInfo, error) { + output, err := conn.DescribeNFSFileShares(ctx, input) + + if operationErrorCode(err) == operationErrCodeFileShareNotFound { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.NFSFileShareInfoList, err +} + +func statusNFSFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findNFSFileShareByARN(ctx, conn, arn) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.ToString(output.FileShareStatus), nil + } +} + +func waitNFSFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileShareStatusCreating}, + Target: []string{fileShareStatusAvailable}, + Refresh: statusNFSFileShare(ctx, conn, arn), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { + return output, err + } + + return nil, err +} + +func waitNFSFileShareUpdated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileShareStatusUpdating}, + Target: []string{fileShareStatusAvailable}, + Refresh: statusNFSFileShare(ctx, conn, arn), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { + return output, err + } + + return nil, err +} + +func waitNFSFileShareDeleted(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileShareStatusAvailable, fileShareStatusDeleting, fileShareStatusForceDeleting}, + Target: []string{}, + Refresh: statusNFSFileShare(ctx, conn, arn), + Timeout: timeout, + Delay: 5 * time.Second, + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { + return output, err + } + + return nil, err +} + func resourceNFSFileShareDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) @@ -423,70 +530,70 @@ func resourceNFSFileShareDelete(ctx context.Context, d *schema.ResourceData, met return diags } -func expandNFSFileShareDefaults(l []interface{}) (*awstypes.NFSFileShareDefaults, error) { - if len(l) == 0 || l[0] == nil { +func expandNFSFileShareDefaults(tfList []interface{}) (*awstypes.NFSFileShareDefaults, error) { + if len(tfList) == 0 || tfList[0] == nil { return nil, nil } - m := l[0].(map[string]interface{}) + tfMap := tfList[0].(map[string]interface{}) - groupID, err := strconv.ParseInt(m["group_id"].(string), 10, 64) + groupID, err := strconv.ParseInt(tfMap["group_id"].(string), 10, 64) if err != nil { return nil, err } - ownerID, err := strconv.ParseInt(m[names.AttrOwnerID].(string), 10, 64) + ownerID, err := strconv.ParseInt(tfMap[names.AttrOwnerID].(string), 10, 64) if err != nil { return nil, err } - nfsFileShareDefaults := &awstypes.NFSFileShareDefaults{ - DirectoryMode: aws.String(m["directory_mode"].(string)), - FileMode: aws.String(m["file_mode"].(string)), + apiObject := &awstypes.NFSFileShareDefaults{ + DirectoryMode: aws.String(tfMap["directory_mode"].(string)), + FileMode: aws.String(tfMap["file_mode"].(string)), GroupId: aws.Int64(groupID), OwnerId: aws.Int64(ownerID), } - return nfsFileShareDefaults, nil + return apiObject, nil } -func flattenNFSFileShareDefaults(nfsFileShareDefaults *awstypes.NFSFileShareDefaults) []interface{} { - if nfsFileShareDefaults == nil { +func flattenNFSFileShareDefaults(apiObject *awstypes.NFSFileShareDefaults) []interface{} { + if apiObject == nil { return []interface{}{} } - m := map[string]interface{}{ - "directory_mode": aws.ToString(nfsFileShareDefaults.DirectoryMode), - "file_mode": aws.ToString(nfsFileShareDefaults.FileMode), - "group_id": strconv.Itoa(int(aws.ToInt64(nfsFileShareDefaults.GroupId))), - names.AttrOwnerID: strconv.Itoa(int(aws.ToInt64(nfsFileShareDefaults.OwnerId))), + tfMap := map[string]interface{}{ + "directory_mode": aws.ToString(apiObject.DirectoryMode), + "file_mode": aws.ToString(apiObject.FileMode), + "group_id": strconv.Itoa(int(aws.ToInt64(apiObject.GroupId))), + names.AttrOwnerID: strconv.Itoa(int(aws.ToInt64(apiObject.OwnerId))), } - return []interface{}{m} + return []interface{}{tfMap} } -func expandNFSFileShareCacheAttributes(l []interface{}) *awstypes.CacheAttributes { - if len(l) == 0 || l[0] == nil { +func expandNFSFileShareCacheAttributes(tfList []interface{}) *awstypes.CacheAttributes { + if len(tfList) == 0 || tfList[0] == nil { return nil } - m := l[0].(map[string]interface{}) + tfMap := tfList[0].(map[string]interface{}) - ca := &awstypes.CacheAttributes{ - CacheStaleTimeoutInSeconds: aws.Int32(int32(m["cache_stale_timeout_in_seconds"].(int))), + apiObject := &awstypes.CacheAttributes{ + CacheStaleTimeoutInSeconds: aws.Int32(int32(tfMap["cache_stale_timeout_in_seconds"].(int))), } - return ca + return apiObject } -func flattenNFSFileShareCacheAttributes(ca *awstypes.CacheAttributes) []interface{} { - if ca == nil { +func flattenNFSFileShareCacheAttributes(apiObject *awstypes.CacheAttributes) []interface{} { + if apiObject == nil { return []interface{}{} } - m := map[string]interface{}{ - "cache_stale_timeout_in_seconds": aws.ToInt32(ca.CacheStaleTimeoutInSeconds), + tfMap := map[string]interface{}{ + "cache_stale_timeout_in_seconds": aws.ToInt32(apiObject.CacheStaleTimeoutInSeconds), } - return []interface{}{m} + return []interface{}{tfMap} } diff --git a/internal/service/storagegateway/nfs_file_share_test.go b/internal/service/storagegateway/nfs_file_share_test.go index 219824cc676a..461786c9323f 100644 --- a/internal/service/storagegateway/nfs_file_share_test.go +++ b/internal/service/storagegateway/nfs_file_share_test.go @@ -709,11 +709,11 @@ func testAccCheckNFSFileShareDestroy(ctx context.Context) resource.TestCheckFunc } } -func testAccCheckNFSFileShareExists(ctx context.Context, resourceName string, nfsFileShare *awstypes.NFSFileShareInfo) resource.TestCheckFunc { +func testAccCheckNFSFileShareExists(ctx context.Context, n string, v *awstypes.NFSFileShareInfo) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) @@ -724,7 +724,7 @@ func testAccCheckNFSFileShareExists(ctx context.Context, resourceName string, nf return err } - *nfsFileShare = *output + *v = *output return nil } diff --git a/internal/service/storagegateway/status.go b/internal/service/storagegateway/status.go index e9762f734f9a..64034b6e6fdd 100644 --- a/internal/service/storagegateway/status.go +++ b/internal/service/storagegateway/status.go @@ -45,22 +45,6 @@ func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, v } } -func statusNFSFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findNFSFileShareByARN(ctx, conn, arn) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output.FileShareStatus), nil - } -} - func statusSMBFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { return func() (interface{}, string, error) { output, err := findSMBFileShareByARN(ctx, conn, arn) diff --git a/internal/service/storagegateway/wait.go b/internal/service/storagegateway/wait.go index ade4797dc675..9e13fbcb955b 100644 --- a/internal/service/storagegateway/wait.go +++ b/internal/service/storagegateway/wait.go @@ -14,8 +14,6 @@ import ( const ( storediSCSIVolumeAvailableTimeout = 5 * time.Minute - nfsFileShareAvailableDelay = 5 * time.Second - nfsFileShareDeletedDelay = 5 * time.Second smbFileShareAvailableDelay = 5 * time.Second smbFileShareDeletedDelay = 5 * time.Second ) @@ -38,61 +36,6 @@ func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.Cl return nil, err } -func waitNFSFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileShareStatusCreating}, - Target: []string{fileShareStatusAvailable}, - Refresh: statusNFSFileShare(ctx, conn, arn), - Timeout: timeout, - Delay: nfsFileShareAvailableDelay, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { - return output, err - } - - return nil, err -} - -func waitNFSFileShareDeleted(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileShareStatusAvailable, fileShareStatusDeleting, fileShareStatusForceDeleting}, - Target: []string{}, - Refresh: statusNFSFileShare(ctx, conn, arn), - Timeout: timeout, - Delay: nfsFileShareDeletedDelay, - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { - return output, err - } - - return nil, err -} - -func waitNFSFileShareUpdated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.NFSFileShareInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileShareStatusUpdating}, - Target: []string{fileShareStatusAvailable}, - Refresh: statusNFSFileShare(ctx, conn, arn), - Timeout: timeout, - Delay: nfsFileShareAvailableDelay, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NFSFileShareInfo); ok { - return output, err - } - - return nil, err -} - func waitSMBFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { stateConf := &retry.StateChangeConf{ Pending: []string{fileShareStatusCreating}, From e2341a5856026f37310bd1a9a3a7f2d132023025 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 29 Jul 2024 15:05:44 -0400 Subject: [PATCH 31/39] r/aws_storagegateway_smb_file_share: Cosmetics. --- internal/service/storagegateway/find.go | 30 ----- .../service/storagegateway/smb_file_share.go | 121 +++++++++++++++++- .../storagegateway/smb_file_share_test.go | 8 +- internal/service/storagegateway/status.go | 17 --- internal/service/storagegateway/wait.go | 58 --------- 5 files changed, 118 insertions(+), 116 deletions(-) diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go index 847c2605e970..c4e25debb018 100644 --- a/internal/service/storagegateway/find.go +++ b/internal/service/storagegateway/find.go @@ -9,7 +9,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -84,32 +83,3 @@ func findUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gate return &result, err } - -func findSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.SMBFileShareInfo, error) { - input := &storagegateway.DescribeSMBFileSharesInput{ - FileShareARNList: []string{arn}, - } - - output, err := conn.DescribeSMBFileShares(ctx, input) - - if operationErrorCode(err) == operationErrCodeFileShareNotFound { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || len(output.SMBFileShareInfoList) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - if count := len(output.SMBFileShareInfoList); count > 1 { - return nil, tfresource.NewTooManyResultsError(count, input) - } - - return &output.SMBFileShareInfoList[0], nil -} diff --git a/internal/service/storagegateway/smb_file_share.go b/internal/service/storagegateway/smb_file_share.go index e685d822ecf8..935fbf138988 100644 --- a/internal/service/storagegateway/smb_file_share.go +++ b/internal/service/storagegateway/smb_file_share.go @@ -14,6 +14,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "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" @@ -288,7 +289,6 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met input.VPCEndpointDNSName = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating Storage Gateway SMB File Share: %#v", input) output, err := conn.CreateSMBFileShare(ctx, input) if err != nil { @@ -298,7 +298,7 @@ func resourceSMBFileShareCreate(ctx context.Context, d *schema.ResourceData, met d.SetId(aws.ToString(output.FileShareARN)) if _, err = waitSMBFileShareCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) to create: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) create: %s", d.Id(), err) } return append(diags, resourceSMBFileShareRead(ctx, d, meta)...) @@ -326,7 +326,6 @@ func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta d.Set("audit_destination_arn", fileshare.AuditDestinationARN) d.Set("authentication", fileshare.Authentication) d.Set("bucket_region", fileshare.BucketRegion) - if fileshare.CacheAttributes != nil { if err := d.Set("cache_attributes", []interface{}{flattenCacheAttributes(fileshare.CacheAttributes)}); err != nil { return sdkdiag.AppendErrorf(diags, "setting cache_attributes: %s", err) @@ -334,7 +333,6 @@ func resourceSMBFileShareRead(ctx context.Context, d *schema.ResourceData, meta } else { d.Set("cache_attributes", nil) } - d.Set("case_sensitivity", fileshare.CaseSensitivity) d.Set("default_storage_class", fileshare.DefaultStorageClass) d.Set("fileshare_id", fileshare.FileShareId) @@ -431,7 +429,6 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met input.ValidUserList = flex.ExpandStringValueSet(d.Get("valid_user_list").(*schema.Set)) } - log.Printf("[DEBUG] Updating Storage Gateway SMB File Share: %#v", input) _, err := conn.UpdateSMBFileShare(ctx, input) if err != nil { @@ -439,7 +436,7 @@ func resourceSMBFileShareUpdate(ctx context.Context, d *schema.ResourceData, met } if _, err = waitSMBFileShareUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) to update: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) update: %s", d.Id(), err) } } @@ -464,12 +461,122 @@ func resourceSMBFileShareDelete(ctx context.Context, d *schema.ResourceData, met } if _, err = waitSMBFileShareDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) to delete: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway SMB File Share (%s) delete: %s", d.Id(), err) } return diags } +func findSMBFileShareByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.SMBFileShareInfo, error) { + input := &storagegateway.DescribeSMBFileSharesInput{ + FileShareARNList: []string{arn}, + } + + return findSMBFileShare(ctx, conn, input) +} + +func findSMBFileShare(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeSMBFileSharesInput) (*awstypes.SMBFileShareInfo, error) { + output, err := findSMBFileShares(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSMBFileShares(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeSMBFileSharesInput) ([]awstypes.SMBFileShareInfo, error) { + output, err := conn.DescribeSMBFileShares(ctx, input) + + if operationErrorCode(err) == operationErrCodeFileShareNotFound { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.SMBFileShareInfoList, err +} + +func statusSMBFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findSMBFileShareByARN(ctx, conn, arn) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.ToString(output.FileShareStatus), nil + } +} + +func waitSMBFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileShareStatusCreating}, + Target: []string{fileShareStatusAvailable}, + Refresh: statusSMBFileShare(ctx, conn, arn), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { + return output, err + } + + return nil, err +} + +func waitSMBFileShareUpdated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileShareStatusUpdating}, + Target: []string{fileShareStatusAvailable}, + Refresh: statusSMBFileShare(ctx, conn, arn), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { + return output, err + } + + return nil, err +} + +func waitSMBFileShareDeleted(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{fileShareStatusAvailable, fileShareStatusDeleting, fileShareStatusForceDeleting}, + Target: []string{}, + Refresh: statusSMBFileShare(ctx, conn, arn), + Timeout: timeout, + Delay: 5 * time.Second, + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { + return output, err + } + + return nil, err +} + func expandCacheAttributes(tfMap map[string]interface{}) *awstypes.CacheAttributes { if tfMap == nil { return nil diff --git a/internal/service/storagegateway/smb_file_share_test.go b/internal/service/storagegateway/smb_file_share_test.go index fb40c811ca6e..1791601868ee 100644 --- a/internal/service/storagegateway/smb_file_share_test.go +++ b/internal/service/storagegateway/smb_file_share_test.go @@ -971,11 +971,11 @@ func testAccCheckSMBFileShareDestroy(ctx context.Context) resource.TestCheckFunc } } -func testAccCheckSMBFileShareExists(ctx context.Context, resourceName string, smbFileShare *awstypes.SMBFileShareInfo) resource.TestCheckFunc { +func testAccCheckSMBFileShareExists(ctx context.Context, n string, v *awstypes.SMBFileShareInfo) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) @@ -986,7 +986,7 @@ func testAccCheckSMBFileShareExists(ctx context.Context, resourceName string, sm return err } - *smbFileShare = *output + *v = *output return nil } diff --git a/internal/service/storagegateway/status.go b/internal/service/storagegateway/status.go index 64034b6e6fdd..cdbddd1881ea 100644 --- a/internal/service/storagegateway/status.go +++ b/internal/service/storagegateway/status.go @@ -12,7 +12,6 @@ import ( "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/errs" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) const ( @@ -44,19 +43,3 @@ func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, v return output, aws.ToString(output.StorediSCSIVolumes[0].VolumeStatus), nil } } - -func statusSMBFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findSMBFileShareByARN(ctx, conn, arn) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output.FileShareStatus), nil - } -} diff --git a/internal/service/storagegateway/wait.go b/internal/service/storagegateway/wait.go index 9e13fbcb955b..391fe4a2a389 100644 --- a/internal/service/storagegateway/wait.go +++ b/internal/service/storagegateway/wait.go @@ -8,14 +8,11 @@ import ( "time" "github.com/aws/aws-sdk-go-v2/service/storagegateway" - awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" ) const ( storediSCSIVolumeAvailableTimeout = 5 * time.Minute - smbFileShareAvailableDelay = 5 * time.Second - smbFileShareDeletedDelay = 5 * time.Second ) // waitStorediSCSIVolumeAvailable waits for a StoredIscsiVolume to return Available @@ -35,58 +32,3 @@ func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.Cl return nil, err } - -func waitSMBFileShareCreated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileShareStatusCreating}, - Target: []string{fileShareStatusAvailable}, - Refresh: statusSMBFileShare(ctx, conn, arn), - Timeout: timeout, - Delay: smbFileShareAvailableDelay, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { - return output, err - } - - return nil, err -} - -func waitSMBFileShareDeleted(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileShareStatusAvailable, fileShareStatusDeleting, fileShareStatusForceDeleting}, - Target: []string{}, - Refresh: statusSMBFileShare(ctx, conn, arn), - Timeout: timeout, - Delay: smbFileShareDeletedDelay, - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { - return output, err - } - - return nil, err -} - -func waitSMBFileShareUpdated(ctx context.Context, conn *storagegateway.Client, arn string, timeout time.Duration) (*awstypes.SMBFileShareInfo, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{fileShareStatusUpdating}, - Target: []string{fileShareStatusAvailable}, - Refresh: statusSMBFileShare(ctx, conn, arn), - Timeout: timeout, - Delay: smbFileShareAvailableDelay, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SMBFileShareInfo); ok { - return output, err - } - - return nil, err -} From 6d5d1a7743dfbf5d89b9876abb36def329741c27 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 29 Jul 2024 16:17:53 -0400 Subject: [PATCH 32/39] Add 'findStorediSCSIVolumeByARN'. --- .../storagegateway/cached_iscsi_volume.go | 21 +- internal/service/storagegateway/errors.go | 4 +- .../service/storagegateway/exports_test.go | 1 + internal/service/storagegateway/status.go | 45 ---- .../storagegateway/stored_iscsi_volume.go | 248 +++++++++++------- .../stored_iscsi_volume_test.go | 72 ++--- internal/service/storagegateway/wait.go | 34 --- 7 files changed, 190 insertions(+), 235 deletions(-) delete mode 100644 internal/service/storagegateway/status.go delete mode 100644 internal/service/storagegateway/wait.go diff --git a/internal/service/storagegateway/cached_iscsi_volume.go b/internal/service/storagegateway/cached_iscsi_volume.go index fd883e242831..03871d51a924 100644 --- a/internal/service/storagegateway/cached_iscsi_volume.go +++ b/internal/service/storagegateway/cached_iscsi_volume.go @@ -179,24 +179,20 @@ func resourceCachediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, arn := aws.ToString(volume.VolumeARN) d.Set(names.AttrARN, arn) + d.Set("kms_encrypted", volume.KMSKey != nil) d.Set(names.AttrKMSKey, volume.KMSKey) - if volume.KMSKey != nil { - d.Set("kms_encrypted", true) - } else { - d.Set("kms_encrypted", false) - } d.Set(names.AttrSnapshotID, volume.SourceSnapshotId) d.Set("volume_arn", arn) d.Set("volume_id", volume.VolumeId) d.Set("volume_size_in_bytes", volume.VolumeSizeInBytes) - if volume.VolumeiSCSIAttributes != nil { - d.Set("chap_enabled", volume.VolumeiSCSIAttributes.ChapEnabled) - d.Set("lun_number", volume.VolumeiSCSIAttributes.LunNumber) - d.Set(names.AttrNetworkInterfaceID, volume.VolumeiSCSIAttributes.NetworkInterfaceId) - d.Set("network_interface_port", volume.VolumeiSCSIAttributes.NetworkInterfacePort) + if attr := volume.VolumeiSCSIAttributes; attr != nil { + d.Set("chap_enabled", attr.ChapEnabled) + d.Set("lun_number", attr.LunNumber) + d.Set(names.AttrNetworkInterfaceID, attr.NetworkInterfaceId) + d.Set("network_interface_port", attr.NetworkInterfacePort) - targetARN := aws.ToString(volume.VolumeiSCSIAttributes.TargetARN) + targetARN := aws.ToString(attr.TargetARN) d.Set(names.AttrTargetARN, targetARN) gatewayARN, targetName, err := parseVolumeGatewayARNAndTargetNameFromARN(targetARN) @@ -237,7 +233,7 @@ func resourceCachediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData } if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway cached iSCSI volume %q: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway cached iSCSI Volume (%s): %s", d.Id(), err) } return diags @@ -261,7 +257,6 @@ func findCachediSCSIVolumeByARN(ctx context.Context, conn *storagegateway.Client } return output, nil - } func findCachediSCSIVolume(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeCachediSCSIVolumesInput) (*awstypes.CachediSCSIVolume, error) { diff --git a/internal/service/storagegateway/errors.go b/internal/service/storagegateway/errors.go index 4748a913f570..f7b759e09136 100644 --- a/internal/service/storagegateway/errors.go +++ b/internal/service/storagegateway/errors.go @@ -53,11 +53,11 @@ func isGatewayNotFoundErr(err error) bool { // The API returns multiple responses for a missing volume. func isVolumeNotFoundErr(err error) bool { - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { + if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { return true } - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { + if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { return true } diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index 772480d00687..e70fff21353d 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -21,6 +21,7 @@ var ( FindGatewayByARN = findGatewayByARN FindNFSFileShareByARN = findNFSFileShareByARN FindSMBFileShareByARN = findSMBFileShareByARN + FindStorediSCSIVolumeByARN = findStorediSCSIVolumeByARN FindUploadBufferDisk = findUploadBufferDisk CacheParseResourceID = cacheParseResourceID diff --git a/internal/service/storagegateway/status.go b/internal/service/storagegateway/status.go deleted file mode 100644 index cdbddd1881ea..000000000000 --- a/internal/service/storagegateway/status.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package storagegateway - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" - awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/errs" -) - -const ( - storediSCSIVolumeStatusNotFound = "NotFound" -) - -// statusStorediSCSIVolume fetches the Volume and its Status -func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, volumeARN string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []string{volumeARN}, - } - - output, err := conn.DescribeStorediSCSIVolumes(ctx, input) - - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) || - errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - return nil, storediSCSIVolumeStatusNotFound, nil - } - - if err != nil { - return nil, "", err - } - - if output == nil || len(output.StorediSCSIVolumes) == 0 { - return nil, storediSCSIVolumeStatusNotFound, nil - } - - return output, aws.ToString(output.StorediSCSIVolumes[0].VolumeStatus), nil - } -} diff --git a/internal/service/storagegateway/stored_iscsi_volume.go b/internal/service/storagegateway/stored_iscsi_volume.go index 10b934960a7b..6d8ad3a73dc1 100644 --- a/internal/service/storagegateway/stored_iscsi_volume.go +++ b/internal/service/storagegateway/stored_iscsi_volume.go @@ -11,12 +11,10 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-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" @@ -42,6 +40,10 @@ func resourceStorediSCSIVolume() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "chap_enabled": { + Type: schema.TypeBool, + Computed: true, + }, "disk_id": { Type: schema.TypeString, Required: true, @@ -53,16 +55,6 @@ func resourceStorediSCSIVolume() *schema.Resource { ForceNew: true, ValidateFunc: verify.ValidARN, }, - "target_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "preserve_existing_data": { - Type: schema.TypeBool, - Required: true, - ForceNew: true, - }, "kms_encrypted": { Type: schema.TypeBool, Optional: true, @@ -75,7 +67,11 @@ func resourceStorediSCSIVolume() *schema.Resource { ValidateFunc: verify.ValidARN, RequiredWith: []string{"kms_encrypted"}, }, - // Poor API naming: this accepts the IP address of the network interface + "lun_number": { + Type: schema.TypeInt, + Computed: true, + }, + // Poor API naming: this accepts the IP address of the network interface. names.AttrNetworkInterfaceID: { Type: schema.TypeString, Required: true, @@ -85,20 +81,28 @@ func resourceStorediSCSIVolume() *schema.Resource { Type: schema.TypeInt, Computed: true, }, + "preserve_existing_data": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, names.AttrSnapshotID: { Type: schema.TypeString, Optional: true, ForceNew: true, }, - "chap_enabled": { - Type: schema.TypeBool, + names.AttrTags: tftags.TagsSchema(), + names.AttrTagsAll: tftags.TagsSchemaComputed(), + names.AttrTargetARN: { + Type: schema.TypeString, Computed: true, }, - "lun_number": { - Type: schema.TypeInt, - Computed: true, + "target_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, }, - names.AttrTargetARN: { + "volume_attachment_status": { Type: schema.TypeString, Computed: true, }, @@ -114,16 +118,10 @@ func resourceStorediSCSIVolume() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "volume_attachment_status": { - Type: schema.TypeString, - Computed: true, - }, names.AttrVolumeType: { Type: schema.TypeString, Computed: true, }, - names.AttrTags: tftags.TagsSchema(), - names.AttrTagsAll: tftags.TagsSchemaComputed(), }, CustomizeDiff: verify.SetTagsDiff, @@ -138,35 +136,33 @@ func resourceStorediSCSIVolumeCreate(ctx context.Context, d *schema.ResourceData DiskId: aws.String(d.Get("disk_id").(string)), GatewayARN: aws.String(d.Get("gateway_arn").(string)), NetworkInterfaceId: aws.String(d.Get(names.AttrNetworkInterfaceID).(string)), - TargetName: aws.String(d.Get("target_name").(string)), PreserveExistingData: d.Get("preserve_existing_data").(bool), Tags: getTagsIn(ctx), + TargetName: aws.String(d.Get("target_name").(string)), } - if v, ok := d.GetOk(names.AttrSnapshotID); ok { - input.SnapshotId = aws.String(v.(string)) + if v, ok := d.GetOk("kms_encrypted"); ok { + input.KMSEncrypted = aws.Bool(v.(bool)) } if v, ok := d.GetOk(names.AttrKMSKey); ok { input.KMSKey = aws.String(v.(string)) } - if v, ok := d.GetOk("kms_encrypted"); ok { - input.KMSEncrypted = aws.Bool(v.(bool)) + if v, ok := d.GetOk(names.AttrSnapshotID); ok { + input.SnapshotId = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating Storage Gateway Stored iSCSI volume: %#v", input) output, err := conn.CreateStorediSCSIVolume(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Stored iSCSI volume: %s", err) + return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Stored iSCSI Volume: %s", err) } d.SetId(aws.ToString(output.VolumeARN)) - _, err = waitStorediSCSIVolumeAvailable(ctx, conn, d.Id()) - - if err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Stored Iscsi Volume %q to be Available: %s", d.Id(), err) + if _, err := waitStorediSCSIVolumeAvailable(ctx, conn, d.Id()); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway Stored iSCSI Volume (%s) create: %s", d.Id(), err) } return append(diags, resourceStorediSCSIVolumeRead(ctx, d, meta)...) @@ -176,58 +172,47 @@ func resourceStorediSCSIVolumeRead(ctx context.Context, d *schema.ResourceData, var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []string{d.Id()}, - } - - log.Printf("[DEBUG] Reading Storage Gateway Stored iSCSI volume: %s", input) - output, err := conn.DescribeStorediSCSIVolumes(ctx, input) + volume, err := findStorediSCSIVolumeByARN(ctx, conn, d.Id()) - if err != nil { - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) || errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - log.Printf("[WARN] Storage Gateway Stored iSCSI volume %q not found, removing from state", d.Id()) - d.SetId("") - return diags - } - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Stored iSCSI volume %q: %s", d.Id(), err) - } - - if output == nil || len(output.StorediSCSIVolumes) == 0 || aws.ToString(output.StorediSCSIVolumes[0].VolumeARN) != d.Id() { - log.Printf("[WARN] Storage Gateway Stored iSCSI volume %q not found, removing from state", d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Storage Gateway Stored iSCSI Volume (%s) not found, removing from state", d.Id()) d.SetId("") return diags } - volume := output.StorediSCSIVolumes[0] + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Stored iSCSI Volume (%s): %s", d.Id(), err) + } arn := aws.ToString(volume.VolumeARN) d.Set(names.AttrARN, arn) d.Set("disk_id", volume.VolumeDiskId) + d.Set("kms_encrypted", volume.KMSKey != nil) + d.Set(names.AttrKMSKey, volume.KMSKey) + d.Set("preserve_existing_data", volume.PreservedExistingData) d.Set(names.AttrSnapshotID, volume.SourceSnapshotId) + d.Set("volume_attachment_status", volume.VolumeAttachmentStatus) d.Set("volume_id", volume.VolumeId) - d.Set(names.AttrVolumeType, volume.VolumeType) d.Set("volume_size_in_bytes", volume.VolumeSizeInBytes) d.Set("volume_status", volume.VolumeStatus) - d.Set("volume_attachment_status", volume.VolumeAttachmentStatus) - d.Set("preserve_existing_data", volume.PreservedExistingData) - d.Set(names.AttrKMSKey, volume.KMSKey) - d.Set("kms_encrypted", volume.KMSKey != nil) + d.Set(names.AttrVolumeType, volume.VolumeType) - attr := volume.VolumeiSCSIAttributes - d.Set("chap_enabled", attr.ChapEnabled) - d.Set("lun_number", attr.LunNumber) - d.Set(names.AttrNetworkInterfaceID, attr.NetworkInterfaceId) - d.Set("network_interface_port", attr.NetworkInterfacePort) + if attr := volume.VolumeiSCSIAttributes; attr != nil { + d.Set("chap_enabled", attr.ChapEnabled) + d.Set("lun_number", attr.LunNumber) + d.Set(names.AttrNetworkInterfaceID, attr.NetworkInterfaceId) + d.Set("network_interface_port", attr.NetworkInterfacePort) - targetARN := aws.ToString(attr.TargetARN) - d.Set(names.AttrTargetARN, targetARN) + targetARN := aws.ToString(attr.TargetARN) + d.Set(names.AttrTargetARN, targetARN) - gatewayARN, targetName, err := parseVolumeGatewayARNAndTargetNameFromARN(targetARN) - if err != nil { - return sdkdiag.AppendErrorf(diags, "parsing Storage Gateway volume gateway ARN and target name from target ARN %q: %s", targetARN, err) + gatewayARN, targetName, err := parseVolumeGatewayARNAndTargetNameFromARN(targetARN) + if err != nil { + return sdkdiag.AppendFromErr(diags, err) + } + d.Set("gateway_arn", gatewayARN) + d.Set("target_name", targetName) } - d.Set("gateway_arn", gatewayARN) - d.Set("target_name", targetName) return diags } @@ -244,35 +229,110 @@ func resourceStorediSCSIVolumeDelete(ctx context.Context, d *schema.ResourceData var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DeleteVolumeInput{ - VolumeARN: aws.String(d.Id()), + log.Printf("[DEBUG] Deleting Storage Gateway Stored iSCSI Volume: %s", d.Id()) + const ( + timeout = 2 * time.Minute + ) + _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](ctx, timeout, func() (interface{}, error) { + return conn.DeleteVolume(ctx, &storagegateway.DeleteVolumeInput{ + VolumeARN: aws.String(d.Id()), + }) + }, "The specified gateway is not connected") + + if isVolumeNotFoundErr(err) { + return diags } - log.Printf("[DEBUG] Deleting Storage Gateway Stored iSCSI volume: %#v", input) - err := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { - _, err := conn.DeleteVolume(ctx, input) - if err != nil { - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { - return nil - } - // InvalidGatewayRequestException: The specified gateway is not connected. - // Can occur during concurrent DeleteVolume operations - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified gateway is not connected") { - return retry.RetryableError(err) - } - return retry.NonRetryableError(err) + if err != nil { + return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Stored iSCSI Volume (%s): %s", d.Id(), err) + } + + return diags +} + +func findStorediSCSIVolumeByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.StorediSCSIVolume, error) { + input := &storagegateway.DescribeStorediSCSIVolumesInput{ + VolumeARNs: []string{arn}, + } + output, err := findStorediSCSIVolume(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.VolumeARN) != arn { + return nil, &retry.NotFoundError{ + LastRequest: input, } - return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.DeleteVolume(ctx, input) } - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - return diags + + return output, nil +} + +func findStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeStorediSCSIVolumesInput) (*awstypes.StorediSCSIVolume, error) { + output, err := findStorediSCSIVolumes(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findStorediSCSIVolumes(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeStorediSCSIVolumesInput) ([]awstypes.StorediSCSIVolume, error) { + output, err := conn.DescribeStorediSCSIVolumes(ctx, input) + + if isVolumeNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } } + if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Stored iSCSI volume %q: %s", d.Id(), err) + return nil, err } - return diags + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.StorediSCSIVolumes, err +} + +func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, volumeARN string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findStorediSCSIVolumeByARN(ctx, conn, volumeARN) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.ToString(output.VolumeStatus), nil + } +} + +func waitStorediSCSIVolumeAvailable(ctx context.Context, conn *storagegateway.Client, volumeARN string) (*awstypes.StorediSCSIVolume, error) { + const ( + timeout = 5 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: []string{"BOOTSTRAPPING", "CREATING", "RESTORING"}, + Target: []string{"AVAILABLE"}, + Refresh: statusStorediSCSIVolume(ctx, conn, volumeARN), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.StorediSCSIVolume); ok { + return output, err + } + + return nil, err } diff --git a/internal/service/storagegateway/stored_iscsi_volume_test.go b/internal/service/storagegateway/stored_iscsi_volume_test.go index 9c32c6a09743..6919f7e5db16 100644 --- a/internal/service/storagegateway/stored_iscsi_volume_test.go +++ b/internal/service/storagegateway/stored_iscsi_volume_test.go @@ -9,17 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" 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" tfstoragegateway "github.com/hashicorp/terraform-provider-aws/internal/service/storagegateway" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -206,30 +203,22 @@ func TestAccStorageGatewayStorediSCSIVolume_disappears(t *testing.T) { }) } -func testAccCheckStorediSCSIVolumeExists(ctx context.Context, resourceName string, storedIscsiVolume *awstypes.StorediSCSIVolume) resource.TestCheckFunc { +func testAccCheckStorediSCSIVolumeExists(ctx context.Context, n string, v *awstypes.StorediSCSIVolume) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []string{rs.Primary.ID}, - } - - output, err := conn.DescribeStorediSCSIVolumes(ctx, input) + output, err := tfstoragegateway.FindStorediSCSIVolumeByARN(ctx, conn, rs.Primary.ID) if err != nil { - return fmt.Errorf("error reading Storage Gateway stored iSCSI volume: %w", err) - } - - if output == nil || len(output.StorediSCSIVolumes) == 0 || aws.ToString(output.StorediSCSIVolumes[0].VolumeARN) != rs.Primary.ID { - return fmt.Errorf("Storage Gateway stored iSCSI volume %q not found", rs.Primary.ID) + return err } - *storedIscsiVolume = output.StorediSCSIVolumes[0] + *v = *output return nil } @@ -244,36 +233,25 @@ func testAccCheckStorediSCSIVolumeDestroy(ctx context.Context) resource.TestChec continue } - input := &storagegateway.DescribeStorediSCSIVolumesInput{ - VolumeARNs: []string{rs.Primary.ID}, - } + _, err := tfstoragegateway.FindStorediSCSIVolumeByARN(ctx, conn, rs.Primary.ID) - output, err := conn.DescribeStorediSCSIVolumes(ctx, input) + if tfresource.NotFound(err) { + continue + } if err != nil { - if tfstoragegateway.IsGatewayNotFoundErr(err) { - return nil - } - if tfawserr.ErrCodeEquals(err, string(awstypes.ErrorCodeVolumeNotFound)) { - return nil - } - if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified volume was not found") { - return nil - } return err } - if output != nil && len(output.StorediSCSIVolumes) > 0 && aws.ToString(output.StorediSCSIVolumes[0].VolumeARN) == rs.Primary.ID { - return fmt.Errorf("Storage Gateway stored iSCSI volume %q still exists", rs.Primary.ID) - } + return fmt.Errorf("Storage Gateway Stored iSCSI Volume %s still exists", rs.Primary.ID) } return nil } } -func testAccStorediSCSIVolumeBaseConfig(rName string) string { - return testAccGatewayConfig_typeStored(rName) + fmt.Sprintf(` +func testAccStorediSCSIVolumeConfig_base(rName string) string { + return acctest.ConfigCompose(testAccGatewayConfig_typeStored(rName), fmt.Sprintf(` resource "aws_ebs_volume" "buffer" { availability_zone = aws_instance.test.availability_zone size = 10 @@ -322,11 +300,11 @@ data "aws_storagegateway_local_disk" "test" { disk_node = aws_volume_attachment.test.device_name gateway_arn = aws_storagegateway_gateway.test.arn } -`, rName) +`, rName)) } func testAccStorediSCSIVolumeConfig_basic(rName string) string { - return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccStorediSCSIVolumeConfig_base(rName), fmt.Sprintf(` resource "aws_storagegateway_stored_iscsi_volume" "test" { gateway_arn = data.aws_storagegateway_local_disk.test.gateway_arn network_interface_id = aws_instance.test.private_ip @@ -336,11 +314,11 @@ resource "aws_storagegateway_stored_iscsi_volume" "test" { depends_on = [aws_storagegateway_working_storage.buffer] } -`, rName) +`, rName)) } func testAccStorediSCSIVolumeConfig_kmsEncrypted(rName string) string { - return testAccStorediSCSIVolumeBaseConfig(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccStorediSCSIVolumeConfig_base(rName), fmt.Sprintf(` resource "aws_kms_key" "test" { description = "Terraform acc test %[1]s" policy = < Date: Mon, 29 Jul 2024 16:30:50 -0400 Subject: [PATCH 33/39] Add 'findTapePoolByARN'. --- .../storagegateway/cached_iscsi_volume.go | 2 +- .../service/storagegateway/exports_test.go | 1 + .../storagegateway/file_system_association.go | 2 +- .../service/storagegateway/nfs_file_share.go | 2 +- .../service/storagegateway/smb_file_share.go | 2 +- .../storagegateway/stored_iscsi_volume.go | 2 +- internal/service/storagegateway/tape_pool.go | 97 ++++++++++++------- .../service/storagegateway/tape_pool_test.go | 35 +++---- 8 files changed, 80 insertions(+), 63 deletions(-) diff --git a/internal/service/storagegateway/cached_iscsi_volume.go b/internal/service/storagegateway/cached_iscsi_volume.go index 03871d51a924..7dcfedec715b 100644 --- a/internal/service/storagegateway/cached_iscsi_volume.go +++ b/internal/service/storagegateway/cached_iscsi_volume.go @@ -287,7 +287,7 @@ func findCachediSCSIVolumes(ctx context.Context, conn *storagegateway.Client, in return nil, tfresource.NewEmptyResultError(input) } - return output.CachediSCSIVolumes, err + return output.CachediSCSIVolumes, nil } func parseVolumeGatewayARNAndTargetNameFromARN(inputARN string) (string, string, error) { diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index e70fff21353d..0a76563627d7 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -22,6 +22,7 @@ var ( FindNFSFileShareByARN = findNFSFileShareByARN FindSMBFileShareByARN = findSMBFileShareByARN FindStorediSCSIVolumeByARN = findStorediSCSIVolumeByARN + FindTapePoolByARN = findTapePoolByARN FindUploadBufferDisk = findUploadBufferDisk CacheParseResourceID = cacheParseResourceID diff --git a/internal/service/storagegateway/file_system_association.go b/internal/service/storagegateway/file_system_association.go index edcb2733e966..318123dc0267 100644 --- a/internal/service/storagegateway/file_system_association.go +++ b/internal/service/storagegateway/file_system_association.go @@ -264,7 +264,7 @@ func findFileSystemAssociations(ctx context.Context, conn *storagegateway.Client return nil, tfresource.NewEmptyResultError(input) } - return output.FileSystemAssociationInfoList, err + return output.FileSystemAssociationInfoList, nil } func statusFileSystemAssociation(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { diff --git a/internal/service/storagegateway/nfs_file_share.go b/internal/service/storagegateway/nfs_file_share.go index 75ca48b4c30b..ab2bfd96c6f5 100644 --- a/internal/service/storagegateway/nfs_file_share.go +++ b/internal/service/storagegateway/nfs_file_share.go @@ -432,7 +432,7 @@ func findNFSFileShares(ctx context.Context, conn *storagegateway.Client, input * return nil, tfresource.NewEmptyResultError(input) } - return output.NFSFileShareInfoList, err + return output.NFSFileShareInfoList, nil } func statusNFSFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { diff --git a/internal/service/storagegateway/smb_file_share.go b/internal/service/storagegateway/smb_file_share.go index 935fbf138988..fff3f832e2c0 100644 --- a/internal/service/storagegateway/smb_file_share.go +++ b/internal/service/storagegateway/smb_file_share.go @@ -503,7 +503,7 @@ func findSMBFileShares(ctx context.Context, conn *storagegateway.Client, input * return nil, tfresource.NewEmptyResultError(input) } - return output.SMBFileShareInfoList, err + return output.SMBFileShareInfoList, nil } func statusSMBFileShare(ctx context.Context, conn *storagegateway.Client, arn string) retry.StateRefreshFunc { diff --git a/internal/service/storagegateway/stored_iscsi_volume.go b/internal/service/storagegateway/stored_iscsi_volume.go index 6d8ad3a73dc1..5c9d1e607e67 100644 --- a/internal/service/storagegateway/stored_iscsi_volume.go +++ b/internal/service/storagegateway/stored_iscsi_volume.go @@ -298,7 +298,7 @@ func findStorediSCSIVolumes(ctx context.Context, conn *storagegateway.Client, in return nil, tfresource.NewEmptyResultError(input) } - return output.StorediSCSIVolumes, err + return output.StorediSCSIVolumes, nil } func statusStorediSCSIVolume(ctx context.Context, conn *storagegateway.Client, volumeARN string) retry.StateRefreshFunc { diff --git a/internal/service/storagegateway/tape_pool.go b/internal/service/storagegateway/tape_pool.go index dca2ed671ec0..3c06d4489e7b 100644 --- a/internal/service/storagegateway/tape_pool.go +++ b/internal/service/storagegateway/tape_pool.go @@ -18,6 +18,7 @@ import ( "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" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -46,11 +47,12 @@ func resourceTapePool() *schema.Resource { ForceNew: true, ValidateFunc: validation.StringLenBetween(1, 100), }, - names.AttrStorageClass: { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateDiagFunc: enum.Validate[awstypes.TapeStorageClass](), + "retention_lock_time_in_days": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 0, + ValidateFunc: validation.IntBetween(0, 36500), }, "retention_lock_type": { Type: schema.TypeString, @@ -59,12 +61,11 @@ func resourceTapePool() *schema.Resource { ForceNew: true, ValidateDiagFunc: enum.Validate[awstypes.RetentionLockType](), }, - "retention_lock_time_in_days": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - Default: 0, - ValidateFunc: validation.IntBetween(0, 36500), + names.AttrStorageClass: { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.TapeStorageClass](), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -78,18 +79,19 @@ func resourceTapePoolCreate(ctx context.Context, d *schema.ResourceData, meta in var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) + name := d.Get("pool_name").(string) input := &storagegateway.CreateTapePoolInput{ - PoolName: aws.String(d.Get("pool_name").(string)), + PoolName: aws.String(name), StorageClass: awstypes.TapeStorageClass(d.Get(names.AttrStorageClass).(string)), RetentionLockType: awstypes.RetentionLockType(d.Get("retention_lock_type").(string)), RetentionLockTimeInDays: aws.Int32(int32(d.Get("retention_lock_time_in_days").(int))), Tags: getTagsIn(ctx), } - log.Printf("[DEBUG] Creating Storage Gateway Tape Pool: %#v", input) output, err := conn.CreateTapePool(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Tape Pool: %s", err) + return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Tape Pool (%s): %s", name, err) } d.SetId(aws.ToString(output.PoolARN)) @@ -101,27 +103,19 @@ func resourceTapePoolRead(ctx context.Context, d *schema.ResourceData, meta inte var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.ListTapePoolsInput{ - PoolARNs: []string{d.Id()}, - } - - log.Printf("[DEBUG] Reading Storage Gateway Tape Pool: %#v", input) - output, err := conn.ListTapePools(ctx, input) + pool, err := findTapePoolByARN(ctx, conn, d.Id()) - if err != nil { - return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Tape Pools: %s", err) - } - - if output == nil || len(output.PoolInfos) == 0 || aws.ToString(output.PoolInfos[0].PoolARN) != d.Id() { - log.Printf("[WARN] Storage Gateway Tape Pool %q not found, removing from state", d.Id()) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Storage Gateway Tape Pool (%s) not found, removing from state", d.Id()) d.SetId("") return diags } - pool := output.PoolInfos[0] + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Tape Pool (%s): %s", d.Id(), err) + } - poolArn := aws.ToString(pool.PoolARN) - d.Set(names.AttrARN, poolArn) + d.Set(names.AttrARN, pool.PoolARN) d.Set("pool_name", pool.PoolName) d.Set("retention_lock_time_in_days", pool.RetentionLockTimeInDays) d.Set("retention_lock_type", pool.RetentionLockType) @@ -142,20 +136,53 @@ func resourceTapePoolDelete(ctx context.Context, d *schema.ResourceData, meta in var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.DeleteTapePoolInput{ + log.Printf("[DEBUG] Deleting Storage Gateway Tape Pool: %s", d.Id()) + _, err := conn.DeleteTapePool(ctx, &storagegateway.DeleteTapePoolInput{ PoolARN: aws.String(d.Id()), - } - - log.Printf("[DEBUG] Deleting Storage Gateway Tape Pool: %#v", input) - _, err := conn.DeleteTapePool(ctx, input) + }) if errs.IsAErrorMessageContains[*awstypes.InvalidGatewayRequestException](err, "The specified pool was not found") { return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Tape Pool %q: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway Tape Pool (%s): %s", d.Id(), err) } return diags } + +func findTapePoolByARN(ctx context.Context, conn *storagegateway.Client, arn string) (*awstypes.PoolInfo, error) { + input := &storagegateway.ListTapePoolsInput{ + PoolARNs: []string{arn}, + } + + return findTapePool(ctx, conn, input) +} + +func findTapePool(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListTapePoolsInput) (*awstypes.PoolInfo, error) { + output, err := findTapePools(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTapePools(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListTapePoolsInput) ([]awstypes.PoolInfo, error) { + var output []awstypes.PoolInfo + + pages := storagegateway.NewListTapePoolsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.PoolInfos...) + } + + return output, nil +} diff --git a/internal/service/storagegateway/tape_pool_test.go b/internal/service/storagegateway/tape_pool_test.go index fa0098e2b8a8..a94faf6970de 100644 --- a/internal/service/storagegateway/tape_pool_test.go +++ b/internal/service/storagegateway/tape_pool_test.go @@ -9,8 +9,6 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -18,6 +16,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" tfstoragegateway "github.com/hashicorp/terraform-provider-aws/internal/service/storagegateway" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -155,30 +154,22 @@ func TestAccStorageGatewayTapePool_disappears(t *testing.T) { }) } -func testAccCheckTapePoolExists(ctx context.Context, resourceName string, TapePool *awstypes.PoolInfo) resource.TestCheckFunc { +func testAccCheckTapePoolExists(ctx context.Context, n string, v *awstypes.PoolInfo) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.ListTapePoolsInput{ - PoolARNs: []string{rs.Primary.ID}, - } - - output, err := conn.ListTapePools(ctx, input) + output, err := tfstoragegateway.FindTapePoolByARN(ctx, conn, rs.Primary.ID) if err != nil { - return fmt.Errorf("error reading Storage Gateway Tape Pool: %s", err) - } - - if output == nil || len(output.PoolInfos) == 0 || aws.ToString(output.PoolInfos[0].PoolARN) != rs.Primary.ID { - return fmt.Errorf("Storage Gateway Tape Pool %q not found", rs.Primary.ID) + return err } - *TapePool = output.PoolInfos[0] + *v = *output return nil } @@ -193,19 +184,17 @@ func testAccCheckTapePoolDestroy(ctx context.Context) resource.TestCheckFunc { continue } - input := &storagegateway.ListTapePoolsInput{ - PoolARNs: []string{rs.Primary.ID}, - } + _, err := tfstoragegateway.FindTapePoolByARN(ctx, conn, rs.Primary.ID) - output, err := conn.ListTapePools(ctx, input) + if tfresource.NotFound(err) { + continue + } if err != nil { return err } - if len(output.PoolInfos) != 0 { - return fmt.Errorf("Storage Gateway Tape Pool %q not found", rs.Primary.ID) - } + return fmt.Errorf("Storage Gateway Tape Pool %s still exists", rs.Primary.ID) } return nil From 44c3acf48aa40aec46404d5bb9809ea83bbec095 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 30 Jul 2024 16:49:07 -0400 Subject: [PATCH 34/39] r/aws_storagegateway_upload_buffer: Cosmetics. --- internal/service/storagegateway/cache.go | 2 +- internal/service/storagegateway/cache_test.go | 2 +- .../service/storagegateway/exports_test.go | 21 ++- internal/service/storagegateway/find.go | 85 --------- .../storagegateway/local_disk_data_source.go | 34 +--- .../service/storagegateway/upload_buffer.go | 167 +++++++++++++----- .../storagegateway/upload_buffer_test.go | 39 ++-- 7 files changed, 158 insertions(+), 192 deletions(-) delete mode 100644 internal/service/storagegateway/find.go diff --git a/internal/service/storagegateway/cache.go b/internal/service/storagegateway/cache.go index c2194fb30bf7..eb4d7244b3ed 100644 --- a/internal/service/storagegateway/cache.go +++ b/internal/service/storagegateway/cache.go @@ -139,7 +139,7 @@ func cacheParseResourceID(id string) (string, string, error) { return "", "", idFormatErr } // gatewayARNAndDisk.Resource = gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 - resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, ":", 2) + resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, cacheResourceIDSeparator, 2) if len(resourceParts) != 2 { return "", "", idFormatErr } diff --git a/internal/service/storagegateway/cache_test.go b/internal/service/storagegateway/cache_test.go index b4ea71e6f0b4..a53ceed120c4 100644 --- a/internal/service/storagegateway/cache_test.go +++ b/internal/service/storagegateway/cache_test.go @@ -17,7 +17,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func TestDecodeCacheID(t *testing.T) { +func TestCacheParseResourceID(t *testing.T) { t.Parallel() var testCases = []struct { diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index 0a76563627d7..5d5b303f9400 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -15,19 +15,18 @@ var ( ResourceTapePool = resourceTapePool ResourceUploadBuffer = resourceUploadBuffer - FindCacheByTwoPartKey = findCacheByTwoPartKey - FindCachediSCSIVolumeByARN = findCachediSCSIVolumeByARN - FindFileSystemAssociationByARN = findFileSystemAssociationByARN - FindGatewayByARN = findGatewayByARN - FindNFSFileShareByARN = findNFSFileShareByARN - FindSMBFileShareByARN = findSMBFileShareByARN - FindStorediSCSIVolumeByARN = findStorediSCSIVolumeByARN - FindTapePoolByARN = findTapePoolByARN - FindUploadBufferDisk = findUploadBufferDisk + FindCacheByTwoPartKey = findCacheByTwoPartKey + FindCachediSCSIVolumeByARN = findCachediSCSIVolumeByARN + FindFileSystemAssociationByARN = findFileSystemAssociationByARN + FindGatewayByARN = findGatewayByARN + FindNFSFileShareByARN = findNFSFileShareByARN + FindSMBFileShareByARN = findSMBFileShareByARN + FindStorediSCSIVolumeByARN = findStorediSCSIVolumeByARN + FindTapePoolByARN = findTapePoolByARN + FindUploadBufferDiskIDByTwoPartKey = findUploadBufferDiskIDByTwoPartKey CacheParseResourceID = cacheParseResourceID - DecodeUploadBufferID = decodeUploadBufferID + UploadBufferParseResourceID = uploadBufferParseResourceID DecodeWorkingStorageID = decodeWorkingStorageID - IsGatewayNotFoundErr = isGatewayNotFoundErr ParseVolumeGatewayARNAndTargetNameFromARN = parseVolumeGatewayARNAndTargetNameFromARN ) diff --git a/internal/service/storagegateway/find.go b/internal/service/storagegateway/find.go deleted file mode 100644 index c4e25debb018..000000000000 --- a/internal/service/storagegateway/find.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package storagegateway - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" - awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/types" - tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" -) - -func findLocalDisk(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[awstypes.Disk]) (*awstypes.Disk, error) { - output, err := findLocalDisks(ctx, conn, input, filter) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLocalDisks(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[awstypes.Disk]) ([]awstypes.Disk, error) { - output, err := conn.ListLocalDisks(ctx, input) - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return tfslices.Filter(output.Disks, filter), nil -} - -func findLocalDiskByGatewayARNAndDiskID(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskID string) (*awstypes.Disk, error) { - input := &storagegateway.ListLocalDisksInput{ - GatewayARN: aws.String(gatewayARN), - } - - return findLocalDisk(ctx, conn, input, func(v awstypes.Disk) bool { - return aws.ToString(v.DiskId) == diskID - }) -} - -func findLocalDiskByGatewayARNAndDiskPath(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskPath string) (*awstypes.Disk, error) { - input := &storagegateway.ListLocalDisksInput{ - GatewayARN: aws.String(gatewayARN), - } - - return findLocalDisk(ctx, conn, input, func(v awstypes.Disk) bool { - return aws.ToString(v.DiskPath) == diskPath - }) -} - -func findUploadBufferDisk(ctx context.Context, conn *storagegateway.Client, gatewayARN string, diskID string) (*string, error) { - input := &storagegateway.DescribeUploadBufferInput{ - GatewayARN: aws.String(gatewayARN), - } - - var result string - - output, err := conn.DescribeUploadBuffer(ctx, input) - - if err != nil { - return nil, err - } - - if output == nil { - return nil, nil - } - - for _, diskId := range output.DiskIds { - if diskId == diskID { - result = diskId - break - } - } - - return &result, err -} diff --git a/internal/service/storagegateway/local_disk_data_source.go b/internal/service/storagegateway/local_disk_data_source.go index 4c9c4ca1699b..fff7ee4257fc 100644 --- a/internal/service/storagegateway/local_disk_data_source.go +++ b/internal/service/storagegateway/local_disk_data_source.go @@ -13,6 +13,7 @@ import ( "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/sdkdiag" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -53,39 +54,20 @@ func dataSourceLocalDiskRead(ctx context.Context, d *schema.ResourceData, meta i GatewayARN: aws.String(d.Get("gateway_arn").(string)), } - output, err := conn.ListLocalDisks(ctx, input) - - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Local Disks: %s", err) - } - - if output == nil || len(output.Disks) == 0 { - return sdkdiag.AppendErrorf(diags, "no results found for query, try adjusting your search criteria") - } - - var matchingDisks []awstypes.Disk - - for _, disk := range output.Disks { + disk, err := findLocalDisk(ctx, conn, input, func(disk awstypes.Disk) bool { if v, ok := d.GetOk("disk_node"); ok && v.(string) == aws.ToString(disk.DiskNode) { - matchingDisks = append(matchingDisks, disk) - continue + return true } if v, ok := d.GetOk("disk_path"); ok && v.(string) == aws.ToString(disk.DiskPath) { - matchingDisks = append(matchingDisks, disk) - continue + return true } - } - - if len(matchingDisks) == 0 { - return sdkdiag.AppendErrorf(diags, "no results found for query, try adjusting your search criteria") - } + return false + }) - if len(matchingDisks) > 1 { - return sdkdiag.AppendErrorf(diags, "multiple results found for query, try adjusting your search criteria") + if err != nil { + return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("Storage Gateway Local Disk", err)) } - disk := matchingDisks[0] - d.SetId(aws.ToString(disk.DiskId)) d.Set("disk_id", disk.DiskId) d.Set("disk_node", disk.DiskNode) diff --git a/internal/service/storagegateway/upload_buffer.go b/internal/service/storagegateway/upload_buffer.go index 42de03b232d3..45b77671cc4e 100644 --- a/internal/service/storagegateway/upload_buffer.go +++ b/internal/service/storagegateway/upload_buffer.go @@ -12,10 +12,14 @@ import ( "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/storagegateway" + awstypes "github.com/aws/aws-sdk-go-v2/service/storagegateway/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/sdkdiag" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -59,48 +63,45 @@ func resourceUploadBufferCreate(ctx context.Context, d *schema.ResourceData, met var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - input := &storagegateway.AddUploadBufferInput{} - - if v, ok := d.GetOk("disk_id"); ok { - input.DiskIds = []string{v.(string)} + diskID := d.Get("disk_id").(string) + gatewayARN := d.Get("gateway_arn").(string) + input := &storagegateway.AddUploadBufferInput{ + GatewayARN: aws.String(gatewayARN), } - // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17809 - if v, ok := d.GetOk("disk_path"); ok { - input.DiskIds = []string{v.(string)} + if diskID != "" { + input.DiskIds = []string{diskID} } - if v, ok := d.GetOk("gateway_arn"); ok { - input.GatewayARN = aws.String(v.(string)) + // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17809. + var diskPath string + if v, ok := d.GetOk("disk_path"); ok { + diskPath = v.(string) + input.DiskIds = []string{diskPath} } output, err := conn.AddUploadBuffer(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "adding Storage Gateway upload buffer: %s", err) + return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Upload Buffer: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "adding Storage Gateway upload buffer: empty response") - } + gatewayARN = aws.ToString(output.GatewayARN) - if v, ok := d.GetOk("disk_id"); ok { - d.SetId(fmt.Sprintf("%s:%s", aws.ToString(output.GatewayARN), v.(string))) + if diskID != "" { + d.SetId(uploadBufferCreateResourceID(gatewayARN, diskID)) return append(diags, resourceUploadBufferRead(ctx, d, meta)...) } - disk, err := findLocalDiskByGatewayARNAndDiskPath(ctx, conn, aws.ToString(output.GatewayARN), input.DiskIds[0]) + disk, err := findLocalDiskByGatewayARNAndDiskPath(ctx, conn, aws.ToString(output.GatewayARN), diskPath) if err != nil { - return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks after creating Upload Buffer: %s", err) - } - - if disk == nil { - return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks after creating Upload Buffer: disk not found") + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Local Disk (%s): %s", diskPath, err) } - d.SetId(fmt.Sprintf("%s:%s", aws.ToString(output.GatewayARN), aws.ToString(disk.DiskId))) + diskID = aws.ToString(disk.DiskId) + d.SetId(uploadBufferCreateResourceID(gatewayARN, diskID)) return append(diags, resourceUploadBufferRead(ctx, d, meta)...) } @@ -109,14 +110,14 @@ func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - gatewayARN, diskID, err := decodeUploadBufferID(d.Id()) + gatewayARN, diskID, err := uploadBufferParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Upload Buffer (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } - foundDiskID, err := findUploadBufferDisk(ctx, conn, gatewayARN, diskID) + foundDiskID, err := findUploadBufferDiskIDByTwoPartKey(ctx, conn, gatewayARN, diskID) - if !d.IsNewResource() && isGatewayNotFoundErr(err) { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway Upload Buffer (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -126,28 +127,15 @@ func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Upload Buffer (%s): %s", d.Id(), err) } - if foundDiskID == nil { - if d.IsNewResource() { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Upload Buffer (%s): not found", d.Id()) - } - - log.Printf("[WARN] Storage Gateway Upload Buffer (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags - } - d.Set("disk_id", foundDiskID) d.Set("gateway_arn", gatewayARN) if _, ok := d.GetOk("disk_path"); !ok { - disk, err := findLocalDiskByGatewayARNAndDiskID(ctx, conn, gatewayARN, aws.ToString(foundDiskID)) + diskID := aws.ToString(foundDiskID) + disk, err := findLocalDiskByGatewayARNAndDiskID(ctx, conn, gatewayARN, diskID) if err != nil { - return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks: %s", err) - } - - if disk == nil { - return sdkdiag.AppendErrorf(diags, "listing Storage Gateway Local Disks: disk not found") + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Local Disk (%s): %s", diskID, err) } d.Set("disk_path", disk.DiskPath) @@ -156,15 +144,24 @@ func resourceUploadBufferRead(ctx context.Context, d *schema.ResourceData, meta return diags } -func decodeUploadBufferID(id string) (string, string, error) { +const uploadBufferResourceIDSeparator = ":" + +func uploadBufferCreateResourceID(gatewayARN, diskID string) string { + parts := []string{gatewayARN, diskID} + id := strings.Join(parts, uploadBufferResourceIDSeparator) + + return id +} + +func uploadBufferParseResourceID(id string) (string, string, error) { // id = arn:aws:storagegateway:us-east-1:123456789012:gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 - idFormatErr := fmt.Errorf("expected ID in form of GatewayARN:DiskId, received: %s", id) + idFormatErr := fmt.Errorf("unexpected format for ID (%[1]s), expected GatewayARN%[2]sDiskID", id, uploadBufferResourceIDSeparator) gatewayARNAndDisk, err := arn.Parse(id) if err != nil { return "", "", idFormatErr } // gatewayARNAndDisk.Resource = gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 - resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, ":", 2) + resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, uploadBufferResourceIDSeparator, 2) if len(resourceParts) != 2 { return "", "", idFormatErr } @@ -178,3 +175,83 @@ func decodeUploadBufferID(id string) (string, string, error) { } return gatewayARN.String(), resourceParts[1], nil } + +func findLocalDiskByGatewayARNAndDiskID(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskID string) (*awstypes.Disk, error) { + input := &storagegateway.ListLocalDisksInput{ + GatewayARN: aws.String(gatewayARN), + } + + return findLocalDisk(ctx, conn, input, func(v awstypes.Disk) bool { + return aws.ToString(v.DiskId) == diskID + }) +} + +func findLocalDiskByGatewayARNAndDiskPath(ctx context.Context, conn *storagegateway.Client, gatewayARN, diskPath string) (*awstypes.Disk, error) { + input := &storagegateway.ListLocalDisksInput{ + GatewayARN: aws.String(gatewayARN), + } + + return findLocalDisk(ctx, conn, input, func(v awstypes.Disk) bool { + return aws.ToString(v.DiskPath) == diskPath + }) +} + +func findLocalDisk(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[awstypes.Disk]) (*awstypes.Disk, error) { + output, err := findLocalDisks(ctx, conn, input, filter) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findLocalDisks(ctx context.Context, conn *storagegateway.Client, input *storagegateway.ListLocalDisksInput, filter tfslices.Predicate[awstypes.Disk]) ([]awstypes.Disk, error) { + output, err := conn.ListLocalDisks(ctx, input) + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return tfslices.Filter(output.Disks, filter), nil +} + +func findUploadBufferDiskIDByTwoPartKey(ctx context.Context, conn *storagegateway.Client, gatewayARN string, diskID string) (*string, error) { + input := &storagegateway.DescribeUploadBufferInput{ + GatewayARN: aws.String(gatewayARN), + } + output, err := findUploadBuffer(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(tfslices.Filter(output.DiskIds, func(v string) bool { + return v == diskID + })) +} + +func findUploadBuffer(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeUploadBufferInput) (*storagegateway.DescribeUploadBufferOutput, error) { + output, err := conn.DescribeUploadBuffer(ctx, input) + + if isGatewayNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} diff --git a/internal/service/storagegateway/upload_buffer_test.go b/internal/service/storagegateway/upload_buffer_test.go index a49fa7dd26af..8aceb85b966e 100644 --- a/internal/service/storagegateway/upload_buffer_test.go +++ b/internal/service/storagegateway/upload_buffer_test.go @@ -18,7 +18,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func TestDecodeUploadBufferID(t *testing.T) { +func TestUploadBufferParseResourceID(t *testing.T) { t.Parallel() var testCases = []struct { @@ -60,7 +60,7 @@ func TestDecodeUploadBufferID(t *testing.T) { } for _, tc := range testCases { - gatewayARN, diskID, err := tfstoragegateway.DecodeUploadBufferID(tc.Input) + gatewayARN, diskID, err := tfstoragegateway.UploadBufferParseResourceID(tc.Input) if tc.ErrCount == 0 && err != nil { t.Fatalf("expected %q not to trigger an error, received: %s", tc.Input, err) } @@ -87,9 +87,8 @@ func TestAccStorageGatewayUploadBuffer_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - // Storage Gateway API does not support removing upload buffers, - // but we want to ensure other resources are removed. - CheckDestroy: testAccCheckGatewayDestroy(ctx), + // Storage Gateway API does not support removing upload buffers. + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccUploadBufferConfig_diskID(rName), @@ -109,7 +108,7 @@ func TestAccStorageGatewayUploadBuffer_basic(t *testing.T) { }) } -// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17809 +// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17809. func TestAccStorageGatewayUploadBuffer_diskPath(t *testing.T) { ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -121,9 +120,7 @@ func TestAccStorageGatewayUploadBuffer_diskPath(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - // Storage Gateway API does not support removing upload buffers, - // but we want to ensure other resources are removed. - CheckDestroy: testAccCheckGatewayDestroy(ctx), + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccUploadBufferConfig_diskPath(rName), @@ -143,28 +140,24 @@ func TestAccStorageGatewayUploadBuffer_diskPath(t *testing.T) { }) } -func testAccCheckUploadBufferExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckUploadBufferExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) - gatewayARN, diskID, err := tfstoragegateway.DecodeUploadBufferID(rs.Primary.ID) + gatewayARN, diskID, err := tfstoragegateway.UploadBufferParseResourceID(rs.Primary.ID) if err != nil { return err } - foundDiskID, err := tfstoragegateway.FindUploadBufferDisk(ctx, conn, gatewayARN, diskID) + _, err = tfstoragegateway.FindUploadBufferDiskIDByTwoPartKey(ctx, conn, gatewayARN, diskID) if err != nil { - return fmt.Errorf("error reading Storage Gateway Upload Buffer (%s): %w", rs.Primary.ID, err) - } - - if foundDiskID == nil { - return fmt.Errorf("Storage Gateway Upload Buffer (%s) not found", rs.Primary.ID) + return err } return nil @@ -172,7 +165,7 @@ func testAccCheckUploadBufferExists(ctx context.Context, resourceName string) re } func testAccUploadBufferConfig_diskID(rName string) string { - return testAccGatewayConfig_typeStored(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_typeStored(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" @@ -199,11 +192,11 @@ resource "aws_storagegateway_upload_buffer" "test" { disk_id = data.aws_storagegateway_local_disk.test.id gateway_arn = aws_storagegateway_gateway.test.arn } -`, rName) +`, rName)) } func testAccUploadBufferConfig_diskPath(rName string) string { - return testAccGatewayConfig_typeCached(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_typeCached(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" @@ -230,5 +223,5 @@ resource "aws_storagegateway_upload_buffer" "test" { disk_path = data.aws_storagegateway_local_disk.test.disk_path gateway_arn = aws_storagegateway_gateway.test.arn } -`, rName) +`, rName)) } From c5246164d1fa8a65443547b592ba41dad29a6266 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 31 Jul 2024 08:01:36 -0400 Subject: [PATCH 35/39] r/aws_storagegateway_working_storage: Add 'findWorkingStorageDiskIDByTwoPartKey'. --- .../service/storagegateway/exports_test.go | 23 ++--- .../service/storagegateway/working_storage.go | 96 ++++++++++++------- .../storagegateway/working_storage_test.go | 43 +++------ 3 files changed, 86 insertions(+), 76 deletions(-) diff --git a/internal/service/storagegateway/exports_test.go b/internal/service/storagegateway/exports_test.go index 5d5b303f9400..83ae1d93f243 100644 --- a/internal/service/storagegateway/exports_test.go +++ b/internal/service/storagegateway/exports_test.go @@ -15,18 +15,19 @@ var ( ResourceTapePool = resourceTapePool ResourceUploadBuffer = resourceUploadBuffer - FindCacheByTwoPartKey = findCacheByTwoPartKey - FindCachediSCSIVolumeByARN = findCachediSCSIVolumeByARN - FindFileSystemAssociationByARN = findFileSystemAssociationByARN - FindGatewayByARN = findGatewayByARN - FindNFSFileShareByARN = findNFSFileShareByARN - FindSMBFileShareByARN = findSMBFileShareByARN - FindStorediSCSIVolumeByARN = findStorediSCSIVolumeByARN - FindTapePoolByARN = findTapePoolByARN - FindUploadBufferDiskIDByTwoPartKey = findUploadBufferDiskIDByTwoPartKey + FindCacheByTwoPartKey = findCacheByTwoPartKey + FindCachediSCSIVolumeByARN = findCachediSCSIVolumeByARN + FindFileSystemAssociationByARN = findFileSystemAssociationByARN + FindGatewayByARN = findGatewayByARN + FindNFSFileShareByARN = findNFSFileShareByARN + FindSMBFileShareByARN = findSMBFileShareByARN + FindStorediSCSIVolumeByARN = findStorediSCSIVolumeByARN + FindTapePoolByARN = findTapePoolByARN + FindUploadBufferDiskIDByTwoPartKey = findUploadBufferDiskIDByTwoPartKey + FindWorkingStorageDiskIDByTwoPartKey = findWorkingStorageDiskIDByTwoPartKey CacheParseResourceID = cacheParseResourceID - UploadBufferParseResourceID = uploadBufferParseResourceID - DecodeWorkingStorageID = decodeWorkingStorageID ParseVolumeGatewayARNAndTargetNameFromARN = parseVolumeGatewayARNAndTargetNameFromARN + UploadBufferParseResourceID = uploadBufferParseResourceID + WorkingStorageParseResourceID = workingStorageParseResourceID ) diff --git a/internal/service/storagegateway/working_storage.go b/internal/service/storagegateway/working_storage.go index 4e0bf298764a..bd7d8d6d1ef6 100644 --- a/internal/service/storagegateway/working_storage.go +++ b/internal/service/storagegateway/working_storage.go @@ -13,9 +13,12 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/arn" "github.com/aws/aws-sdk-go-v2/service/storagegateway" "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/sdkdiag" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -52,19 +55,19 @@ func resourceWorkingStorageCreate(ctx context.Context, d *schema.ResourceData, m diskID := d.Get("disk_id").(string) gatewayARN := d.Get("gateway_arn").(string) - + id := workingStorageCreateResourceID(gatewayARN, diskID) input := &storagegateway.AddWorkingStorageInput{ DiskIds: []string{diskID}, GatewayARN: aws.String(gatewayARN), } - log.Printf("[DEBUG] Adding Storage Gateway Working Storage: %#v", input) _, err := conn.AddWorkingStorage(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "adding Storage Gateway Working Storage: %s", err) + return sdkdiag.AppendErrorf(diags, "creating Storage Gateway Working Storage (%s): %s", id, err) } - d.SetId(fmt.Sprintf("%s:%s", gatewayARN, diskID)) + d.SetId(id) return append(diags, resourceWorkingStorageRead(ctx, d, meta)...) } @@ -73,43 +76,21 @@ func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, met var diags diag.Diagnostics conn := meta.(*conns.AWSClient).StorageGatewayClient(ctx) - gatewayARN, diskID, err := decodeWorkingStorageID(d.Id()) + gatewayARN, diskID, err := workingStorageParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Working Storage (%s): %s", d.Id(), err) - } - - input := &storagegateway.DescribeWorkingStorageInput{ - GatewayARN: aws.String(gatewayARN), + return sdkdiag.AppendFromErr(diags, err) } - output, err := conn.DescribeWorkingStorage(ctx, input) - if err != nil { - if isGatewayNotFoundErr(err) { - log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags - } - return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Working Storage (%s): %s", d.Id(), err) - } + _, err = findWorkingStorageDiskIDByTwoPartKey(ctx, conn, gatewayARN, diskID) - if output == nil || len(output.DiskIds) == 0 { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) d.SetId("") return diags } - found := false - for _, existingDiskID := range output.DiskIds { - if existingDiskID == diskID { - found = true - break - } - } - - if !found { - log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Storage Gateway Working Storage (%s): %s", d.Id(), err) } d.Set("disk_id", diskID) @@ -118,15 +99,24 @@ func resourceWorkingStorageRead(ctx context.Context, d *schema.ResourceData, met return diags } -func decodeWorkingStorageID(id string) (string, string, error) { +const workingStorageResourceIDSeparator = ":" + +func workingStorageCreateResourceID(gatewayARN, diskID string) string { + parts := []string{gatewayARN, diskID} + id := strings.Join(parts, workingStorageResourceIDSeparator) + + return id +} + +func workingStorageParseResourceID(id string) (string, string, error) { // id = arn:aws:storagegateway:us-east-1:123456789012:gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 - idFormatErr := fmt.Errorf("expected ID in form of GatewayARN:DiskId, received: %s", id) + idFormatErr := fmt.Errorf("unexpected format for ID (%[1]s), expected GatewayARN%[2]sDiskID", id, workingStorageResourceIDSeparator) gatewayARNAndDisk, err := arn.Parse(id) if err != nil { return "", "", idFormatErr } // gatewayARNAndDisk.Resource = gateway/sgw-12345678:pci-0000:03:00.0-scsi-0:0:0:0 - resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, ":", 2) + resourceParts := strings.SplitN(gatewayARNAndDisk.Resource, workingStorageResourceIDSeparator, 2) if len(resourceParts) != 2 { return "", "", idFormatErr } @@ -140,3 +130,39 @@ func decodeWorkingStorageID(id string) (string, string, error) { } return gatewayARN.String(), resourceParts[1], nil } + +func findWorkingStorageDiskIDByTwoPartKey(ctx context.Context, conn *storagegateway.Client, gatewayARN string, diskID string) (*string, error) { + input := &storagegateway.DescribeWorkingStorageInput{ + GatewayARN: aws.String(gatewayARN), + } + output, err := findWorkingStorage(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(tfslices.Filter(output.DiskIds, func(v string) bool { + return v == diskID + })) +} + +func findWorkingStorage(ctx context.Context, conn *storagegateway.Client, input *storagegateway.DescribeWorkingStorageInput) (*storagegateway.DescribeWorkingStorageOutput, error) { + output, err := conn.DescribeWorkingStorage(ctx, input) + + if isGatewayNotFoundErr(err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} diff --git a/internal/service/storagegateway/working_storage_test.go b/internal/service/storagegateway/working_storage_test.go index b9ae1fbbce7e..4de9a84c6add 100644 --- a/internal/service/storagegateway/working_storage_test.go +++ b/internal/service/storagegateway/working_storage_test.go @@ -8,8 +8,6 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/storagegateway" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -19,7 +17,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func TestDecodeWorkingStorageID(t *testing.T) { +func TestWorkingStorageParseResourceID(t *testing.T) { t.Parallel() var testCases = []struct { @@ -61,7 +59,7 @@ func TestDecodeWorkingStorageID(t *testing.T) { } for _, tc := range testCases { - gatewayARN, diskID, err := tfstoragegateway.DecodeWorkingStorageID(tc.Input) + gatewayARN, diskID, err := tfstoragegateway.WorkingStorageParseResourceID(tc.Input) if tc.ErrCount == 0 && err != nil { t.Fatalf("expected %q not to trigger an error, received: %s", tc.Input, err) } @@ -88,9 +86,8 @@ func TestAccStorageGatewayWorkingStorage_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.StorageGatewayServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - // Storage Gateway API does not support removing working storages, - // but we want to ensure other resources are removed. - CheckDestroy: testAccCheckGatewayDestroy(ctx), + // Storage Gateway API does not support removing working storages. + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccWorkingStorageConfig_basic(rName), @@ -109,46 +106,32 @@ func TestAccStorageGatewayWorkingStorage_basic(t *testing.T) { }) } -func testAccCheckWorkingStorageExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckWorkingStorageExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).StorageGatewayClient(ctx) - gatewayARN, diskID, err := tfstoragegateway.DecodeWorkingStorageID(rs.Primary.ID) + gatewayARN, diskID, err := tfstoragegateway.WorkingStorageParseResourceID(rs.Primary.ID) if err != nil { return err } - input := &storagegateway.DescribeWorkingStorageInput{ - GatewayARN: aws.String(gatewayARN), - } - - output, err := conn.DescribeWorkingStorage(ctx, input) + _, err = tfstoragegateway.FindWorkingStorageDiskIDByTwoPartKey(ctx, conn, gatewayARN, diskID) if err != nil { - return fmt.Errorf("error reading Storage Gateway working storage: %s", err) - } - - if output == nil || len(output.DiskIds) == 0 { - return fmt.Errorf("Storage Gateway working storage %q not found", rs.Primary.ID) - } - - for _, existingDiskID := range output.DiskIds { - if existingDiskID == diskID { - return nil - } + return err } - return fmt.Errorf("Storage Gateway working storage %q not found", rs.Primary.ID) + return nil } } func testAccWorkingStorageConfig_basic(rName string) string { - return testAccGatewayConfig_typeStored(rName) + fmt.Sprintf(` + return acctest.ConfigCompose(testAccGatewayConfig_typeStored(rName), fmt.Sprintf(` resource "aws_ebs_volume" "test" { availability_zone = aws_instance.test.availability_zone size = "10" @@ -175,5 +158,5 @@ resource "aws_storagegateway_working_storage" "test" { disk_id = data.aws_storagegateway_local_disk.test.id gateway_arn = aws_storagegateway_gateway.test.arn } -`, rName) +`, rName)) } From 2864aecb311bcfdc24d7aa693e558da136be62b7 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 31 Jul 2024 08:05:24 -0400 Subject: [PATCH 36/39] storagegateway: Tweak 'operationErrorCode'. --- internal/service/storagegateway/errors.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/service/storagegateway/errors.go b/internal/service/storagegateway/errors.go index f7b759e09136..99f064a8cf40 100644 --- a/internal/service/storagegateway/errors.go +++ b/internal/service/storagegateway/errors.go @@ -10,11 +10,11 @@ import ( ) // Operation error code constants missing from AWS Go SDK: https://docs.aws.amazon.com/sdk-for-go/api/service/storagegateway/#pkg-constants. -// See https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIOperationErrorCodes for details. +// See e.g. https://docs.aws.amazon.com/filegateway/latest/files3/AWSStorageGatewayAPI.html#APIOperationErrorCodes for details. const ( - operationErrCodeFileShareNotFound = "FileShareNotFound" - operationErrCodeFileSystemAssociationNotFound = "FileSystemAssociationNotFound" - operationErrCodeGatewayNotFound = "GatewayNotFound" + operationErrCodeFileShareNotFound awstypes.ErrorCode = "FileShareNotFound" + operationErrCodeFileSystemAssociationNotFound awstypes.ErrorCode = "FileSystemAssociationNotFound" + operationErrCodeGatewayNotFound awstypes.ErrorCode = "GatewayNotFound" ) // operationErrorCode returns the operation error code from the specified error: @@ -22,13 +22,13 @@ const ( // - Error_ is not nil // // See https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIErrorResponses for details. -func operationErrorCode(err error) string { +func operationErrorCode(err error) awstypes.ErrorCode { if v, ok := errs.As[*awstypes.InternalServerError](err); ok && v.Error_ != nil { - return string(v.Error_.ErrorCode) + return v.Error_.ErrorCode } if v, ok := errs.As[*awstypes.InvalidGatewayRequestException](err); ok && v.Error_ != nil { - return string(v.Error_.ErrorCode) + return v.Error_.ErrorCode } return "" From 4ab7daa88af0ffad79a4e7b6e57799dd20234baf Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 31 Jul 2024 08:15:38 -0400 Subject: [PATCH 37/39] r/aws_storagegateway_file_system_association: Add configurable timeouts. --- .changelog/38554.txt | 3 +++ internal/service/storagegateway/consts.go | 10 ---------- .../storagegateway/file_system_association.go | 12 +++++++++--- ...ragegateway_file_system_association.html.markdown | 8 ++++++++ 4 files changed, 20 insertions(+), 13 deletions(-) create mode 100644 .changelog/38554.txt diff --git a/.changelog/38554.txt b/.changelog/38554.txt new file mode 100644 index 000000000000..22d1395360f9 --- /dev/null +++ b/.changelog/38554.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_storagegateway_file_system_association: Add configurable timeouts +``` \ No newline at end of file diff --git a/internal/service/storagegateway/consts.go b/internal/service/storagegateway/consts.go index de7e6d2d97dc..bad376ed5a69 100644 --- a/internal/service/storagegateway/consts.go +++ b/internal/service/storagegateway/consts.go @@ -3,10 +3,6 @@ package storagegateway -import ( - "time" -) - const ( authenticationActiveDirectory = "ActiveDirectory" authenticationGuestAccess = "GuestAccess" @@ -107,12 +103,6 @@ const ( fileShareStatusUpdating = "UPDATING" ) -const ( - fileSystemAssociationCreateTimeout = 10 * time.Minute - fileSystemAssociationUpdateTimeout = 10 * time.Minute - fileSystemAssociationDeleteTimeout = 10 * time.Minute -) - const ( fileSystemAssociationStatusAvailable = "AVAILABLE" fileSystemAssociationStatusCreating = "CREATING" diff --git a/internal/service/storagegateway/file_system_association.go b/internal/service/storagegateway/file_system_association.go index 318123dc0267..bc341bab447b 100644 --- a/internal/service/storagegateway/file_system_association.go +++ b/internal/service/storagegateway/file_system_association.go @@ -43,6 +43,12 @@ func resourceFileSystemAssociation() *schema.Resource { StateContext: schema.ImportStatePassthroughContext, }, + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + }, + Schema: map[string]*schema.Schema{ names.AttrARN: { Type: schema.TypeString, @@ -138,7 +144,7 @@ func resourceFileSystemAssociationCreate(ctx context.Context, d *schema.Resource d.SetId(aws.ToString(output.FileSystemAssociationARN)) - if _, err = waitFileSystemAssociationAvailable(ctx, conn, d.Id(), fileSystemAssociationCreateTimeout); err != nil { + if _, err = waitFileSystemAssociationAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway File System Association (%s) create: %s", d.Id(), err) } @@ -196,7 +202,7 @@ func resourceFileSystemAssociationUpdate(ctx context.Context, d *schema.Resource return sdkdiag.AppendErrorf(diags, "updating Storage Gateway File System Association (%s): %s", d.Id(), err) } - if _, err = waitFileSystemAssociationAvailable(ctx, conn, d.Id(), fileSystemAssociationUpdateTimeout); err != nil { + if _, err = waitFileSystemAssociationAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway File System Association (%s) update: %s", d.Id(), err) } } @@ -221,7 +227,7 @@ func resourceFileSystemAssociationDelete(ctx context.Context, d *schema.Resource return sdkdiag.AppendErrorf(diags, "deleting Storage Gateway File System Association (%s): %s", d.Id(), err) } - if _, err = waitFileSystemAssociationDeleted(ctx, conn, d.Id(), fileSystemAssociationDeleteTimeout); err != nil { + if _, err = waitFileSystemAssociationDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Storage Gateway File System Association (%s) delete: %s", d.Id(), err) } diff --git a/website/docs/r/storagegateway_file_system_association.html.markdown b/website/docs/r/storagegateway_file_system_association.html.markdown index c989e19cc411..98cd3308a71a 100644 --- a/website/docs/r/storagegateway_file_system_association.html.markdown +++ b/website/docs/r/storagegateway_file_system_association.html.markdown @@ -104,6 +104,14 @@ This resource exports the following attributes in addition to the arguments abov * `arn` - Amazon Resource Name (ARN) of the newly created file system association. * `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block). +## Timeouts + +[Configuration options](https://developer.hashicorp.com/terraform/language/resources/syntax#operation-timeouts): + +- `create` - (Default `30m`) +- `update` - (Default `30m`) +- `delete` - (Default `30m`) + ## Import In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import `aws_storagegateway_file_system_association` using the FSx file system association Amazon Resource Name (ARN). For example: From dafc14b15fdef65017b08e88ba8f38bc36346519 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 31 Jul 2024 08:17:50 -0400 Subject: [PATCH 38/39] Fix semgrep 'dgryski.semgrep-go.errnilcheck.err-nil-check'. --- internal/service/storagegateway/upload_buffer_test.go | 6 +----- internal/service/storagegateway/working_storage_test.go | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/internal/service/storagegateway/upload_buffer_test.go b/internal/service/storagegateway/upload_buffer_test.go index 8aceb85b966e..608b40899808 100644 --- a/internal/service/storagegateway/upload_buffer_test.go +++ b/internal/service/storagegateway/upload_buffer_test.go @@ -156,11 +156,7 @@ func testAccCheckUploadBufferExists(ctx context.Context, n string) resource.Test _, err = tfstoragegateway.FindUploadBufferDiskIDByTwoPartKey(ctx, conn, gatewayARN, diskID) - if err != nil { - return err - } - - return nil + return err } } diff --git a/internal/service/storagegateway/working_storage_test.go b/internal/service/storagegateway/working_storage_test.go index 4de9a84c6add..6451ce3088c7 100644 --- a/internal/service/storagegateway/working_storage_test.go +++ b/internal/service/storagegateway/working_storage_test.go @@ -122,11 +122,7 @@ func testAccCheckWorkingStorageExists(ctx context.Context, n string) resource.Te _, err = tfstoragegateway.FindWorkingStorageDiskIDByTwoPartKey(ctx, conn, gatewayARN, diskID) - if err != nil { - return err - } - - return nil + return err } } From ce32cd70523dbef2ed659f04ad9443743edad8e6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 31 Jul 2024 15:06:29 -0400 Subject: [PATCH 39/39] Fix 'TestAccStorageGatewayLocalDiskDataSource_diskNode' and 'TestAccStorageGatewayLocalDiskDataSource_diskPath'. --- .../service/storagegateway/local_disk_data_source_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/storagegateway/local_disk_data_source_test.go b/internal/service/storagegateway/local_disk_data_source_test.go index d4214794de9f..a97cd02e8bf3 100644 --- a/internal/service/storagegateway/local_disk_data_source_test.go +++ b/internal/service/storagegateway/local_disk_data_source_test.go @@ -26,7 +26,7 @@ func TestAccStorageGatewayLocalDiskDataSource_diskNode(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccLocalDiskDataSourceConfig_nodeNonExistent(rName), - ExpectError: regexache.MustCompile(`no results found`), + ExpectError: regexache.MustCompile(`no matching Storage Gateway Local Disk found`), }, { Config: testAccLocalDiskDataSourceConfig_node(rName), @@ -52,7 +52,7 @@ func TestAccStorageGatewayLocalDiskDataSource_diskPath(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccLocalDiskDataSourceConfig_pathNonExistent(rName), - ExpectError: regexache.MustCompile(`no results found`), + ExpectError: regexache.MustCompile(`no matching Storage Gateway Local Disk found`), }, { Config: testAccLocalDiskDataSourceConfig_path(rName),