From 454d03e7ad39c9b210d4967ad5311951c3075517 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:18:56 +0100 Subject: [PATCH 01/24] elasticsearch: Migrate to AWS SDK v2 --- go.mod | 7 ++++--- go.sum | 14 ++++++++------ internal/conns/awsclient_gen.go | 6 +++--- names/data/names_data.hcl | 2 +- names/names.go | 1 + 5 files changed, 17 insertions(+), 13 deletions(-) diff --git a/go.mod b/go.mod index 7814509023f2..7af8a60065d5 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/YakDriver/go-version v0.1.0 github.com/YakDriver/regexache v0.23.0 github.com/aws/aws-sdk-go v1.54.4 - github.com/aws/aws-sdk-go-v2 v1.29.0 + github.com/aws/aws-sdk-go-v2 v1.30.0 github.com/aws/aws-sdk-go-v2/config v1.27.20 github.com/aws/aws-sdk-go-v2/credentials v1.17.20 github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.7 @@ -92,6 +92,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/elasticache v1.39.0 github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk v1.24.0 github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.32.0 + github.com/aws/aws-sdk-go-v2/service/elasticsearchservice v1.29.1 github.com/aws/aws-sdk-go-v2/service/emr v1.40.0 github.com/aws/aws-sdk-go-v2/service/emrserverless v1.22.0 github.com/aws/aws-sdk-go-v2/service/eventbridge v1.32.0 @@ -248,8 +249,8 @@ require ( github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/armon/go-radix v1.0.0 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.2 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.11 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.11 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.12 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.12 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.11 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.2 // indirect diff --git a/go.sum b/go.sum index 9bbd96de6b75..936c36bb4e88 100644 --- a/go.sum +++ b/go.sum @@ -24,8 +24,8 @@ github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aws/aws-sdk-go v1.54.4 h1:xZga3fPu7uxVgh83DIaQlb7r0cixFx1xKiiROTWAhpU= github.com/aws/aws-sdk-go v1.54.4/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU= -github.com/aws/aws-sdk-go-v2 v1.29.0 h1:uMlEecEwgp2gs6CsM6ugquNHr6mg0LHylPBR8u5Ojac= -github.com/aws/aws-sdk-go-v2 v1.29.0/go.mod h1:ffIFB97e2yNsv4aTSGkqtHnppsIJzw7G7BReUZ3jCXM= +github.com/aws/aws-sdk-go-v2 v1.30.0 h1:6qAwtzlfcTtcL8NHtbDQAqgM5s6NDipQTkPxyH/6kAA= +github.com/aws/aws-sdk-go-v2 v1.30.0/go.mod h1:ffIFB97e2yNsv4aTSGkqtHnppsIJzw7G7BReUZ3jCXM= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.2 h1:x6xsQXGSmW6frevwDA+vi/wqhp1ct18mVXYN08/93to= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.2/go.mod h1:lPprDr1e6cJdyYeGXnRaJoP4Md+cDBvi2eOj00BlGmg= github.com/aws/aws-sdk-go-v2/config v1.27.20 h1:oQSn/KNUMV54X0FBEDQQ2ymNfcKyMT81ar8gyvMzzqs= @@ -36,10 +36,10 @@ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.7 h1:54QUEXjkE1SlxHmRA3gBXA5 github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.7/go.mod h1:bQRjJsdSMzmo/qbtGeBtPbIMp1IgQ+9R9jYJLm12uJA= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.0 h1:51p4kCxB/9+QvBtg0KfwgTu10yiHuB9SrjbUE0d/vgw= github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.0/go.mod h1:FtmZRmuRxdLBk4P/JcvZncfbwvLobQYktVaVAF8cx9A= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.11 h1:ltkhl3I9ddcRR3Dsy+7bOFFq546O8OYsfNEXVIyuOSE= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.11/go.mod h1:H4D8JoCFNJwnT7U5U8iwgG24n71Fx2I/ZP/18eYFr9g= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.11 h1:+BgX2AY7yV4ggSwa80z/yZIJX+e0jnNxjMLVyfpSXM0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.11/go.mod h1:DlBATBSDCz30BCdRFldmyLsAzJwi2pdQ+YSdJTHhTUI= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.12 h1:SJ04WXGTwnHlWIODtC5kJzKbeuHt+OUNOgKg7nfnUGw= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.12/go.mod h1:FkpvXhA92gb3GE9LD6Og0pHHycTxW7xGpnEh5E7Opwo= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.12 h1:hb5KgeYfObi5MHkSSZMEudnIvX30iB+E21evI4r6BnQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.12/go.mod h1:CroKe/eWJdyfy9Vx4rljP5wTUjNJfb+fPz1uMYUhEGM= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY= github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.11 h1:jJ2dythFP5oNunvwc3gBsINl3ZPt/InVm4a5OAr3tag= @@ -204,6 +204,8 @@ github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk v1.24.0 h1:luQaJXM8g3MRZPE github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk v1.24.0/go.mod h1:72t1RRQNbuAt0wYiYmw6IshZETm5gkmr75zFrZopFLU= github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.32.0 h1:iMTooAw0vUOiY6byiaVQgtFUE2GsudZ9DTJwnmKb+K4= github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.32.0/go.mod h1:7dAQkaiNMiZGo0h3l5Il1v9E3eiqKW3DugEQmmJHoqo= +github.com/aws/aws-sdk-go-v2/service/elasticsearchservice v1.29.1 h1:XSqXGoV8j2ZAXUQU0aBbAk/pktbcC9FKn8/F2sA58zg= +github.com/aws/aws-sdk-go-v2/service/elasticsearchservice v1.29.1/go.mod h1:eC0gnV0MZwdJBeytsEaFPoQc3huZ+0rNjmXbXbCChrQ= github.com/aws/aws-sdk-go-v2/service/emr v1.40.0 h1:hWsQlAEHgHJIW2gkW+d+J4tPqZ9LRGBkvInZ3Mje9+A= github.com/aws/aws-sdk-go-v2/service/emr v1.40.0/go.mod h1:5xmrleryUdXi+uFipHwKiDgUwIgZbGXn6hs7PZjnZTQ= github.com/aws/aws-sdk-go-v2/service/emrserverless v1.22.0 h1:vW/D2ptwtnwjALuTz6FU5yENgTmFTH+3Cgsl43rDbMA= diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index c5dd41c88195..537624adf714 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -84,6 +84,7 @@ import ( elasticache_sdkv2 "github.com/aws/aws-sdk-go-v2/service/elasticache" elasticbeanstalk_sdkv2 "github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk" elasticloadbalancingv2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2" + elasticsearchservice_sdkv2 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" emr_sdkv2 "github.com/aws/aws-sdk-go-v2/service/emr" emrserverless_sdkv2 "github.com/aws/aws-sdk-go-v2/service/emrserverless" eventbridge_sdkv2 "github.com/aws/aws-sdk-go-v2/service/eventbridge" @@ -202,7 +203,6 @@ import ( ecs_sdkv1 "github.com/aws/aws-sdk-go/service/ecs" efs_sdkv1 "github.com/aws/aws-sdk-go/service/efs" elasticache_sdkv1 "github.com/aws/aws-sdk-go/service/elasticache" - elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go/service/elasticsearchservice" elastictranscoder_sdkv1 "github.com/aws/aws-sdk-go/service/elastictranscoder" elb_sdkv1 "github.com/aws/aws-sdk-go/service/elb" elbv2_sdkv1 "github.com/aws/aws-sdk-go/service/elbv2" @@ -664,8 +664,8 @@ func (c *AWSClient) ElasticTranscoderConn(ctx context.Context) *elastictranscode return errs.Must(conn[*elastictranscoder_sdkv1.ElasticTranscoder](ctx, c, names.ElasticTranscoder, make(map[string]any))) } -func (c *AWSClient) ElasticsearchConn(ctx context.Context) *elasticsearchservice_sdkv1.ElasticsearchService { - return errs.Must(conn[*elasticsearchservice_sdkv1.ElasticsearchService](ctx, c, names.Elasticsearch, make(map[string]any))) +func (c *AWSClient) ElasticsearchClient(ctx context.Context) *elasticsearchservice_sdkv2.Client { + return errs.Must(client[*elasticsearchservice_sdkv2.Client](ctx, c, names.Elasticsearch, make(map[string]any))) } func (c *AWSClient) EventsClient(ctx context.Context) *eventbridge_sdkv2.Client { diff --git a/names/data/names_data.hcl b/names/data/names_data.hcl index d658e30bb0ec..fd6c4deb8e21 100644 --- a/names/data/names_data.hcl +++ b/names/data/names_data.hcl @@ -3437,7 +3437,7 @@ service "elasticsearch" { sdk { id = "Elasticsearch Service" - client_version = [1] + client_version = [2] } names { diff --git a/names/names.go b/names/names.go index 8d2aab5841f7..3d086983702b 100644 --- a/names/names.go +++ b/names/names.go @@ -66,6 +66,7 @@ const ( ECREndpointID = "api.ecr" EKSEndpointID = "eks" EMREndpointID = "elasticmapreduce" + ElasticsearchEndpointID = "es" EventsEndpointID = "events" EvidentlyEndpointID = "evidently" FMSEndpointID = "fms" From 4d4c94dc85da964a3937a8cce104440e83a67f39 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:20:10 +0100 Subject: [PATCH 02/24] gopatch --- internal/service/elasticsearch/domain.go | 54 ++++++++--------- .../elasticsearch/domain_data_source.go | 11 ++-- .../service/elasticsearch/domain_policy.go | 10 ++-- .../elasticsearch/domain_policy_test.go | 2 +- .../elasticsearch/domain_saml_options.go | 8 +-- .../elasticsearch/domain_saml_options_test.go | 2 +- .../service/elasticsearch/domain_structure.go | 38 ++++++------ internal/service/elasticsearch/domain_test.go | 22 +++---- internal/service/elasticsearch/find.go | 8 +-- internal/service/elasticsearch/flex.go | 50 ++++++++-------- .../service_endpoints_gen_test.go | 2 +- .../elasticsearch/service_package_gen.go | 2 +- internal/service/elasticsearch/status.go | 14 ++--- internal/service/elasticsearch/sweep.go | 14 +++-- internal/service/elasticsearch/tags_gen.go | 25 ++++---- .../service/elasticsearch/vpc_endpoint.go | 60 ++++++++++--------- .../elasticsearch/vpc_endpoint_test.go | 37 ++++++------ internal/service/elasticsearch/wait.go | 16 ++--- 18 files changed, 191 insertions(+), 184 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index d5d53cb042ca..5e369c8f9789 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -11,9 +11,9 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" awspolicy "github.com/hashicorp/awspolicyequivalence" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" @@ -55,7 +55,7 @@ func ResourceDomain() *schema.Resource { domainName := d.Get(names.AttrDomainName).(string) conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) - resp, err := conn.GetCompatibleElasticsearchVersionsWithContext(ctx, &elasticsearch.GetCompatibleElasticsearchVersionsInput{ + resp, err := conn.GetCompatibleElasticsearchVersions(ctx, &elasticsearch.GetCompatibleElasticsearchVersionsInput{ DomainName: aws.String(domainName), }) if err != nil { @@ -66,7 +66,7 @@ func ResourceDomain() *schema.Resource { return true } for _, targetVersion := range resp.CompatibleElasticsearchVersions[0].TargetVersions { - if aws.StringValue(targetVersion) == newVersion { + if aws.ToString(targetVersion) == newVersion { return false } } @@ -666,7 +666,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte outputRaw, err := tfresource.RetryWhen(ctx, propagationTimeout, func() (interface{}, error) { - return conn.CreateElasticsearchDomainWithContext(ctx, input) + return conn.CreateElasticsearchDomain(ctx, input) }, func(err error) (bool, error) { if tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeInvalidTypeException, "Error setting policy") || @@ -688,7 +688,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "creating Elasticsearch Domain (%s): %s", name, err) } - d.SetId(aws.StringValue(outputRaw.(*elasticsearch.CreateElasticsearchDomainOutput).DomainStatus.ARN)) + d.SetId(aws.ToString(outputRaw.(*elasticsearch.CreateElasticsearchDomainOutput).DomainStatus.ARN)) if err := WaitForDomainCreation(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) create: %s", d.Id(), err) @@ -701,7 +701,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte } log.Printf("[DEBUG] Updating Elasticsearch Domain config: %s", input) - _, err = conn.UpdateElasticsearchDomainConfigWithContext(ctx, input) + _, err = conn.UpdateElasticsearchDomainConfig(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Elasticsearch Domain (%s) config: %s", d.Id(), err) @@ -732,7 +732,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain (%s): %s", d.Id(), err) } - output, err := conn.DescribeElasticsearchDomainConfigWithContext(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ + output, err := conn.DescribeElasticsearchDomainConfig(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ DomainName: aws.String(name), }) @@ -742,7 +742,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf dc := output.DomainConfig - if v := aws.StringValue(ds.AccessPolicies); v != "" { + if v := aws.ToString(ds.AccessPolicies); v != "" { policies, err := verify.PolicyToSet(d.Get("access_policies").(string), v) if err != nil { @@ -787,7 +787,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf // from resource as they are not returned from the API if ds.AdvancedSecurityOptions != nil { advSecOpts := flattenAdvancedSecurityOptions(ds.AdvancedSecurityOptions) - if !aws.BoolValue(ds.AdvancedSecurityOptions.Enabled) { + if !aws.ToBool(ds.AdvancedSecurityOptions.Enabled) { advSecOpts[0]["internal_user_database_enabled"] = getUserDBEnabled(d) } advSecOpts[0]["master_user_options"] = getMasterUserOptions(d) @@ -952,7 +952,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte } log.Printf("[DEBUG] Updating Elasticsearch Domain config: %s", input) - _, err := conn.UpdateElasticsearchDomainConfigWithContext(ctx, input) + _, err := conn.UpdateElasticsearchDomainConfig(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Elasticsearch Domain (%s) config: %s", d.Id(), err) @@ -969,7 +969,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte } log.Printf("[DEBUG] Upgrading Elasticsearch Domain: %s", input) - _, err := conn.UpgradeElasticsearchDomainWithContext(ctx, input) + _, err := conn.UpgradeElasticsearchDomain(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "upgrading Elasticsearch Domain (%s): %s", d.Id(), err) @@ -991,7 +991,7 @@ func resourceDomainDelete(ctx context.Context, d *schema.ResourceData, meta inte name := d.Get(names.AttrDomainName).(string) log.Printf("[DEBUG] Deleting Elasticsearch Domain: %s", d.Id()) - _, err := conn.DeleteElasticsearchDomainWithContext(ctx, &elasticsearch.DeleteElasticsearchDomainInput{ + _, err := conn.DeleteElasticsearchDomain(ctx, &elasticsearch.DeleteElasticsearchDomainInput{ DomainName: aws.String(name), }) @@ -1021,7 +1021,7 @@ func resourceDomainImport(ctx context.Context, d *schema.ResourceData, meta inte return nil, err } - d.SetId(aws.StringValue(ds.ARN)) + d.SetId(aws.ToString(ds.ARN)) return []*schema.ResourceData{d}, nil } @@ -1077,7 +1077,7 @@ func flattenNodeToNodeEncryptionOptions(o *elasticsearch.NodeToNodeEncryptionOpt m := map[string]interface{}{} if o.Enabled != nil { - m[names.AttrEnabled] = aws.BoolValue(o.Enabled) + m[names.AttrEnabled] = aws.ToBool(o.Enabled) } return []map[string]interface{}{m} @@ -1173,35 +1173,35 @@ func expandZoneAwarenessConfig(l []interface{}) *elasticsearch.ZoneAwarenessConf func flattenClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[string]interface{} { m := map[string]interface{}{ "zone_awareness_config": flattenZoneAwarenessConfig(c.ZoneAwarenessConfig), - "zone_awareness_enabled": aws.BoolValue(c.ZoneAwarenessEnabled), + "zone_awareness_enabled": aws.ToBool(c.ZoneAwarenessEnabled), } if c.ColdStorageOptions != nil { m["cold_storage_options"] = flattenColdStorageOptions(c.ColdStorageOptions) } if c.DedicatedMasterCount != nil { - m["dedicated_master_count"] = aws.Int64Value(c.DedicatedMasterCount) + m["dedicated_master_count"] = aws.ToInt64(c.DedicatedMasterCount) } if c.DedicatedMasterEnabled != nil { - m["dedicated_master_enabled"] = aws.BoolValue(c.DedicatedMasterEnabled) + m["dedicated_master_enabled"] = aws.ToBool(c.DedicatedMasterEnabled) } if c.DedicatedMasterType != nil { - m["dedicated_master_type"] = aws.StringValue(c.DedicatedMasterType) + m["dedicated_master_type"] = aws.ToString(c.DedicatedMasterType) } if c.InstanceCount != nil { - m[names.AttrInstanceCount] = aws.Int64Value(c.InstanceCount) + m[names.AttrInstanceCount] = aws.ToInt64(c.InstanceCount) } if c.InstanceType != nil { - m[names.AttrInstanceType] = aws.StringValue(c.InstanceType) + m[names.AttrInstanceType] = aws.ToString(c.InstanceType) } if c.WarmEnabled != nil { - m["warm_enabled"] = aws.BoolValue(c.WarmEnabled) + m["warm_enabled"] = aws.ToBool(c.WarmEnabled) } if c.WarmCount != nil { - m["warm_count"] = aws.Int64Value(c.WarmCount) + m["warm_count"] = aws.ToInt64(c.WarmCount) } if c.WarmType != nil { - m["warm_type"] = aws.StringValue(c.WarmType) + m["warm_type"] = aws.ToString(c.WarmType) } return []map[string]interface{}{m} @@ -1213,7 +1213,7 @@ func flattenColdStorageOptions(coldStorageOptions *elasticsearch.ColdStorageOpti } m := map[string]interface{}{ - names.AttrEnabled: aws.BoolValue(coldStorageOptions.Enabled), + names.AttrEnabled: aws.ToBool(coldStorageOptions.Enabled), } return []interface{}{m} @@ -1225,7 +1225,7 @@ func flattenZoneAwarenessConfig(zoneAwarenessConfig *elasticsearch.ZoneAwareness } m := map[string]interface{}{ - "availability_zone_count": aws.Int64Value(zoneAwarenessConfig.AvailabilityZoneCount), + "availability_zone_count": aws.ToInt64(zoneAwarenessConfig.AvailabilityZoneCount), } return []interface{}{m} diff --git a/internal/service/elasticsearch/domain_data_source.go b/internal/service/elasticsearch/domain_data_source.go index ee93c8bbf89c..ed2d6bfa3ce4 100644 --- a/internal/service/elasticsearch/domain_data_source.go +++ b/internal/service/elasticsearch/domain_data_source.go @@ -6,8 +6,9 @@ package elasticsearch import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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/structure" @@ -359,7 +360,7 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte DomainName: aws.String(d.Get(names.AttrDomainName).(string)), } - respDescribeDomainConfig, err := conn.DescribeElasticsearchDomainConfigWithContext(ctx, reqDescribeDomainConfig) + respDescribeDomainConfig, err := conn.DescribeElasticsearchDomainConfig(ctx, reqDescribeDomainConfig) if err != nil { return sdkdiag.AppendErrorf(diags, "querying config for elasticsearch_domain: %s", err) } @@ -370,9 +371,9 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte dc := respDescribeDomainConfig.DomainConfig - d.SetId(aws.StringValue(ds.ARN)) + d.SetId(aws.ToString(ds.ARN)) - if ds.AccessPolicies != nil && aws.StringValue(ds.AccessPolicies) != "" { + if ds.AccessPolicies != nil && aws.ToString(ds.AccessPolicies) != "" { policies, err := structure.NormalizeJsonString(*ds.AccessPolicies) if err != nil { return sdkdiag.AppendErrorf(diags, "access policies contain an invalid JSON: %s", err) diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index 7501342434f1..baa4a5d2d67b 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -8,8 +8,8 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" @@ -70,7 +70,7 @@ func resourceDomainPolicyRead(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain Policy (%s): %s", d.Id(), err) } - policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.StringValue(ds.AccessPolicies)) + policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.ToString(ds.AccessPolicies)) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain Policy (%s): %s", d.Id(), err) @@ -94,7 +94,7 @@ func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, met _, err = tfresource.RetryWhenAWSErrMessageContains(ctx, propagationTimeout, func() (interface{}, error) { - return conn.UpdateElasticsearchDomainConfigWithContext(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ + return conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(domainName), AccessPolicies: aws.String(policy), }) @@ -119,7 +119,7 @@ func resourceDomainPolicyDelete(ctx context.Context, d *schema.ResourceData, met var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) - _, err := conn.UpdateElasticsearchDomainConfigWithContext(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ + _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(d.Get(names.AttrDomainName).(string)), AccessPolicies: aws.String(""), }) diff --git a/internal/service/elasticsearch/domain_policy_test.go b/internal/service/elasticsearch/domain_policy_test.go index f689a309def1..e17d54e80d24 100644 --- a/internal/service/elasticsearch/domain_policy_test.go +++ b/internal/service/elasticsearch/domain_policy_test.go @@ -7,7 +7,7 @@ import ( "fmt" "testing" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 782d78eefb65..9b676fe5f9a7 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -8,8 +8,8 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "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" @@ -154,7 +154,7 @@ func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, m log.Printf("[DEBUG] Updating Elasticsearch domain SAML Options %s", config) - _, err := conn.UpdateElasticsearchDomainConfigWithContext(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ + _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(domainName), AdvancedSecurityOptions: &config, }) @@ -180,7 +180,7 @@ func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData config := elasticsearch.AdvancedSecurityOptionsInput{} config.SetSAMLOptions(nil) - _, err := conn.UpdateElasticsearchDomainConfigWithContext(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ + _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(domainName), AdvancedSecurityOptions: &config, }) diff --git a/internal/service/elasticsearch/domain_saml_options_test.go b/internal/service/elasticsearch/domain_saml_options_test.go index 2be3459728d6..c73b5b731231 100644 --- a/internal/service/elasticsearch/domain_saml_options_test.go +++ b/internal/service/elasticsearch/domain_saml_options_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" diff --git a/internal/service/elasticsearch/domain_structure.go b/internal/service/elasticsearch/domain_structure.go index 87628b375216..686eed49a9e3 100644 --- a/internal/service/elasticsearch/domain_structure.go +++ b/internal/service/elasticsearch/domain_structure.go @@ -6,8 +6,8 @@ package elasticsearch import ( "time" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -63,7 +63,7 @@ func expandAutoTuneOptions(tfMap map[string]interface{}) *elasticsearch.AutoTune options.MaintenanceSchedules = autoTuneOptionsInput.MaintenanceSchedules if v, ok := tfMap["rollback_on_disable"].(string); ok && v != "" { - options.RollbackOnDisable = aws.String(v) + options.RollbackOnDisable = awstypes.RollbackOnDisable(v) } return options @@ -178,9 +178,9 @@ func flattenAdvancedSecurityOptions(advancedSecurityOptions *elasticsearch.Advan } m := map[string]interface{}{} - m[names.AttrEnabled] = aws.BoolValue(advancedSecurityOptions.Enabled) - if aws.BoolValue(advancedSecurityOptions.Enabled) { - m["internal_user_database_enabled"] = aws.BoolValue(advancedSecurityOptions.InternalUserDatabaseEnabled) + m[names.AttrEnabled] = aws.ToBool(advancedSecurityOptions.Enabled) + if aws.ToBool(advancedSecurityOptions.Enabled) { + m["internal_user_database_enabled"] = aws.ToBool(advancedSecurityOptions.InternalUserDatabaseEnabled) } return []map[string]interface{}{m} @@ -193,13 +193,13 @@ func flattenAutoTuneOptions(autoTuneOptions *elasticsearch.AutoTuneOptions) map[ m := map[string]interface{}{} - m["desired_state"] = aws.StringValue(autoTuneOptions.DesiredState) + m["desired_state"] = aws.ToString(autoTuneOptions.DesiredState) if v := autoTuneOptions.MaintenanceSchedules; v != nil { m["maintenance_schedule"] = flattenAutoTuneMaintenanceSchedules(v) } - m["rollback_on_disable"] = aws.StringValue(autoTuneOptions.RollbackOnDisable) + m["rollback_on_disable"] = string(autoTuneOptions.RollbackOnDisable) return m } @@ -218,7 +218,7 @@ func flattenAutoTuneMaintenanceSchedules(autoTuneMaintenanceSchedules []*elastic m[names.AttrDuration] = []interface{}{flattenAutoTuneMaintenanceScheduleDuration(autoTuneMaintenanceSchedule.Duration)} - m["cron_expression_for_recurrence"] = aws.StringValue(autoTuneMaintenanceSchedule.CronExpressionForRecurrence) + m["cron_expression_for_recurrence"] = aws.ToString(autoTuneMaintenanceSchedule.CronExpressionForRecurrence) tfList = append(tfList, m) } @@ -229,8 +229,8 @@ func flattenAutoTuneMaintenanceSchedules(autoTuneMaintenanceSchedules []*elastic func flattenAutoTuneMaintenanceScheduleDuration(autoTuneMaintenanceScheduleDuration *elasticsearch.Duration) map[string]interface{} { m := map[string]interface{}{} - m[names.AttrValue] = aws.Int64Value(autoTuneMaintenanceScheduleDuration.Value) - m[names.AttrUnit] = aws.StringValue(autoTuneMaintenanceScheduleDuration.Unit) + m[names.AttrValue] = aws.ToInt64(autoTuneMaintenanceScheduleDuration.Value) + m[names.AttrUnit] = aws.ToString(autoTuneMaintenanceScheduleDuration.Unit) return m } @@ -241,13 +241,13 @@ func flattenESSAMLOptions(d *schema.ResourceData, samlOptions *elasticsearch.SAM } m := map[string]interface{}{ - names.AttrEnabled: aws.BoolValue(samlOptions.Enabled), + names.AttrEnabled: aws.ToBool(samlOptions.Enabled), "idp": flattenESSAMLIdpOptions(samlOptions.Idp), } - m["roles_key"] = aws.StringValue(samlOptions.RolesKey) - m["session_timeout_minutes"] = aws.Int64Value(samlOptions.SessionTimeoutMinutes) - m["subject_key"] = aws.StringValue(samlOptions.SubjectKey) + m["roles_key"] = aws.ToString(samlOptions.RolesKey) + m["session_timeout_minutes"] = aws.ToInt64(samlOptions.SessionTimeoutMinutes) + m["subject_key"] = aws.ToString(samlOptions.SubjectKey) // samlOptions.master_backend_role and samlOptions.master_user_name will be added to the // all_access role in kibana's security manager. These values cannot be read or @@ -265,8 +265,8 @@ func flattenESSAMLIdpOptions(SAMLIdp *elasticsearch.SAMLIdp) []interface{} { } m := map[string]interface{}{ - "entity_id": aws.StringValue(SAMLIdp.EntityId), - "metadata_content": aws.StringValue(SAMLIdp.MetadataContent), + "entity_id": aws.ToString(SAMLIdp.EntityId), + "metadata_content": aws.ToString(SAMLIdp.MetadataContent), } return []interface{}{m} @@ -317,11 +317,11 @@ func flattenLogPublishingOptions(o map[string]*elasticsearch.LogPublishingOption for logType, val := range o { mm := map[string]interface{}{ "log_type": logType, - names.AttrEnabled: aws.BoolValue(val.Enabled), + names.AttrEnabled: aws.ToBool(val.Enabled), } if val.CloudWatchLogsLogGroupArn != nil { - mm[names.AttrCloudWatchLogGroupARN] = aws.StringValue(val.CloudWatchLogsLogGroupArn) + mm[names.AttrCloudWatchLogGroupARN] = aws.ToString(val.CloudWatchLogsLogGroupArn) } m = append(m, mm) diff --git a/internal/service/elasticsearch/domain_test.go b/internal/service/elasticsearch/domain_test.go index 4adeb449bc5b..914f6048f52d 100644 --- a/internal/service/elasticsearch/domain_test.go +++ b/internal/service/elasticsearch/domain_test.go @@ -10,9 +10,9 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -414,7 +414,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) - _, err := conn.DeleteElasticsearchDomainWithContext(ctx, &elasticsearch.DeleteElasticsearchDomainInput{ + _, err := conn.DeleteElasticsearchDomain(ctx, &elasticsearch.DeleteElasticsearchDomainInput{ DomainName: aws.String(rName), }) return err @@ -424,7 +424,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { PreConfig: func() { // Create duplicate conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) - _, err := conn.CreateElasticsearchDomainWithContext(ctx, &elasticsearch.CreateElasticsearchDomainInput{ + _, err := conn.CreateElasticsearchDomain(ctx, &elasticsearch.CreateElasticsearchDomainInput{ DomainName: aws.String(rName), EBSOptions: &elasticsearch.EBSOptions{ EBSEnabled: aws.Bool(true), @@ -1765,8 +1765,8 @@ func testAccCheckDomainEncrypted(encrypted bool, status *elasticsearch.Elasticse func testAccCheckNodeToNodeEncrypted(encrypted bool, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { options := status.NodeToNodeEncryptionOptions - if aws.BoolValue(options.Enabled) != encrypted { - return fmt.Errorf("Node-to-Node Encryption not set properly. Given: %t, Expected: %t", aws.BoolValue(options.Enabled), encrypted) + if aws.ToBool(options.Enabled) != encrypted { + return fmt.Errorf("Node-to-Node Encryption not set properly. Given: %t, Expected: %t", aws.ToBool(options.Enabled), encrypted) } return nil } @@ -1776,19 +1776,19 @@ func testAccCheckAdvancedSecurityOptions(enabled bool, userDbEnabled bool, statu return func(s *terraform.State) error { conf := status.AdvancedSecurityOptions - if aws.BoolValue(conf.Enabled) != enabled { + if aws.ToBool(conf.Enabled) != enabled { return fmt.Errorf( "AdvancedSecurityOptions.Enabled not set properly. Given: %t, Expected: %t", - aws.BoolValue(conf.Enabled), + aws.ToBool(conf.Enabled), enabled, ) } - if aws.BoolValue(conf.Enabled) { - if aws.BoolValue(conf.InternalUserDatabaseEnabled) != userDbEnabled { + if aws.ToBool(conf.Enabled) { + if aws.ToBool(conf.InternalUserDatabaseEnabled) != userDbEnabled { return fmt.Errorf( "AdvancedSecurityOptions.InternalUserDatabaseEnabled not set properly. Given: %t, Expected: %t", - aws.BoolValue(conf.InternalUserDatabaseEnabled), + aws.ToBool(conf.InternalUserDatabaseEnabled), userDbEnabled, ) } diff --git a/internal/service/elasticsearch/find.go b/internal/service/elasticsearch/find.go index 41bf9b858de4..1135c0fa22e9 100644 --- a/internal/service/elasticsearch/find.go +++ b/internal/service/elasticsearch/find.go @@ -6,9 +6,9 @@ package elasticsearch import ( "context" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + "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/tfresource" ) @@ -18,7 +18,7 @@ func FindDomainByName(ctx context.Context, conn *elasticsearch.ElasticsearchServ DomainName: aws.String(name), } - output, err := conn.DescribeElasticsearchDomainWithContext(ctx, input) + output, err := conn.DescribeElasticsearchDomain(ctx, input) if tfawserr.ErrCodeEquals(err, elasticsearch.ErrCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ diff --git a/internal/service/elasticsearch/flex.go b/internal/service/elasticsearch/flex.go index bbe2908b7156..483f6523c628 100644 --- a/internal/service/elasticsearch/flex.go +++ b/internal/service/elasticsearch/flex.go @@ -4,8 +4,8 @@ package elasticsearch import ( - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/flex" "github.com/hashicorp/terraform-provider-aws/names" @@ -53,7 +53,7 @@ func expandDomainEndpointOptions(l []interface{}) *elasticsearch.DomainEndpointO } if v, ok := m["tls_security_policy"].(string); ok { - domainEndpointOptions.TLSSecurityPolicy = aws.String(v) + domainEndpointOptions.TLSSecurityPolicy = awstypes.TLSSecurityPolicy(v) } if customEndpointEnabled, ok := m["custom_endpoint_enabled"]; ok { @@ -86,7 +86,7 @@ func expandEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions { var volumeType string if v, ok := m[names.AttrVolumeType]; ok && v.(string) != "" { volumeType = v.(string) - options.VolumeType = aws.String(volumeType) + options.VolumeType = awstypes.VolumeType(volumeType) } if v, ok := m[names.AttrIOPS]; ok && v.(int) > 0 && EBSVolumeTypePermitsIopsInput(volumeType) { options.Iops = aws.Int64(int64(v.(int))) @@ -133,12 +133,12 @@ func expandVPCOptions(m map[string]interface{}) *elasticsearch.VPCOptions { func flattenCognitoOptions(c *elasticsearch.CognitoOptions) []map[string]interface{} { m := map[string]interface{}{} - m[names.AttrEnabled] = aws.BoolValue(c.Enabled) + m[names.AttrEnabled] = aws.ToBool(c.Enabled) - if aws.BoolValue(c.Enabled) { - m["identity_pool_id"] = aws.StringValue(c.IdentityPoolId) - m[names.AttrUserPoolID] = aws.StringValue(c.UserPoolId) - m[names.AttrRoleARN] = aws.StringValue(c.RoleArn) + if aws.ToBool(c.Enabled) { + m["identity_pool_id"] = aws.ToString(c.IdentityPoolId) + m[names.AttrUserPoolID] = aws.ToString(c.UserPoolId) + m[names.AttrRoleARN] = aws.ToString(c.RoleArn) } return []map[string]interface{}{m} @@ -150,16 +150,16 @@ func flattenDomainEndpointOptions(domainEndpointOptions *elasticsearch.DomainEnd } m := map[string]interface{}{ - "enforce_https": aws.BoolValue(domainEndpointOptions.EnforceHTTPS), - "tls_security_policy": aws.StringValue(domainEndpointOptions.TLSSecurityPolicy), - "custom_endpoint_enabled": aws.BoolValue(domainEndpointOptions.CustomEndpointEnabled), + "enforce_https": aws.ToBool(domainEndpointOptions.EnforceHTTPS), + "tls_security_policy": string(domainEndpointOptions.TLSSecurityPolicy), + "custom_endpoint_enabled": aws.ToBool(domainEndpointOptions.CustomEndpointEnabled), } - if aws.BoolValue(domainEndpointOptions.CustomEndpointEnabled) { + if aws.ToBool(domainEndpointOptions.CustomEndpointEnabled) { if domainEndpointOptions.CustomEndpoint != nil { - m["custom_endpoint"] = aws.StringValue(domainEndpointOptions.CustomEndpoint) + m["custom_endpoint"] = aws.ToString(domainEndpointOptions.CustomEndpoint) } if domainEndpointOptions.CustomEndpointCertificateArn != nil { - m["custom_endpoint_certificate_arn"] = aws.StringValue(domainEndpointOptions.CustomEndpointCertificateArn) + m["custom_endpoint_certificate_arn"] = aws.ToString(domainEndpointOptions.CustomEndpointCertificateArn) } } @@ -170,21 +170,21 @@ func flattenEBSOptions(o *elasticsearch.EBSOptions) []map[string]interface{} { m := map[string]interface{}{} if o.EBSEnabled != nil { - m["ebs_enabled"] = aws.BoolValue(o.EBSEnabled) + m["ebs_enabled"] = aws.ToBool(o.EBSEnabled) } - if aws.BoolValue(o.EBSEnabled) { + if aws.ToBool(o.EBSEnabled) { if o.Iops != nil { - m[names.AttrIOPS] = aws.Int64Value(o.Iops) + m[names.AttrIOPS] = aws.ToInt64(o.Iops) } if o.Throughput != nil { - m[names.AttrThroughput] = aws.Int64Value(o.Throughput) + m[names.AttrThroughput] = aws.ToInt64(o.Throughput) } if o.VolumeSize != nil { - m[names.AttrVolumeSize] = aws.Int64Value(o.VolumeSize) + m[names.AttrVolumeSize] = aws.ToInt64(o.VolumeSize) } if o.VolumeType != nil { - m[names.AttrVolumeType] = aws.StringValue(o.VolumeType) + m[names.AttrVolumeType] = string(o.VolumeType) } } @@ -199,10 +199,10 @@ func flattenEncryptAtRestOptions(o *elasticsearch.EncryptionAtRestOptions) []map m := map[string]interface{}{} if o.Enabled != nil { - m[names.AttrEnabled] = aws.BoolValue(o.Enabled) + m[names.AttrEnabled] = aws.ToBool(o.Enabled) } if o.KmsKeyId != nil { - m[names.AttrKMSKeyID] = aws.StringValue(o.KmsKeyId) + m[names.AttrKMSKeyID] = aws.ToString(o.KmsKeyId) } return []map[string]interface{}{m} @@ -214,7 +214,7 @@ func flattenSnapshotOptions(snapshotOptions *elasticsearch.SnapshotOptions) []ma } m := map[string]interface{}{ - "automated_snapshot_start_hour": int(aws.Int64Value(snapshotOptions.AutomatedSnapshotStartHour)), + "automated_snapshot_start_hour": int(aws.ToInt64(snapshotOptions.AutomatedSnapshotStartHour)), } return []map[string]interface{}{m} @@ -237,7 +237,7 @@ func flattenVPCDerivedInfo(o *elasticsearch.VPCDerivedInfo) map[string]interface m[names.AttrSubnetIDs] = flex.FlattenStringSet(o.SubnetIds) } if o.VPCId != nil { - m[names.AttrVPCID] = aws.StringValue(o.VPCId) + m[names.AttrVPCID] = aws.ToString(o.VPCId) } return m diff --git a/internal/service/elasticsearch/service_endpoints_gen_test.go b/internal/service/elasticsearch/service_endpoints_gen_test.go index a732ab343f3e..f8c5d851c4a4 100644 --- a/internal/service/elasticsearch/service_endpoints_gen_test.go +++ b/internal/service/elasticsearch/service_endpoints_gen_test.go @@ -12,9 +12,9 @@ import ( "strings" "testing" + elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" aws_sdkv1 "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" - elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go/service/elasticsearchservice" "github.com/google/go-cmp/cmp" "github.com/hashicorp/aws-sdk-go-base/v2/servicemocks" "github.com/hashicorp/go-cty/cty" diff --git a/internal/service/elasticsearch/service_package_gen.go b/internal/service/elasticsearch/service_package_gen.go index 1e483ca6d664..08befd6db2c2 100644 --- a/internal/service/elasticsearch/service_package_gen.go +++ b/internal/service/elasticsearch/service_package_gen.go @@ -5,10 +5,10 @@ package elasticsearch import ( "context" + elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" aws_sdkv1 "github.com/aws/aws-sdk-go/aws" endpoints_sdkv1 "github.com/aws/aws-sdk-go/aws/endpoints" session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" diff --git a/internal/service/elasticsearch/status.go b/internal/service/elasticsearch/status.go index 5ce295a7c77e..3dcc0f791ae6 100644 --- a/internal/service/elasticsearch/status.go +++ b/internal/service/elasticsearch/status.go @@ -6,9 +6,9 @@ package elasticsearch import ( "context" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" ) @@ -21,7 +21,7 @@ const ( func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.ElasticsearchService, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - out, err := conn.GetUpgradeStatusWithContext(ctx, &elasticsearch.GetUpgradeStatusInput{ + out, err := conn.GetUpgradeStatus(ctx, &elasticsearch.GetUpgradeStatusInput{ DomainName: aws.String(name), }) if err != nil { @@ -31,17 +31,17 @@ func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.ElasticsearchS // Elasticsearch upgrades consist of multiple steps: // https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-version-migration.html // Prevent false positive completion where the UpgradeStep is not the final UPGRADE step. - if aws.StringValue(out.StepStatus) == elasticsearch.UpgradeStatusSucceeded && aws.StringValue(out.UpgradeStep) != elasticsearch.UpgradeStepUpgrade { + if aws.ToString(out.StepStatus) == elasticsearch.UpgradeStatusSucceeded && string(out.UpgradeStep) != elasticsearch.UpgradeStepUpgrade { return out, elasticsearch.UpgradeStatusInProgress, nil } - return out, aws.StringValue(out.StepStatus), nil + return out, aws.ToString(out.StepStatus), nil } } func domainConfigStatus(ctx context.Context, conn *elasticsearch.ElasticsearchService, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - out, err := conn.DescribeElasticsearchDomainConfigWithContext(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ + out, err := conn.DescribeElasticsearchDomainConfig(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ DomainName: aws.String(name), }) diff --git a/internal/service/elasticsearch/sweep.go b/internal/service/elasticsearch/sweep.go index 92720130ced8..9338564dbe3a 100644 --- a/internal/service/elasticsearch/sweep.go +++ b/internal/service/elasticsearch/sweep.go @@ -7,10 +7,12 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/sweep" "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv1" "github.com/hashicorp/terraform-provider-aws/names" @@ -38,7 +40,7 @@ func sweepDomains(region string) error { input := &elasticsearchservice.ListDomainNamesInput{} // ListDomainNames has no pagination support whatsoever - output, err := conn.ListDomainNamesWithContext(ctx, input) + output, err := conn.ListDomainNames(ctx, input) if awsv1.SkipSweepError(err) { log.Printf("[WARN] Skipping Elasticsearch Domain sweep for %s: %s", region, err) @@ -62,9 +64,9 @@ func sweepDomains(region string) error { continue } - name := aws.StringValue(domainInfo.DomainName) + name := aws.ToString(domainInfo.DomainName) - if engineType := aws.StringValue(domainInfo.EngineType); engineType != elasticsearchservice.EngineTypeElasticsearch { + if engineType := string(domainInfo.EngineType); engineType != awstypes.EngineTypeElasticsearch { log.Printf("[INFO] Skipping Elasticsearch Domain %s: EngineType = %s", name, engineType) continue } @@ -81,7 +83,7 @@ func sweepDomains(region string) error { continue } - if output != nil && aws.BoolValue(output.Deleted) { + if output != nil && aws.ToBool(output.Deleted) { log.Printf("[INFO] Skipping Elasticsearch Domain (%s) with deleted status", name) continue } diff --git a/internal/service/elasticsearch/tags_gen.go b/internal/service/elasticsearch/tags_gen.go index a4c0359a9675..c7517f522888 100644 --- a/internal/service/elasticsearch/tags_gen.go +++ b/internal/service/elasticsearch/tags_gen.go @@ -5,8 +5,9 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/aws/aws-sdk-go/service/elasticsearchservice/elasticsearchserviceiface" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -24,7 +25,7 @@ func listTags(ctx context.Context, conn elasticsearchserviceiface.ElasticsearchS ARN: aws.String(identifier), } - output, err := conn.ListTagsWithContext(ctx, input) + output, err := conn.ListTags(ctx, input) if err != nil { return tftags.New(ctx, nil), err @@ -52,11 +53,11 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri // []*SERVICE.Tag handling // Tags returns elasticsearch service tags. -func Tags(tags tftags.KeyValueTags) []*elasticsearchservice.Tag { - result := make([]*elasticsearchservice.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 := &elasticsearchservice.Tag{ + tag := &awstypes.Tag{ Key: aws.String(k), Value: aws.String(v), } @@ -68,11 +69,11 @@ func Tags(tags tftags.KeyValueTags) []*elasticsearchservice.Tag { } // KeyValueTags creates tftags.KeyValueTags from elasticsearchservice service tags. -func KeyValueTags(ctx context.Context, tags []*elasticsearchservice.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 +81,7 @@ func KeyValueTags(ctx context.Context, tags []*elasticsearchservice.Tag) tftags. // getTagsIn returns elasticsearch service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) []*elasticsearchservice.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 +92,7 @@ func getTagsIn(ctx context.Context) []*elasticsearchservice.Tag { } // setTagsOut sets elasticsearch service tags in Context. -func setTagsOut(ctx context.Context, tags []*elasticsearchservice.Tag) { +func setTagsOut(ctx context.Context, tags []*awstypes.Tag) { if inContext, ok := tftags.FromContext(ctx); ok { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } @@ -114,7 +115,7 @@ func updateTags(ctx context.Context, conn elasticsearchserviceiface.Elasticsearc TagKeys: aws.StringSlice(removedTags.Keys()), } - _, err := conn.RemoveTagsWithContext(ctx, input) + _, err := conn.RemoveTags(ctx, input) if err != nil { return fmt.Errorf("untagging resource (%s): %w", identifier, err) @@ -129,7 +130,7 @@ func updateTags(ctx context.Context, conn elasticsearchserviceiface.Elasticsearc TagList: Tags(updatedTags), } - _, err := conn.AddTagsWithContext(ctx, input) + _, err := conn.AddTags(ctx, input) if err != nil { return fmt.Errorf("tagging resource (%s): %w", identifier, err) diff --git a/internal/service/elasticsearch/vpc_endpoint.go b/internal/service/elasticsearch/vpc_endpoint.go index 528456d7a4f3..201965a747a2 100644 --- a/internal/service/elasticsearch/vpc_endpoint.go +++ b/internal/service/elasticsearch/vpc_endpoint.go @@ -10,13 +10,15 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "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/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -94,13 +96,13 @@ func resourceVPCEndpointCreate(ctx context.Context, d *schema.ResourceData, meta VpcOptions: expandVPCOptions(d.Get("vpc_options").([]interface{})[0].(map[string]interface{})), } - output, err := conn.CreateVpcEndpointWithContext(ctx, input) + output, err := conn.CreateVpcEndpoint(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Elasticsearch VPC Endpoint: %s", err) } - d.SetId(aws.StringValue(output.VpcEndpoint.VpcEndpointId)) + d.SetId(aws.ToString(output.VpcEndpoint.VpcEndpointId)) if err := waitVPCEndpointCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch VPC Endpoint (%s) create: %s", d.Id(), err) @@ -147,7 +149,7 @@ func resourceVPCEndpointUpdate(ctx context.Context, d *schema.ResourceData, meta VpcEndpointId: aws.String(d.Id()), } - _, err := conn.UpdateVpcEndpointWithContext(ctx, input) + _, err := conn.UpdateVpcEndpoint(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Elasticsearch VPC Endpoint (%s): %s", d.Id(), err) @@ -165,11 +167,11 @@ func resourceVPCEndpointDelete(ctx context.Context, d *schema.ResourceData, meta conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) log.Printf("[DEBUG] Deleting Elasticsearch VPC Endpoint: %s", d.Id()) - _, err := conn.DeleteVpcEndpointWithContext(ctx, &elasticsearchservice.DeleteVpcEndpointInput{ + _, err := conn.DeleteVpcEndpoint(ctx, &elasticsearchservice.DeleteVpcEndpointInput{ VpcEndpointId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, elasticsearchservice.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -214,23 +216,23 @@ func (e *vpcEndpointNotFoundError) As(target any) bool { return true } -func vpcEndpointError(apiObject *elasticsearchservice.VpcEndpointError) error { +func vpcEndpointError(apiObject *awstypes.VpcEndpointError) error { if apiObject == nil { return nil } - errorCode := aws.StringValue(apiObject.ErrorCode) - innerError := fmt.Errorf("%s: %s", errorCode, aws.StringValue(apiObject.ErrorMessage)) - err := fmt.Errorf("%s: %w", aws.StringValue(apiObject.VpcEndpointId), innerError) + errorCode := aws.ToString(apiObject.ErrorCode) + innerError := fmt.Errorf("%s: %s", errorCode, aws.ToString(apiObject.ErrorMessage)) + err := fmt.Errorf("%s: %w", aws.ToString(apiObject.VpcEndpointId), innerError) - if errorCode == elasticsearchservice.VpcEndpointErrorCodeEndpointNotFound { + if errorCode == awstypes.VpcEndpointErrorCodeEndpointNotFound { err = &vpcEndpointNotFoundError{apiError: err} } return err } -func vpcEndpointsError(apiObjects []*elasticsearchservice.VpcEndpointError) error { +func vpcEndpointsError(apiObjects []*awstypes.VpcEndpointError) error { var errs []error for _, apiObject := range apiObjects { @@ -240,15 +242,15 @@ func vpcEndpointsError(apiObjects []*elasticsearchservice.VpcEndpointError) erro return errors.Join(errs...) } -func findVPCEndpointByID(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, id string) (*elasticsearchservice.VpcEndpoint, error) { +func findVPCEndpointByID(ctx context.Context, conn *elasticsearchservice.Client, id string) (*awstypes.VpcEndpoint, error) { input := &elasticsearchservice.DescribeVpcEndpointsInput{ - VpcEndpointIds: aws.StringSlice([]string{id}), + VpcEndpointIds: []string{id}, } return findVPCEndpoint(ctx, conn, input) } -func findVPCEndpoint(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, input *elasticsearchservice.DescribeVpcEndpointsInput) (*elasticsearchservice.VpcEndpoint, error) { +func findVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Client, input *elasticsearchservice.DescribeVpcEndpointsInput) (*awstypes.VpcEndpoint, error) { output, err := findVPCEndpoints(ctx, conn, input) if err != nil { @@ -258,8 +260,8 @@ func findVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Elasticsear return tfresource.AssertSinglePtrResult(output) } -func findVPCEndpoints(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, input *elasticsearchservice.DescribeVpcEndpointsInput) ([]*elasticsearchservice.VpcEndpoint, error) { - output, err := conn.DescribeVpcEndpointsWithContext(ctx, input) +func findVPCEndpoints(ctx context.Context, conn *elasticsearchservice.Client, input *elasticsearchservice.DescribeVpcEndpointsInput) ([]*awstypes.VpcEndpoint, error) { + output, err := conn.DescribeVpcEndpoints(ctx, input) if err != nil { return nil, err @@ -276,7 +278,7 @@ func findVPCEndpoints(ctx context.Context, conn *elasticsearchservice.Elasticsea return output.VpcEndpoints, nil } -func statusVPCEndpoint(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, id string) retry.StateRefreshFunc { +func statusVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { output, err := findVPCEndpointByID(ctx, conn, id) @@ -288,14 +290,14 @@ func statusVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Elasticse return nil, "", err } - return output, aws.StringValue(output.Status), nil + return output, aws.ToString(output.Status), nil } } -func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, id string, timeout time.Duration) error { +func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{elasticsearchservice.VpcEndpointStatusCreating}, - Target: []string{elasticsearchservice.VpcEndpointStatusActive}, + Pending: []string{awstypes.VpcEndpointStatusCreating}, + Target: []string{awstypes.VpcEndpointStatusActive}, Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } @@ -305,10 +307,10 @@ func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.Elas return err } -func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, id string, timeout time.Duration) error { +func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{elasticsearchservice.VpcEndpointStatusUpdating}, - Target: []string{elasticsearchservice.VpcEndpointStatusActive}, + Pending: []string{awstypes.VpcEndpointStatusUpdating}, + Target: []string{awstypes.VpcEndpointStatusActive}, Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } @@ -318,9 +320,9 @@ func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.Elas return err } -func waitVPCEndpointDeleted(ctx context.Context, conn *elasticsearchservice.ElasticsearchService, id string, timeout time.Duration) error { +func waitVPCEndpointDeleted(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{elasticsearchservice.VpcEndpointStatusDeleting}, + Pending: []string{awstypes.VpcEndpointStatusDeleting}, Target: []string{}, Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, diff --git a/internal/service/elasticsearch/vpc_endpoint_test.go b/internal/service/elasticsearch/vpc_endpoint_test.go index bb3563202764..8eab1ae83c04 100644 --- a/internal/service/elasticsearch/vpc_endpoint_test.go +++ b/internal/service/elasticsearch/vpc_endpoint_test.go @@ -8,8 +8,9 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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" @@ -25,7 +26,7 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { testCases := []struct { name string - apiObjects []*elasticsearchservice.VpcEndpointError + apiObjects []*awstypes.VpcEndpointError notFound bool }{ { @@ -33,20 +34,20 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { }, { name: "slice of nil input", - apiObjects: []*elasticsearchservice.VpcEndpointError{nil, nil}, + apiObjects: []*awstypes.VpcEndpointError{nil, nil}, }, { name: "single SERVER_ERROR", - apiObjects: []*elasticsearchservice.VpcEndpointError{{ - ErrorCode: aws.String(elasticsearchservice.VpcEndpointErrorCodeServerError), + apiObjects: []*awstypes.VpcEndpointError{{ + ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), ErrorMessage: aws.String("fail"), VpcEndpointId: aws.String("aos-12345678"), }}, }, { name: "single ENDPOINT_NOT_FOUND", - apiObjects: []*elasticsearchservice.VpcEndpointError{{ - ErrorCode: aws.String(elasticsearchservice.VpcEndpointErrorCodeEndpointNotFound), + apiObjects: []*awstypes.VpcEndpointError{{ + ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeEndpointNotFound), ErrorMessage: aws.String("Endpoint does not exist"), VpcEndpointId: aws.String("aos-12345678"), }}, @@ -54,14 +55,14 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { }, { name: "no ENDPOINT_NOT_FOUND in many", - apiObjects: []*elasticsearchservice.VpcEndpointError{ + apiObjects: []*awstypes.VpcEndpointError{ { - ErrorCode: aws.String(elasticsearchservice.VpcEndpointErrorCodeServerError), + ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), ErrorMessage: aws.String("fail"), VpcEndpointId: aws.String("aos-abcd0123"), }, { - ErrorCode: aws.String(elasticsearchservice.VpcEndpointErrorCodeServerError), + ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), ErrorMessage: aws.String("crash"), VpcEndpointId: aws.String("aos-12345678"), }, @@ -69,14 +70,14 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { }, { name: "single ENDPOINT_NOT_FOUND in many", - apiObjects: []*elasticsearchservice.VpcEndpointError{ + apiObjects: []*awstypes.VpcEndpointError{ { - ErrorCode: aws.String(elasticsearchservice.VpcEndpointErrorCodeServerError), + ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), ErrorMessage: aws.String("fail"), VpcEndpointId: aws.String("aos-abcd0123"), }, { - ErrorCode: aws.String(elasticsearchservice.VpcEndpointErrorCodeEndpointNotFound), + ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeEndpointNotFound), ErrorMessage: aws.String("Endpoint does not exist"), VpcEndpointId: aws.String("aos-12345678"), }, @@ -103,7 +104,7 @@ func TestAccElasticsearchVPCEndpoint_basic(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var v elasticsearchservice.VpcEndpoint + var v awstypes.VpcEndpoint rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) domainName := testAccRandomDomainName() resourceName := "aws_elasticsearch_vpc_endpoint.test" @@ -141,7 +142,7 @@ func TestAccElasticsearchVPCEndpoint_disappears(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var v elasticsearchservice.VpcEndpoint + var v awstypes.VpcEndpoint rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) domainName := testAccRandomDomainName() resourceName := "aws_elasticsearch_vpc_endpoint.test" @@ -170,7 +171,7 @@ func TestAccElasticsearchVPCEndpoint_update(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var v elasticsearchservice.VpcEndpoint + var v awstypes.VpcEndpoint rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) domainName := testAccRandomDomainName() resourceName := "aws_elasticsearch_vpc_endpoint.test" @@ -209,7 +210,7 @@ func TestAccElasticsearchVPCEndpoint_update(t *testing.T) { }) } -func testAccCheckVPCEndpointExists(ctx context.Context, n string, v *elasticsearchservice.VpcEndpoint) resource.TestCheckFunc { +func testAccCheckVPCEndpointExists(ctx context.Context, n string, v *awstypes.VpcEndpoint) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { diff --git a/internal/service/elasticsearch/wait.go b/internal/service/elasticsearch/wait.go index 6d7d6326e065..0e18fa144360 100644 --- a/internal/service/elasticsearch/wait.go +++ b/internal/service/elasticsearch/wait.go @@ -8,8 +8,8 @@ import ( "fmt" "time" - "github.com/aws/aws-sdk-go/aws" - elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" + "github.com/aws/aws-sdk-go-v2/aws" + elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -48,7 +48,7 @@ func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.Elasticsearc return retry.NonRetryableError(err) } - if !aws.BoolValue(out.Processing) && (out.Endpoint != nil || out.Endpoints != nil) { + if !aws.ToBool(out.Processing) && (out.Endpoint != nil || out.Endpoints != nil) { return nil } @@ -60,7 +60,7 @@ func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.Elasticsearc if err != nil { return fmt.Errorf("describing Elasticsearch domain: %w", err) } - if !aws.BoolValue(out.Processing) && (out.Endpoint != nil || out.Endpoints != nil) { + if !aws.ToBool(out.Processing) && (out.Endpoint != nil || out.Endpoints != nil) { return nil } } @@ -77,7 +77,7 @@ func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.ElasticsearchS return retry.NonRetryableError(err) } - if !aws.BoolValue(out.Processing) { + if !aws.ToBool(out.Processing) { return nil } @@ -89,7 +89,7 @@ func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.ElasticsearchS if err != nil { return fmt.Errorf("describing Elasticsearch domain: %w", err) } - if !aws.BoolValue(out.Processing) { + if !aws.ToBool(out.Processing) { return nil } } @@ -110,7 +110,7 @@ func waitForDomainDelete(ctx context.Context, conn *elasticsearch.ElasticsearchS return retry.NonRetryableError(err) } - if out != nil && !aws.BoolValue(out.Processing) { + if out != nil && !aws.ToBool(out.Processing) { return nil } @@ -124,7 +124,7 @@ func waitForDomainDelete(ctx context.Context, conn *elasticsearch.ElasticsearchS } return fmt.Errorf("describing Elasticsearch domain: %s", err) } - if out != nil && !aws.BoolValue(out.Processing) { + if out != nil && !aws.ToBool(out.Processing) { return nil } } From 554eb1ffd83de2c8161cae0993f9d4574609c26d Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:28:04 +0100 Subject: [PATCH 03/24] make gen --- internal/service/elasticsearch/generate.go | 2 +- .../service_endpoints_gen_test.go | 147 ++++++++++++++---- .../elasticsearch/service_package_gen.go | 36 ++--- internal/service/elasticsearch/tags_gen.go | 29 ++-- 4 files changed, 152 insertions(+), 62 deletions(-) diff --git a/internal/service/elasticsearch/generate.go b/internal/service/elasticsearch/generate.go index 362e91cd0aeb..50dd05e71bb4 100644 --- a/internal/service/elasticsearch/generate.go +++ b/internal/service/elasticsearch/generate.go @@ -1,7 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -ListTags -ListTagsOp=ListTags -ListTagsInIDElem=ARN -ListTagsOutTagsElem=TagList -ServiceTagsSlice -TagOp=AddTags -TagInIDElem=ARN -TagInTagsElem=TagList -UntagOp=RemoveTags -UpdateTags +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ListTags -ListTagsOp=ListTags -ListTagsInIDElem=ARN -ListTagsOutTagsElem=TagList -ServiceTagsSlice -TagOp=AddTags -TagInIDElem=ARN -TagInTagsElem=TagList -UntagOp=RemoveTags -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/elasticsearch/service_endpoints_gen_test.go b/internal/service/elasticsearch/service_endpoints_gen_test.go index f8c5d851c4a4..af3469640e34 100644 --- a/internal/service/elasticsearch/service_endpoints_gen_test.go +++ b/internal/service/elasticsearch/service_endpoints_gen_test.go @@ -4,17 +4,20 @@ package elasticsearch_test import ( "context" + "errors" "fmt" "maps" - "net/url" "os" "path/filepath" + "reflect" "strings" "testing" - elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + elasticsearchservice_sdkv2 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + "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/go-cty/cty" @@ -352,54 +355,63 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S } func defaultEndpoint(region string) string { - r := endpoints.DefaultResolver() + r := elasticsearchservice_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(elasticsearchservice_sdkv1.EndpointsID, region) + ep, err := r.ResolveEndpoint(context.Background(), elasticsearchservice_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + }) if err != nil { return err.Error() } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return url.String() + return ep.URI.String() } func defaultFIPSEndpoint(region string) string { - r := endpoints.DefaultResolver() + r := elasticsearchservice_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(elasticsearchservice_sdkv1.EndpointsID, region, func(opt *endpoints.Options) { - opt.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled + ep, err := r.ResolveEndpoint(context.Background(), elasticsearchservice_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + UseFIPS: aws_sdkv2.Bool(true), }) if err != nil { return err.Error() } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return url.String() + return ep.URI.String() } func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { t.Helper() - client := meta.ElasticsearchConn(ctx) + client := meta.ElasticsearchClient(ctx) - req, _ := client.ListDomainNamesRequest(&elasticsearchservice_sdkv1.ListDomainNamesInput{}) + var result apiCallParams - req.HTTPRequest.URL.Path = "/" - - return apiCallParams{ - endpoint: req.HTTPRequest.URL.String(), - region: aws_sdkv1.StringValue(client.Config.Region), + _, err := client.ListDomainNames(ctx, &elasticsearchservice_sdkv2.ListDomainNamesInput{}, + func(opts *elasticsearchservice_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) { @@ -600,6 +612,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/elasticsearch/service_package_gen.go b/internal/service/elasticsearch/service_package_gen.go index 08befd6db2c2..b1c20c8fdb2b 100644 --- a/internal/service/elasticsearch/service_package_gen.go +++ b/internal/service/elasticsearch/service_package_gen.go @@ -5,10 +5,8 @@ package elasticsearch import ( "context" - elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - endpoints_sdkv1 "github.com/aws/aws-sdk-go/aws/endpoints" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + elasticsearchservice_sdkv2 "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" @@ -63,25 +61,23 @@ func (p *servicePackage) ServicePackageName() string { return names.Elasticsearch } -// 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) (*elasticsearchservice_sdkv1.ElasticsearchService, 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) (*elasticsearchservice_sdkv2.Client, error) { + cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) - cfg := aws_sdkv1.Config{} + return elasticsearchservice_sdkv2.NewFromConfig(cfg, func(o *elasticsearchservice_sdkv2.Options) { + if endpoint := config[names.AttrEndpoint].(string); endpoint != "" { + tflog.Debug(ctx, "setting endpoint", map[string]any{ + "tf_aws.endpoint": endpoint, + }) + o.BaseEndpoint = aws_sdkv2.String(endpoint) - 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) - - if sess.Config.UseFIPSEndpoint == endpoints_sdkv1.FIPSEndpointStateEnabled { - tflog.Debug(ctx, "endpoint set, ignoring UseFIPSEndpoint setting") - cfg.UseFIPSEndpoint = endpoints_sdkv1.FIPSEndpointStateDisabled + if o.EndpointOptions.UseFIPSEndpoint == aws_sdkv2.FIPSEndpointStateEnabled { + tflog.Debug(ctx, "endpoint set, ignoring UseFIPSEndpoint setting") + o.EndpointOptions.UseFIPSEndpoint = aws_sdkv2.FIPSEndpointStateDisabled + } } - } - - return elasticsearchservice_sdkv1.New(sess.Copy(&cfg)), nil + }), nil } func ServicePackage(ctx context.Context) conns.ServicePackage { diff --git a/internal/service/elasticsearch/tags_gen.go b/internal/service/elasticsearch/tags_gen.go index c7517f522888..0403d7176c3b 100644 --- a/internal/service/elasticsearch/tags_gen.go +++ b/internal/service/elasticsearch/tags_gen.go @@ -8,7 +8,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" - "github.com/aws/aws-sdk-go/service/elasticsearchservice/elasticsearchserviceiface" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" @@ -20,12 +19,12 @@ import ( // listTags lists elasticsearch 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 elasticsearchserviceiface.ElasticsearchServiceAPI, identifier string) (tftags.KeyValueTags, error) { +func listTags(ctx context.Context, conn *elasticsearchservice.Client, identifier string, optFns ...func(*elasticsearchservice.Options)) (tftags.KeyValueTags, error) { input := &elasticsearchservice.ListTagsInput{ ARN: aws.String(identifier), } - output, err := conn.ListTags(ctx, input) + output, err := conn.ListTags(ctx, input, optFns...) if err != nil { return tftags.New(ctx, nil), err @@ -37,7 +36,7 @@ func listTags(ctx context.Context, conn elasticsearchserviceiface.ElasticsearchS // ListTags lists elasticsearch 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).ElasticsearchConn(ctx), identifier) + tags, err := listTags(ctx, meta.(*conns.AWSClient).ElasticsearchClient(ctx), identifier) if err != nil { return err @@ -53,11 +52,11 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri // []*SERVICE.Tag handling // Tags returns elasticsearch service tags. -func Tags(tags tftags.KeyValueTags) []*awstypes.Tag { - result := make([]*awstypes.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 := &awstypes.Tag{ + tag := awstypes.Tag{ Key: aws.String(k), Value: aws.String(v), } @@ -69,7 +68,7 @@ func Tags(tags tftags.KeyValueTags) []*awstypes.Tag { } // KeyValueTags creates tftags.KeyValueTags from elasticsearchservice service tags. -func KeyValueTags(ctx context.Context, tags []*awstypes.Tag) tftags.KeyValueTags { +func KeyValueTags(ctx context.Context, tags []awstypes.Tag) tftags.KeyValueTags { m := make(map[string]*string, len(tags)) for _, tag := range tags { @@ -81,7 +80,7 @@ func KeyValueTags(ctx context.Context, tags []*awstypes.Tag) tftags.KeyValueTags // getTagsIn returns elasticsearch service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) []*awstypes.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 @@ -92,7 +91,7 @@ func getTagsIn(ctx context.Context) []*awstypes.Tag { } // setTagsOut sets elasticsearch service tags in Context. -func setTagsOut(ctx context.Context, tags []*awstypes.Tag) { +func setTagsOut(ctx context.Context, tags []awstypes.Tag) { if inContext, ok := tftags.FromContext(ctx); ok { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } @@ -101,7 +100,7 @@ func setTagsOut(ctx context.Context, tags []*awstypes.Tag) { // updateTags updates elasticsearch 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 elasticsearchserviceiface.ElasticsearchServiceAPI, identifier string, oldTagsMap, newTagsMap any) error { +func updateTags(ctx context.Context, conn *elasticsearchservice.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*elasticsearchservice.Options)) error { oldTags := tftags.New(ctx, oldTagsMap) newTags := tftags.New(ctx, newTagsMap) @@ -112,10 +111,10 @@ func updateTags(ctx context.Context, conn elasticsearchserviceiface.Elasticsearc if len(removedTags) > 0 { input := &elasticsearchservice.RemoveTagsInput{ ARN: aws.String(identifier), - TagKeys: aws.StringSlice(removedTags.Keys()), + TagKeys: removedTags.Keys(), } - _, err := conn.RemoveTags(ctx, input) + _, err := conn.RemoveTags(ctx, input, optFns...) if err != nil { return fmt.Errorf("untagging resource (%s): %w", identifier, err) @@ -130,7 +129,7 @@ func updateTags(ctx context.Context, conn elasticsearchserviceiface.Elasticsearc TagList: Tags(updatedTags), } - _, err := conn.AddTags(ctx, input) + _, err := conn.AddTags(ctx, input, optFns...) if err != nil { return fmt.Errorf("tagging resource (%s): %w", identifier, err) @@ -143,5 +142,5 @@ func updateTags(ctx context.Context, conn elasticsearchserviceiface.Elasticsearc // UpdateTags updates elasticsearch 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).ElasticsearchConn(ctx), identifier, oldTags, newTags) + return updateTags(ctx, meta.(*conns.AWSClient).ElasticsearchClient(ctx), identifier, oldTags, newTags) } From 7463014e6b813aea75ae5c24ac05fbdd6ad0bd64 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:53:52 +0100 Subject: [PATCH 04/24] d/elasticsearch_domain, r/elasticsearch_domain: Migrate to AWS SDK v2 --- internal/service/elasticsearch/domain.go | 170 +++++++++--------- .../elasticsearch/domain_data_source.go | 7 +- internal/service/elasticsearch/domain_test.go | 169 ++++++++--------- 3 files changed, 171 insertions(+), 175 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index 5e369c8f9789..7a20e62d85d6 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -13,7 +13,7 @@ import ( "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" awspolicy "github.com/hashicorp/awspolicyequivalence" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" @@ -21,6 +21,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" "github.com/hashicorp/terraform-provider-aws/internal/semver" @@ -54,7 +56,7 @@ func ResourceDomain() *schema.Resource { newVersion := d.Get("elasticsearch_version").(string) domainName := d.Get(names.AttrDomainName).(string) - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) resp, err := conn.GetCompatibleElasticsearchVersions(ctx, &elasticsearch.GetCompatibleElasticsearchVersionsInput{ DomainName: aws.String(domainName), }) @@ -66,7 +68,7 @@ func ResourceDomain() *schema.Resource { return true } for _, targetVersion := range resp.CompatibleElasticsearchVersions[0].TargetVersions { - if aws.ToString(targetVersion) == newVersion { + if targetVersion == newVersion { return false } } @@ -166,9 +168,9 @@ func ResourceDomain() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "desired_state": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(elasticsearch.AutoTuneDesiredState_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.AutoTuneDesiredState](), }, "maintenance_schedule": { Type: schema.TypeSet, @@ -187,9 +189,9 @@ func ResourceDomain() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ names.AttrUnit: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(elasticsearch.TimeUnit_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.TimeUnit](), }, names.AttrValue: { Type: schema.TypeInt, @@ -207,10 +209,10 @@ func ResourceDomain() *schema.Resource { }, }, "rollback_on_disable": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice(elasticsearch.RollbackOnDisable_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.RollbackOnDisable](), }, }, }, @@ -260,7 +262,7 @@ func ResourceDomain() *schema.Resource { names.AttrInstanceType: { Type: schema.TypeString, Optional: true, - Default: elasticsearch.ESPartitionInstanceTypeM3MediumElasticsearch, + Default: awstypes.ESPartitionInstanceTypeM3MediumElasticsearch, }, "warm_count": { Type: schema.TypeInt, @@ -275,8 +277,8 @@ func ResourceDomain() *schema.Resource { Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringInSlice([]string{ - elasticsearch.ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch, - elasticsearch.ESWarmPartitionInstanceTypeUltrawarm1LargeElasticsearch, + string(awstypes.ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch), + string(awstypes.ESWarmPartitionInstanceTypeUltrawarm1LargeElasticsearch), "ultrawarm1.xlarge.elasticsearch", }, false), }, @@ -372,10 +374,10 @@ func ResourceDomain() *schema.Resource { Default: true, }, "tls_security_policy": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice(elasticsearch.TLSSecurityPolicy_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.TLSSecurityPolicy](), }, }, }, @@ -407,10 +409,10 @@ func ResourceDomain() *schema.Resource { Optional: true, }, names.AttrVolumeType: { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice(elasticsearch.VolumeType_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.VolumeType](), }, }, }, @@ -465,9 +467,9 @@ func ResourceDomain() *schema.Resource { Default: true, }, "log_type": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(elasticsearch.LogType_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.LogType](), }, }, }, @@ -540,7 +542,7 @@ func ResourceDomain() *schema.Resource { func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) // The API doesn't check for duplicate names // so w/out this check Create would act as upsert @@ -569,7 +571,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte } if v, ok := d.GetOk("advanced_options"); ok { - input.AdvancedOptions = flex.ExpandStringMap(v.(map[string]interface{})) + input.AdvancedOptions = flex.ExpandStringValueMap(v.(map[string]interface{})) } if v, ok := d.GetOk("advanced_security_options"); ok { @@ -632,8 +634,8 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte o := options[0].(map[string]interface{}) - snapshotOptions := elasticsearch.SnapshotOptions{ - AutomatedSnapshotStartHour: aws.Int64(int64(o["automated_snapshot_start_hour"].(int))), + snapshotOptions := awstypes.SnapshotOptions{ + AutomatedSnapshotStartHour: aws.Int32(int32(o["automated_snapshot_start_hour"].(int))), } input.SnapshotOptions = &snapshotOptions @@ -662,21 +664,21 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte input.CognitoOptions = expandCognitoOptions(v.([]interface{})) } - log.Printf("[DEBUG] Creating Elasticsearch Domain: %s", input) + log.Printf("[DEBUG] Creating Elasticsearch Domain: %+v", input) outputRaw, err := tfresource.RetryWhen(ctx, propagationTimeout, func() (interface{}, error) { return conn.CreateElasticsearchDomain(ctx, input) }, func(err error) (bool, error) { - if tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeInvalidTypeException, "Error setting policy") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "enable a service-linked role to give Amazon ES permissions") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "Domain is still being deleted") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "Amazon Elasticsearch must be allowed to use the passed role") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "The passed role has not propagated yet") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "Authentication error") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "Unauthorized Operation: Elasticsearch must be authorised to describe") || - tfawserr.ErrMessageContains(err, elasticsearch.ErrCodeValidationException, "The passed role must authorize Amazon Elasticsearch to describe") { + if errs.IsAErrorMessageContains[*awstypes.InvalidTypeException](err, "Error setting policy") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "enable a service-linked role to give Amazon ES permissions") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "Domain is still being deleted") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "Amazon Elasticsearch must be allowed to use the passed role") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "The passed role has not propagated yet") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "Authentication error") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "Unauthorized Operation: Elasticsearch must be authorised to describe") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "The passed role must authorize Amazon Elasticsearch to describe") { return true, err } @@ -700,7 +702,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte DomainName: aws.String(name), } - log.Printf("[DEBUG] Updating Elasticsearch Domain config: %s", input) + log.Printf("[DEBUG] Updating Elasticsearch Domain config: %+v", input) _, err = conn.UpdateElasticsearchDomainConfig(ctx, input) if err != nil { @@ -717,7 +719,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) name := d.Get(names.AttrDomainName).(string) ds, err := FindDomainByName(ctx, conn, name) @@ -752,7 +754,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf d.Set("access_policies", policies) } - options := advancedOptionsIgnoreDefault(d.Get("advanced_options").(map[string]interface{}), flex.FlattenStringMap(ds.AdvancedOptions)) + options := advancedOptionsIgnoreDefault(d.Get("advanced_options").(map[string]interface{}), flex.FlattenStringValueMap(ds.AdvancedOptions)) if err = d.Set("advanced_options", options); err != nil { return sdkdiag.AppendErrorf(diags, "setting advanced_options: %s", err) } @@ -812,7 +814,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf return sdkdiag.AppendErrorf(diags, "setting vpc_options: %s", err) } - endpoints := flex.FlattenStringMap(ds.Endpoints) + endpoints := flex.FlattenStringValueMap(ds.Endpoints) d.Set(names.AttrEndpoint, endpoints["vpc"]) d.Set("kibana_endpoint", getKibanaEndpoint(d)) @@ -844,7 +846,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) { name := d.Get(names.AttrDomainName).(string) @@ -861,7 +863,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte } if d.HasChange("advanced_options") { - input.AdvancedOptions = flex.ExpandStringMap(d.Get("advanced_options").(map[string]interface{})) + input.AdvancedOptions = flex.ExpandStringValueMap(d.Get("advanced_options").(map[string]interface{})) } if d.HasChange("advanced_security_options") { @@ -928,8 +930,8 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte if len(options) == 1 { o := options[0].(map[string]interface{}) - snapshotOptions := elasticsearch.SnapshotOptions{ - AutomatedSnapshotStartHour: aws.Int64(int64(o["automated_snapshot_start_hour"].(int))), + snapshotOptions := awstypes.SnapshotOptions{ + AutomatedSnapshotStartHour: aws.Int32(int32(o["automated_snapshot_start_hour"].(int))), } input.SnapshotOptions = &snapshotOptions @@ -951,7 +953,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte input.LogPublishingOptions = expandLogPublishingOptions(d.Get("log_publishing_options").(*schema.Set)) } - log.Printf("[DEBUG] Updating Elasticsearch Domain config: %s", input) + log.Printf("[DEBUG] Updating Elasticsearch Domain config: %+v", input) _, err := conn.UpdateElasticsearchDomainConfig(ctx, input) if err != nil { @@ -968,7 +970,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte TargetVersion: aws.String(d.Get("elasticsearch_version").(string)), } - log.Printf("[DEBUG] Upgrading Elasticsearch Domain: %s", input) + log.Printf("[DEBUG] Upgrading Elasticsearch Domain: %+v", input) _, err := conn.UpgradeElasticsearchDomain(ctx, input) if err != nil { @@ -986,7 +988,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte func resourceDomainDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) name := d.Get(names.AttrDomainName).(string) @@ -995,7 +997,7 @@ func resourceDomainDelete(ctx context.Context, d *schema.ResourceData, meta inte DomainName: aws.String(name), }) - if tfawserr.ErrCodeEquals(err, elasticsearch.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -1011,7 +1013,7 @@ func resourceDomainDelete(ctx context.Context, d *schema.ResourceData, meta inte } func resourceDomainImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) d.Set(names.AttrDomainName, d.Id()) @@ -1061,8 +1063,8 @@ func isCustomEndpointDisabled(k, old, new string, d *schema.ResourceData) bool { return false } -func expandNodeToNodeEncryptionOptions(s map[string]interface{}) *elasticsearch.NodeToNodeEncryptionOptions { - options := elasticsearch.NodeToNodeEncryptionOptions{} +func expandNodeToNodeEncryptionOptions(s map[string]interface{}) *awstypes.NodeToNodeEncryptionOptions { + options := awstypes.NodeToNodeEncryptionOptions{} if v, ok := s[names.AttrEnabled]; ok { options.Enabled = aws.Bool(v.(bool)) @@ -1070,7 +1072,7 @@ func expandNodeToNodeEncryptionOptions(s map[string]interface{}) *elasticsearch. return &options } -func flattenNodeToNodeEncryptionOptions(o *elasticsearch.NodeToNodeEncryptionOptions) []map[string]interface{} { +func flattenNodeToNodeEncryptionOptions(o *awstypes.NodeToNodeEncryptionOptions) []map[string]interface{} { if o == nil { return []map[string]interface{}{} } @@ -1083,8 +1085,8 @@ func flattenNodeToNodeEncryptionOptions(o *elasticsearch.NodeToNodeEncryptionOpt return []map[string]interface{}{m} } -func expandClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchClusterConfig { - config := elasticsearch.ElasticsearchClusterConfig{} +func expandClusterConfig(m map[string]interface{}) *awstypes.ElasticsearchClusterConfig { + config := awstypes.ElasticsearchClusterConfig{} if v, ok := m["cold_storage_options"].([]interface{}); ok && len(v) > 0 { config.ColdStorageOptions = expandColdStorageOptions(v[0].(map[string]interface{})) @@ -1096,19 +1098,19 @@ func expandClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchC if isEnabled { if v, ok := m["dedicated_master_count"]; ok && v.(int) > 0 { - config.DedicatedMasterCount = aws.Int64(int64(v.(int))) + config.DedicatedMasterCount = aws.Int32(int32(v.(int))) } if v, ok := m["dedicated_master_type"]; ok && v.(string) != "" { - config.DedicatedMasterType = aws.String(v.(string)) + config.DedicatedMasterType = awstypes.ESPartitionInstanceType(v.(string)) } } } if v, ok := m[names.AttrInstanceCount]; ok { - config.InstanceCount = aws.Int64(int64(v.(int))) + config.InstanceCount = aws.Int32(int32(v.(int))) } if v, ok := m[names.AttrInstanceType]; ok { - config.InstanceType = aws.String(v.(string)) + config.InstanceType = awstypes.ESPartitionInstanceType(v.(string)) } if v, ok := m["zone_awareness_enabled"]; ok { @@ -1128,11 +1130,11 @@ func expandClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchC if isEnabled { if v, ok := m["warm_count"]; ok { - config.WarmCount = aws.Int64(int64(v.(int))) + config.WarmCount = aws.Int32(int32(v.(int))) } if v, ok := m["warm_type"]; ok { - config.WarmType = aws.String(v.(string)) + config.WarmType = awstypes.ESWarmPartitionInstanceType(v.(string)) } } } @@ -1140,12 +1142,12 @@ func expandClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchC return &config } -func expandColdStorageOptions(tfMap map[string]interface{}) *elasticsearch.ColdStorageOptions { +func expandColdStorageOptions(tfMap map[string]interface{}) *awstypes.ColdStorageOptions { if tfMap == nil { return nil } - apiObject := &elasticsearch.ColdStorageOptions{} + apiObject := &awstypes.ColdStorageOptions{} if v, ok := tfMap[names.AttrEnabled].(bool); ok { apiObject.Enabled = aws.Bool(v) @@ -1154,23 +1156,23 @@ func expandColdStorageOptions(tfMap map[string]interface{}) *elasticsearch.ColdS return apiObject } -func expandZoneAwarenessConfig(l []interface{}) *elasticsearch.ZoneAwarenessConfig { +func expandZoneAwarenessConfig(l []interface{}) *awstypes.ZoneAwarenessConfig { if len(l) == 0 || l[0] == nil { return nil } m := l[0].(map[string]interface{}) - zoneAwarenessConfig := &elasticsearch.ZoneAwarenessConfig{} + zoneAwarenessConfig := &awstypes.ZoneAwarenessConfig{} if v, ok := m["availability_zone_count"]; ok && v.(int) > 0 { - zoneAwarenessConfig.AvailabilityZoneCount = aws.Int64(int64(v.(int))) + zoneAwarenessConfig.AvailabilityZoneCount = aws.Int32(int32(v.(int))) } return zoneAwarenessConfig } -func flattenClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[string]interface{} { +func flattenClusterConfig(c *awstypes.ElasticsearchClusterConfig) []map[string]interface{} { m := map[string]interface{}{ "zone_awareness_config": flattenZoneAwarenessConfig(c.ZoneAwarenessConfig), "zone_awareness_enabled": aws.ToBool(c.ZoneAwarenessEnabled), @@ -1180,34 +1182,28 @@ func flattenClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[str m["cold_storage_options"] = flattenColdStorageOptions(c.ColdStorageOptions) } if c.DedicatedMasterCount != nil { - m["dedicated_master_count"] = aws.ToInt64(c.DedicatedMasterCount) + m["dedicated_master_count"] = aws.ToInt32(c.DedicatedMasterCount) } if c.DedicatedMasterEnabled != nil { m["dedicated_master_enabled"] = aws.ToBool(c.DedicatedMasterEnabled) } - if c.DedicatedMasterType != nil { - m["dedicated_master_type"] = aws.ToString(c.DedicatedMasterType) - } + m["dedicated_master_type"] = string(c.DedicatedMasterType) if c.InstanceCount != nil { - m[names.AttrInstanceCount] = aws.ToInt64(c.InstanceCount) - } - if c.InstanceType != nil { - m[names.AttrInstanceType] = aws.ToString(c.InstanceType) + m[names.AttrInstanceCount] = aws.ToInt32(c.InstanceCount) } + m[names.AttrInstanceType] = string(c.InstanceType) if c.WarmEnabled != nil { m["warm_enabled"] = aws.ToBool(c.WarmEnabled) } if c.WarmCount != nil { - m["warm_count"] = aws.ToInt64(c.WarmCount) - } - if c.WarmType != nil { - m["warm_type"] = aws.ToString(c.WarmType) + m["warm_count"] = aws.ToInt32(c.WarmCount) } + m["warm_type"] = string(c.WarmType) return []map[string]interface{}{m} } -func flattenColdStorageOptions(coldStorageOptions *elasticsearch.ColdStorageOptions) []interface{} { +func flattenColdStorageOptions(coldStorageOptions *awstypes.ColdStorageOptions) []interface{} { if coldStorageOptions == nil { return []interface{}{} } @@ -1219,13 +1215,13 @@ func flattenColdStorageOptions(coldStorageOptions *elasticsearch.ColdStorageOpti return []interface{}{m} } -func flattenZoneAwarenessConfig(zoneAwarenessConfig *elasticsearch.ZoneAwarenessConfig) []interface{} { +func flattenZoneAwarenessConfig(zoneAwarenessConfig *awstypes.ZoneAwarenessConfig) []interface{} { if zoneAwarenessConfig == nil { return []interface{}{} } m := map[string]interface{}{ - "availability_zone_count": aws.ToInt64(zoneAwarenessConfig.AvailabilityZoneCount), + "availability_zone_count": aws.ToInt32(zoneAwarenessConfig.AvailabilityZoneCount), } return []interface{}{m} @@ -1256,7 +1252,7 @@ func advancedOptionsIgnoreDefault(o map[string]interface{}, n map[string]interfa // This check prevents a ValidationException when updating EBS volume types from a value // that supports IOPS (ex. gp3) to one that doesn't (ex. gp2). func EBSVolumeTypePermitsIopsInput(volumeType string) bool { - permittedTypes := []string{elasticsearch.VolumeTypeGp3, elasticsearch.VolumeTypeIo1} + permittedTypes := enum.Slice(awstypes.VolumeTypeGp3, awstypes.VolumeTypeIo1) for _, t := range permittedTypes { if volumeType == t { return true @@ -1270,7 +1266,7 @@ func EBSVolumeTypePermitsIopsInput(volumeType string) bool { // This check prevents a ValidationException when updating EBS volume types from a value // that supports Throughput (ex. gp3) to one that doesn't (ex. gp2). func EBSVolumeTypePermitsThroughputInput(volumeType string) bool { - permittedTypes := []string{elasticsearch.VolumeTypeGp3} + permittedTypes := enum.Slice(awstypes.VolumeTypeGp3) for _, t := range permittedTypes { if volumeType == t { return true diff --git a/internal/service/elasticsearch/domain_data_source.go b/internal/service/elasticsearch/domain_data_source.go index ed2d6bfa3ce4..2f67efb96c73 100644 --- a/internal/service/elasticsearch/domain_data_source.go +++ b/internal/service/elasticsearch/domain_data_source.go @@ -8,7 +8,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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/structure" @@ -348,7 +347,7 @@ func DataSourceDomain() *schema.Resource { func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) @@ -381,7 +380,7 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set("access_policies", policies) } - if err := d.Set("advanced_options", flex.FlattenStringMap(ds.AdvancedOptions)); err != nil { + if err := d.Set("advanced_options", flex.FlattenStringValueMap(ds.AdvancedOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting advanced_options: %s", err) } @@ -425,7 +424,7 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "setting vpc_options: %s", err) } - endpoints := flex.FlattenStringMap(ds.Endpoints) + endpoints := flex.FlattenStringValueMap(ds.Endpoints) if err := d.Set(names.AttrEndpoint, endpoints["vpc"]); err != nil { return sdkdiag.AppendErrorf(diags, "setting endpoint: %s", err) } diff --git a/internal/service/elasticsearch/domain_test.go b/internal/service/elasticsearch/domain_test.go index 914f6048f52d..3f3fdc334138 100644 --- a/internal/service/elasticsearch/domain_test.go +++ b/internal/service/elasticsearch/domain_test.go @@ -12,6 +12,7 @@ import ( "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -32,10 +33,10 @@ func TestEBSVolumeTypePermitsIopsInput(t *testing.T) { want bool }{ {"empty", "", false}, - {"gp2", elasticsearch.VolumeTypeGp2, false}, - {"gp3", elasticsearch.VolumeTypeGp3, true}, - {"io1", elasticsearch.VolumeTypeIo1, true}, - {"standard", elasticsearch.VolumeTypeStandard, false}, + {"gp2", string(awstypes.VolumeTypeGp2), false}, + {"gp3", string(awstypes.VolumeTypeGp3), true}, + {"io1", string(awstypes.VolumeTypeIo1), true}, + {"standard", string(awstypes.VolumeTypeStandard), false}, } for _, testCase := range testCases { testCase := testCase @@ -58,10 +59,10 @@ func TestEBSVolumeTypePermitsThroughputInput(t *testing.T) { want bool }{ {"empty", "", false}, - {"gp2", elasticsearch.VolumeTypeGp2, false}, - {"gp3", elasticsearch.VolumeTypeGp3, true}, - {"io1", elasticsearch.VolumeTypeIo1, false}, - {"standard", elasticsearch.VolumeTypeStandard, false}, + {"gp2", string(awstypes.VolumeTypeGp2), false}, + {"gp3", string(awstypes.VolumeTypeGp3), true}, + {"io1", string(awstypes.VolumeTypeIo1), false}, + {"standard", string(awstypes.VolumeTypeStandard), false}, } for _, testCase := range testCases { testCase := testCase @@ -81,7 +82,7 @@ func TestAccElasticsearchDomain_basic(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -113,7 +114,7 @@ func TestAccElasticsearchDomain_basic(t *testing.T) { func TestAccElasticsearchDomain_requireHTTPS(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resource.ParallelTest(t, resource.TestCase{ @@ -152,7 +153,7 @@ func TestAccElasticsearchDomain_customEndpoint(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" customEndpoint := fmt.Sprintf("%s.example.com", rName) @@ -204,7 +205,7 @@ func TestAccElasticsearchDomain_customEndpoint(t *testing.T) { func TestAccElasticsearchDomain_Cluster_zoneAwareness(t *testing.T) { ctx := acctest.Context(t) - var domain1, domain2, domain3, domain4 elasticsearch.ElasticsearchDomainStatus + var domain1, domain2, domain3, domain4 awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -264,7 +265,7 @@ func TestAccElasticsearchDomain_Cluster_zoneAwareness(t *testing.T) { func TestAccElasticsearchDomain_warm(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -322,7 +323,7 @@ func TestAccElasticsearchDomain_warm(t *testing.T) { func TestAccElasticsearchDomain_withColdStorageOptions(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -360,7 +361,7 @@ func TestAccElasticsearchDomain_withColdStorageOptions(t *testing.T) { func TestAccElasticsearchDomain_withDedicatedMaster(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -404,7 +405,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -413,7 +414,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { ErrorCheck: acctest.ErrorCheck(t, names.ElasticsearchServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) _, err := conn.DeleteElasticsearchDomain(ctx, &elasticsearch.DeleteElasticsearchDomainInput{ DomainName: aws.String(rName), }) @@ -423,12 +424,12 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { { PreConfig: func() { // Create duplicate - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) _, err := conn.CreateElasticsearchDomain(ctx, &elasticsearch.CreateElasticsearchDomainInput{ DomainName: aws.String(rName), - EBSOptions: &elasticsearch.EBSOptions{ + EBSOptions: &awstypes.EBSOptions{ EBSEnabled: aws.Bool(true), - VolumeSize: aws.Int64(10), + VolumeSize: aws.Int32(10), }, }) if err != nil { @@ -458,7 +459,7 @@ func TestAccElasticsearchDomain_v23(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -492,7 +493,7 @@ func TestAccElasticsearchDomain_complex(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -524,7 +525,7 @@ func TestAccElasticsearchDomain_vpc(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -552,7 +553,7 @@ func TestAccElasticsearchDomain_vpc(t *testing.T) { func TestAccElasticsearchDomain_VPC_update(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -592,7 +593,7 @@ func TestAccElasticsearchDomain_internetToVPCEndpoint(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -630,7 +631,7 @@ func TestAccElasticsearchDomain_AutoTuneOptions(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() autoTuneStartAtTime := testAccGetValidStartAtTime(t, "24h") resourceName := "aws_elasticsearch_domain.test" @@ -675,7 +676,7 @@ func TestAccElasticsearchDomain_AdvancedSecurityOptions_userDB(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -713,7 +714,7 @@ func TestAccElasticsearchDomain_AdvancedSecurityOptions_iam(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -751,7 +752,7 @@ func TestAccElasticsearchDomain_AdvancedSecurityOptions_disabled(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -789,7 +790,7 @@ func TestAccElasticsearchDomain_LogPublishingOptions_indexSlowLogs(t *testing.T) t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -800,12 +801,12 @@ func TestAccElasticsearchDomain_LogPublishingOptions_indexSlowLogs(t *testing.T) CheckDestroy: testAccCheckDomainDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeIndexSlowLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, string(awstypes.LogTypeIndexSlowLogs)), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(ctx, resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", acctest.Ct1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "log_publishing_options.*", map[string]string{ - "log_type": elasticsearch.LogTypeIndexSlowLogs, + "log_type": string(awstypes.LogTypeIndexSlowLogs), }), ), }, @@ -825,7 +826,7 @@ func TestAccElasticsearchDomain_LogPublishingOptions_searchSlowLogs(t *testing.T t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -836,12 +837,12 @@ func TestAccElasticsearchDomain_LogPublishingOptions_searchSlowLogs(t *testing.T CheckDestroy: testAccCheckDomainDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeSearchSlowLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, string(awstypes.LogTypeSearchSlowLogs)), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(ctx, resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", acctest.Ct1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "log_publishing_options.*", map[string]string{ - "log_type": elasticsearch.LogTypeSearchSlowLogs, + "log_type": string(awstypes.LogTypeSearchSlowLogs), }), ), }, @@ -861,7 +862,7 @@ func TestAccElasticsearchDomain_LogPublishingOptions_esApplicationLogs(t *testin t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -872,12 +873,12 @@ func TestAccElasticsearchDomain_LogPublishingOptions_esApplicationLogs(t *testin CheckDestroy: testAccCheckDomainDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeEsApplicationLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, string(awstypes.LogTypeEsApplicationLogs)), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(ctx, resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", acctest.Ct1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "log_publishing_options.*", map[string]string{ - "log_type": elasticsearch.LogTypeEsApplicationLogs, + "log_type": string(awstypes.LogTypeEsApplicationLogs), }), ), }, @@ -897,7 +898,7 @@ func TestAccElasticsearchDomain_LogPublishingOptions_auditLogs(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -908,12 +909,12 @@ func TestAccElasticsearchDomain_LogPublishingOptions_auditLogs(t *testing.T) { CheckDestroy: testAccCheckDomainDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccDomainConfig_logPublishingOptions(rName, elasticsearch.LogTypeAuditLogs), + Config: testAccDomainConfig_logPublishingOptions(rName, string(awstypes.LogTypeAuditLogs)), Check: resource.ComposeTestCheckFunc( testAccCheckDomainExists(ctx, resourceName, &domain), resource.TestCheckResourceAttr(resourceName, "log_publishing_options.#", acctest.Ct1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "log_publishing_options.*", map[string]string{ - "log_type": elasticsearch.LogTypeAuditLogs, + "log_type": string(awstypes.LogTypeAuditLogs), }), ), }, @@ -935,7 +936,7 @@ func TestAccElasticsearchDomain_cognitoOptionsCreateAndRemove(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -979,7 +980,7 @@ func TestAccElasticsearchDomain_cognitoOptionsUpdate(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1023,7 +1024,7 @@ func TestAccElasticsearchDomain_policy(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1055,7 +1056,7 @@ func TestAccElasticsearchDomain_policyIgnoreEquivalent(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1085,7 +1086,7 @@ func TestAccElasticsearchDomain_Encryption_atRestDefaultKey(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1118,7 +1119,7 @@ func TestAccElasticsearchDomain_Encryption_atRestSpecifyKey(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1151,7 +1152,7 @@ func TestAccElasticsearchDomain_Encryption_atRestEnable(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain1, domain2 elasticsearch.ElasticsearchDomainStatus + var domain1, domain2 awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1193,7 +1194,7 @@ func TestAccElasticsearchDomain_Encryption_atRestEnableLegacy(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain1, domain2 elasticsearch.ElasticsearchDomainStatus + var domain1, domain2 awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1227,7 +1228,7 @@ func TestAccElasticsearchDomain_Encryption_nodeToNode(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1260,7 +1261,7 @@ func TestAccElasticsearchDomain_Encryption_nodeToNodeEnable(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain1, domain2 elasticsearch.ElasticsearchDomainStatus + var domain1, domain2 awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1302,7 +1303,7 @@ func TestAccElasticsearchDomain_Encryption_nodeToNodeEnableLegacy(t *testing.T) t.Skip("skipping long-running test in short mode") } - var domain1, domain2 elasticsearch.ElasticsearchDomainStatus + var domain1, domain2 awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1343,7 +1344,7 @@ func TestAccElasticsearchDomain_tags(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1394,7 +1395,7 @@ func TestAccElasticsearchDomain_update(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var input elasticsearch.ElasticsearchDomainStatus + var input awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1436,7 +1437,7 @@ func TestAccElasticsearchDomain_VolumeType_update(t *testing.T) { ctx := acctest.Context(t) - var input elasticsearch.ElasticsearchDomainStatus + var input awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1492,7 +1493,7 @@ func TestAccElasticsearchDomain_VolumeType_gp3ToGP2(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var input elasticsearch.ElasticsearchDomainStatus + var input awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1539,7 +1540,7 @@ func TestAccElasticsearchDomain_VolumeType_missing(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus resourceName := "aws_elasticsearch_domain.test" rName := testAccRandomDomainName() @@ -1574,7 +1575,7 @@ func TestAccElasticsearchDomain_VolumeType_missing(t *testing.T) { func TestAccElasticsearchDomain_Update_version(t *testing.T) { ctx := acctest.Context(t) - var domain1, domain2, domain3 elasticsearch.ElasticsearchDomainStatus + var domain1, domain2, domain3 awstypes.ElasticsearchDomainStatus rName := testAccRandomDomainName() resourceName := "aws_elasticsearch_domain.test" @@ -1646,20 +1647,20 @@ func testAccRandomDomainName() string { return fmt.Sprintf("%s-%s", acctest.ResourcePrefix, sdkacctest.RandString(28-(len(acctest.ResourcePrefix)+1))) } -func testAccCheckDomainEndpointOptions(enforceHTTPS bool, tls string, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckDomainEndpointOptions(enforceHTTPS bool, tls string, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { options := status.DomainEndpointOptions if *options.EnforceHTTPS != enforceHTTPS { return fmt.Errorf("EnforceHTTPS differ. Given: %t, Expected: %t", *options.EnforceHTTPS, enforceHTTPS) } - if *options.TLSSecurityPolicy != tls { - return fmt.Errorf("TLSSecurityPolicy differ. Given: %s, Expected: %s", *options.TLSSecurityPolicy, tls) + if string(options.TLSSecurityPolicy) != tls { + return fmt.Errorf("TLSSecurityPolicy differ. Given: %s, Expected: %s", options.TLSSecurityPolicy, tls) } return nil } } -func testAccCheckCustomEndpoint(n string, customEndpointEnabled bool, customEndpoint string, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckCustomEndpoint(n string, customEndpointEnabled bool, customEndpoint string, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -1682,7 +1683,7 @@ func testAccCheckCustomEndpoint(n string, customEndpointEnabled bool, customEndp } } -func testAccCheckNumberOfSecurityGroups(numberOfSecurityGroups int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckNumberOfSecurityGroups(numberOfSecurityGroups int, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { count := len(status.VPCOptions.SecurityGroupIds) if count != numberOfSecurityGroups { @@ -1692,37 +1693,37 @@ func testAccCheckNumberOfSecurityGroups(numberOfSecurityGroups int, status *elas } } -func testAccCheckEBSVolumeThroughput(ebsVolumeThroughput int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckEBSVolumeThroughput(ebsVolumeThroughput int, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.EBSOptions - if *conf.Throughput != int64(ebsVolumeThroughput) { + if *conf.Throughput != int32(ebsVolumeThroughput) { return fmt.Errorf("EBS throughput differ. Given: %d, Expected: %d", *conf.Throughput, ebsVolumeThroughput) } return nil } } -func testAccCheckEBSVolumeIops(ebsVolumeIops int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckEBSVolumeIops(ebsVolumeIops int, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.EBSOptions - if *conf.Iops != int64(ebsVolumeIops) { + if *conf.Iops != int32(ebsVolumeIops) { return fmt.Errorf("EBS IOPS differ. Given: %d, Expected: %d", *conf.Iops, ebsVolumeIops) } return nil } } -func testAccCheckEBSVolumeSize(ebsVolumeSize int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckEBSVolumeSize(ebsVolumeSize int, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.EBSOptions - if *conf.VolumeSize != int64(ebsVolumeSize) { + if *conf.VolumeSize != int32(ebsVolumeSize) { return fmt.Errorf("EBS volume size differ. Given: %d, Expected: %d", *conf.VolumeSize, ebsVolumeSize) } return nil } } -func testAccCheckEBSVolumeEnabled(ebsEnabled bool, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckEBSVolumeEnabled(ebsEnabled bool, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.EBSOptions if *conf.EBSEnabled != ebsEnabled { @@ -1732,27 +1733,27 @@ func testAccCheckEBSVolumeEnabled(ebsEnabled bool, status *elasticsearch.Elastic } } -func testAccCheckSnapshotHour(snapshotHour int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckSnapshotHour(snapshotHour int, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.SnapshotOptions - if *conf.AutomatedSnapshotStartHour != int64(snapshotHour) { + if *conf.AutomatedSnapshotStartHour != int32(snapshotHour) { return fmt.Errorf("Snapshots start hour differ. Given: %d, Expected: %d", *conf.AutomatedSnapshotStartHour, snapshotHour) } return nil } } -func testAccCheckNumberOfInstances(numberOfInstances int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckNumberOfInstances(numberOfInstances int, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.ElasticsearchClusterConfig - if *conf.InstanceCount != int64(numberOfInstances) { + if *conf.InstanceCount != int32(numberOfInstances) { return fmt.Errorf("Number of instances differ. Given: %d, Expected: %d", *conf.InstanceCount, numberOfInstances) } return nil } } -func testAccCheckDomainEncrypted(encrypted bool, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckDomainEncrypted(encrypted bool, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.EncryptionAtRestOptions if *conf.Enabled != encrypted { @@ -1762,7 +1763,7 @@ func testAccCheckDomainEncrypted(encrypted bool, status *elasticsearch.Elasticse } } -func testAccCheckNodeToNodeEncrypted(encrypted bool, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckNodeToNodeEncrypted(encrypted bool, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { options := status.NodeToNodeEncryptionOptions if aws.ToBool(options.Enabled) != encrypted { @@ -1772,7 +1773,7 @@ func testAccCheckNodeToNodeEncrypted(encrypted bool, status *elasticsearch.Elast } } -func testAccCheckAdvancedSecurityOptions(enabled bool, userDbEnabled bool, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckAdvancedSecurityOptions(enabled bool, userDbEnabled bool, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.AdvancedSecurityOptions @@ -1798,7 +1799,7 @@ func testAccCheckAdvancedSecurityOptions(enabled bool, userDbEnabled bool, statu } } -func testAccCheckCognitoOptions(enabled bool, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckCognitoOptions(enabled bool, status *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { conf := status.CognitoOptions if *conf.Enabled != enabled { @@ -1808,7 +1809,7 @@ func testAccCheckCognitoOptions(enabled bool, status *elasticsearch.Elasticsearc } } -func testAccCheckDomainExists(ctx context.Context, n string, domain *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckDomainExists(ctx context.Context, n string, domain *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -1819,7 +1820,7 @@ func testAccCheckDomainExists(ctx context.Context, n string, domain *elasticsear return fmt.Errorf("No ES Domain ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) resp, err := tfelasticsearch.FindDomainByName(ctx, conn, rs.Primary.Attributes[names.AttrDomainName]) if err != nil { return fmt.Errorf("Error describing domain: %s", err.Error()) @@ -1836,10 +1837,10 @@ func testAccCheckDomainExists(ctx context.Context, n string, domain *elasticsear // the same name, if it's created within any reasonable time after deletion. // Also, domain ID is not unique and is simply the domain name so won't work // for this check either. -func testAccCheckDomainNotRecreated(domain1, domain2 *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc { +func testAccCheckDomainNotRecreated(domain1, domain2 *awstypes.ElasticsearchDomainStatus) resource.TestCheckFunc { return func(s *terraform.State) error { /* - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) ic, err := conn.DescribeElasticsearchDomainConfig(&elasticsearch.DescribeElasticsearchDomainConfigInput{ DomainName: domain1.DomainName, @@ -1877,7 +1878,7 @@ func testAccCheckDomainDestroy(ctx context.Context) resource.TestCheckFunc { continue } - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) _, err := tfelasticsearch.FindDomainByName(ctx, conn, rs.Primary.Attributes[names.AttrDomainName]) if tfresource.NotFound(err) { @@ -3045,7 +3046,7 @@ resource "aws_cloudwatch_log_resource_policy" "test" { func testAccDomainConfig_logPublishingOptions(rName, logType string) string { var auditLogsConfig string - if logType == elasticsearch.LogTypeAuditLogs { + if logType == string(awstypes.LogTypeAuditLogs) { auditLogsConfig = ` advanced_security_options { enabled = true From eab3945c15dbd6850452387535aa60c3cdae864d Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:56:13 +0100 Subject: [PATCH 05/24] r/elasticsearch_domain_policy: Migrate to AWS SDK v2 --- internal/service/elasticsearch/domain_policy.go | 14 ++++++-------- .../service/elasticsearch/domain_policy_test.go | 4 ++-- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index baa4a5d2d67b..b0bcba76736e 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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/structure" @@ -56,7 +57,7 @@ func ResourceDomainPolicy() *schema.Resource { func resourceDomainPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) @@ -83,7 +84,7 @@ func resourceDomainPolicyRead(ctx context.Context, d *schema.ResourceData, meta func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) domainName := d.Get(names.AttrDomainName).(string) policy, err := structure.NormalizeJsonString(d.Get("access_policies").(string)) @@ -92,16 +93,13 @@ func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendErrorf(diags, "policy (%s) is invalid JSON: %s", policy, err) } - _, err = tfresource.RetryWhenAWSErrMessageContains(ctx, propagationTimeout, + _, err = tfresource.RetryWhenIsAErrorMessageContains[*awstypes.ValidationException](ctx, propagationTimeout, func() (interface{}, error) { return conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(domainName), AccessPolicies: aws.String(policy), }) - }, - elasticsearch.ErrCodeValidationException, - "A change/update is in progress", - ) + }, "A change/update is in progress") if err != nil { return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain Policy (%s): %s", d.Id(), err) } @@ -117,7 +115,7 @@ func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, met func resourceDomainPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(d.Get(names.AttrDomainName).(string)), diff --git a/internal/service/elasticsearch/domain_policy_test.go b/internal/service/elasticsearch/domain_policy_test.go index e17d54e80d24..a4f0b8579aea 100644 --- a/internal/service/elasticsearch/domain_policy_test.go +++ b/internal/service/elasticsearch/domain_policy_test.go @@ -7,7 +7,7 @@ import ( "fmt" "testing" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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" @@ -18,7 +18,7 @@ import ( func TestAccElasticsearchDomainPolicy_basic(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus ri := sdkacctest.RandInt() policy := `{ "Version": "2012-10-17", From 4d5604bf1678826b0f99823bbd4b8a99b44891ec Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Sun, 23 Jun 2024 11:55:01 +0100 Subject: [PATCH 06/24] r/elasticsearch_domain_saml_options: Migrate to AWS SDK v2 --- .../elasticsearch/domain_saml_options.go | 19 ++++++++++--------- .../elasticsearch/domain_saml_options_test.go | 4 ++-- internal/service/elasticsearch/find.go | 7 ++++--- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 9b676fe5f9a7..c1c2eec5b04a 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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" @@ -119,7 +120,7 @@ func domainSamlOptionsDiffSupress(k, old, new string, d *schema.ResourceData) bo func resourceDomainSAMLOptionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) @@ -133,7 +134,7 @@ func resourceDomainSAMLOptionsRead(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Received Elasticsearch domain: %s", ds) + log.Printf("[DEBUG] Received Elasticsearch domain: %+v", ds) options := ds.AdvancedSecurityOptions.SAMLOptions @@ -146,13 +147,13 @@ func resourceDomainSAMLOptionsRead(ctx context.Context, d *schema.ResourceData, func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) domainName := d.Get(names.AttrDomainName).(string) - config := elasticsearch.AdvancedSecurityOptionsInput{} - config.SetSAMLOptions(expandESSAMLOptions(d.Get("saml_options").([]interface{}))) + config := awstypes.AdvancedSecurityOptionsInput{} + config.SAMLOptions = expandESSAMLOptions(d.Get("saml_options").([]interface{})) - log.Printf("[DEBUG] Updating Elasticsearch domain SAML Options %s", config) + log.Printf("[DEBUG] Updating Elasticsearch domain SAML Options %+v", config) _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(domainName), @@ -174,11 +175,11 @@ func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, m func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) domainName := d.Get(names.AttrDomainName).(string) - config := elasticsearch.AdvancedSecurityOptionsInput{} - config.SetSAMLOptions(nil) + config := awstypes.AdvancedSecurityOptionsInput{} + config.SAMLOptions = nil _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ DomainName: aws.String(domainName), diff --git a/internal/service/elasticsearch/domain_saml_options_test.go b/internal/service/elasticsearch/domain_saml_options_test.go index c73b5b731231..bec99ef51d38 100644 --- a/internal/service/elasticsearch/domain_saml_options_test.go +++ b/internal/service/elasticsearch/domain_saml_options_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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" @@ -21,7 +21,7 @@ import ( func TestAccElasticsearchDomainSAMLOptions_basic(t *testing.T) { ctx := acctest.Context(t) - var domain elasticsearch.ElasticsearchDomainStatus + var domain awstypes.ElasticsearchDomainStatus rName := sdkacctest.RandomWithPrefix("acc-test") rUserName := sdkacctest.RandomWithPrefix("es-master-user") diff --git a/internal/service/elasticsearch/find.go b/internal/service/elasticsearch/find.go index 1135c0fa22e9..e748bac217df 100644 --- a/internal/service/elasticsearch/find.go +++ b/internal/service/elasticsearch/find.go @@ -8,19 +8,20 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "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" ) -func FindDomainByName(ctx context.Context, conn *elasticsearch.ElasticsearchService, name string) (*elasticsearch.ElasticsearchDomainStatus, error) { +func FindDomainByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainStatus, error) { input := &elasticsearch.DescribeElasticsearchDomainInput{ DomainName: aws.String(name), } output, err := conn.DescribeElasticsearchDomain(ctx, input) - if tfawserr.ErrCodeEquals(err, elasticsearch.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, From a3c75d6875efe11b989e977db8870cd0e3056461 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Sun, 23 Jun 2024 20:58:58 +0100 Subject: [PATCH 07/24] elasticsearch: Migrate flex to AWS SDK v2 --- .../service/elasticsearch/domain_structure.go | 74 +++++++++---------- internal/service/elasticsearch/flex.go | 62 ++++++++-------- 2 files changed, 67 insertions(+), 69 deletions(-) diff --git a/internal/service/elasticsearch/domain_structure.go b/internal/service/elasticsearch/domain_structure.go index 686eed49a9e3..c0345a57338f 100644 --- a/internal/service/elasticsearch/domain_structure.go +++ b/internal/service/elasticsearch/domain_structure.go @@ -7,13 +7,13 @@ import ( "time" "github.com/aws/aws-sdk-go-v2/aws" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/names" ) -func expandAdvancedSecurityOptions(m []interface{}) *elasticsearch.AdvancedSecurityOptionsInput { - config := elasticsearch.AdvancedSecurityOptionsInput{} +func expandAdvancedSecurityOptions(m []interface{}) *awstypes.AdvancedSecurityOptionsInput { + config := awstypes.AdvancedSecurityOptionsInput{} group := m[0].(map[string]interface{}) if advancedSecurityEnabled, ok := group[names.AttrEnabled]; ok { @@ -26,7 +26,7 @@ func expandAdvancedSecurityOptions(m []interface{}) *elasticsearch.AdvancedSecur if v, ok := group["master_user_options"].([]interface{}); ok { if len(v) > 0 && v[0] != nil { - muo := elasticsearch.MasterUserOptions{} + muo := awstypes.MasterUserOptions{} masterUserOptions := v[0].(map[string]interface{}) if v, ok := masterUserOptions["master_user_arn"].(string); ok && v != "" { @@ -41,7 +41,7 @@ func expandAdvancedSecurityOptions(m []interface{}) *elasticsearch.AdvancedSecur muo.MasterUserPassword = aws.String(v) } - config.SetMasterUserOptions(&muo) + config.MasterUserOptions = &muo } } } @@ -50,12 +50,12 @@ func expandAdvancedSecurityOptions(m []interface{}) *elasticsearch.AdvancedSecur return &config } -func expandAutoTuneOptions(tfMap map[string]interface{}) *elasticsearch.AutoTuneOptions { +func expandAutoTuneOptions(tfMap map[string]interface{}) *awstypes.AutoTuneOptions { if tfMap == nil { return nil } - options := &elasticsearch.AutoTuneOptions{} + options := &awstypes.AutoTuneOptions{} autoTuneOptionsInput := expandAutoTuneOptionsInput(tfMap) @@ -69,14 +69,14 @@ func expandAutoTuneOptions(tfMap map[string]interface{}) *elasticsearch.AutoTune return options } -func expandAutoTuneOptionsInput(tfMap map[string]interface{}) *elasticsearch.AutoTuneOptionsInput { +func expandAutoTuneOptionsInput(tfMap map[string]interface{}) *awstypes.AutoTuneOptionsInput { if tfMap == nil { return nil } - options := &elasticsearch.AutoTuneOptionsInput{} + options := &awstypes.AutoTuneOptionsInput{} - options.DesiredState = aws.String(tfMap["desired_state"].(string)) + options.DesiredState = awstypes.AutoTuneDesiredState(tfMap["desired_state"].(string)) if v, ok := tfMap["maintenance_schedule"].(*schema.Set); ok && v.Len() > 0 { options.MaintenanceSchedules = expandAutoTuneMaintenanceSchedules(v.List()) @@ -85,13 +85,13 @@ func expandAutoTuneOptionsInput(tfMap map[string]interface{}) *elasticsearch.Aut return options } -func expandAutoTuneMaintenanceSchedules(tfList []interface{}) []*elasticsearch.AutoTuneMaintenanceSchedule { - var autoTuneMaintenanceSchedules []*elasticsearch.AutoTuneMaintenanceSchedule +func expandAutoTuneMaintenanceSchedules(tfList []interface{}) []awstypes.AutoTuneMaintenanceSchedule { + var autoTuneMaintenanceSchedules []awstypes.AutoTuneMaintenanceSchedule for _, tfMapRaw := range tfList { tfMap, _ := tfMapRaw.(map[string]interface{}) - autoTuneMaintenanceSchedule := &elasticsearch.AutoTuneMaintenanceSchedule{} + autoTuneMaintenanceSchedule := awstypes.AutoTuneMaintenanceSchedule{} startAt, _ := time.Parse(time.RFC3339, tfMap["start_at"].(string)) autoTuneMaintenanceSchedule.StartAt = aws.Time(startAt) @@ -108,25 +108,25 @@ func expandAutoTuneMaintenanceSchedules(tfList []interface{}) []*elasticsearch.A return autoTuneMaintenanceSchedules } -func expandAutoTuneMaintenanceScheduleDuration(tfMap map[string]interface{}) *elasticsearch.Duration { - autoTuneMaintenanceScheduleDuration := &elasticsearch.Duration{ +func expandAutoTuneMaintenanceScheduleDuration(tfMap map[string]interface{}) *awstypes.Duration { + autoTuneMaintenanceScheduleDuration := &awstypes.Duration{ Value: aws.Int64(int64(tfMap[names.AttrValue].(int))), - Unit: aws.String(tfMap[names.AttrUnit].(string)), + Unit: awstypes.TimeUnit(tfMap[names.AttrUnit].(string)), } return autoTuneMaintenanceScheduleDuration } -func expandESSAMLOptions(data []interface{}) *elasticsearch.SAMLOptionsInput { +func expandESSAMLOptions(data []interface{}) *awstypes.SAMLOptionsInput { if len(data) == 0 { return nil } if data[0] == nil { - return &elasticsearch.SAMLOptionsInput{} + return &awstypes.SAMLOptionsInput{} } - options := elasticsearch.SAMLOptionsInput{} + options := awstypes.SAMLOptionsInput{} group := data[0].(map[string]interface{}) if SAMLEnabled, ok := group[names.AttrEnabled]; ok { @@ -144,7 +144,7 @@ func expandESSAMLOptions(data []interface{}) *elasticsearch.SAMLOptionsInput { options.RolesKey = aws.String(v) } if v, ok := group["session_timeout_minutes"].(int); ok { - options.SessionTimeoutMinutes = aws.Int64(int64(v)) + options.SessionTimeoutMinutes = aws.Int32(int32(v)) } if v, ok := group["subject_key"].(string); ok { options.SubjectKey = aws.String(v) @@ -155,24 +155,24 @@ func expandESSAMLOptions(data []interface{}) *elasticsearch.SAMLOptionsInput { return &options } -func expandSAMLOptionsIdp(l []interface{}) *elasticsearch.SAMLIdp { +func expandSAMLOptionsIdp(l []interface{}) *awstypes.SAMLIdp { if len(l) == 0 { return nil } if l[0] == nil { - return &elasticsearch.SAMLIdp{} + return &awstypes.SAMLIdp{} } m := l[0].(map[string]interface{}) - return &elasticsearch.SAMLIdp{ + return &awstypes.SAMLIdp{ EntityId: aws.String(m["entity_id"].(string)), MetadataContent: aws.String(m["metadata_content"].(string)), } } -func flattenAdvancedSecurityOptions(advancedSecurityOptions *elasticsearch.AdvancedSecurityOptions) []map[string]interface{} { +func flattenAdvancedSecurityOptions(advancedSecurityOptions *awstypes.AdvancedSecurityOptions) []map[string]interface{} { if advancedSecurityOptions == nil { return []map[string]interface{}{} } @@ -186,14 +186,14 @@ func flattenAdvancedSecurityOptions(advancedSecurityOptions *elasticsearch.Advan return []map[string]interface{}{m} } -func flattenAutoTuneOptions(autoTuneOptions *elasticsearch.AutoTuneOptions) map[string]interface{} { +func flattenAutoTuneOptions(autoTuneOptions *awstypes.AutoTuneOptions) map[string]interface{} { if autoTuneOptions == nil { return nil } m := map[string]interface{}{} - m["desired_state"] = aws.ToString(autoTuneOptions.DesiredState) + m["desired_state"] = string(autoTuneOptions.DesiredState) if v := autoTuneOptions.MaintenanceSchedules; v != nil { m["maintenance_schedule"] = flattenAutoTuneMaintenanceSchedules(v) @@ -204,7 +204,7 @@ func flattenAutoTuneOptions(autoTuneOptions *elasticsearch.AutoTuneOptions) map[ return m } -func flattenAutoTuneMaintenanceSchedules(autoTuneMaintenanceSchedules []*elasticsearch.AutoTuneMaintenanceSchedule) []interface{} { +func flattenAutoTuneMaintenanceSchedules(autoTuneMaintenanceSchedules []awstypes.AutoTuneMaintenanceSchedule) []interface{} { if len(autoTuneMaintenanceSchedules) == 0 { return nil } @@ -214,7 +214,7 @@ func flattenAutoTuneMaintenanceSchedules(autoTuneMaintenanceSchedules []*elastic for _, autoTuneMaintenanceSchedule := range autoTuneMaintenanceSchedules { m := map[string]interface{}{} - m["start_at"] = aws.TimeValue(autoTuneMaintenanceSchedule.StartAt).Format(time.RFC3339) + m["start_at"] = aws.ToTime(autoTuneMaintenanceSchedule.StartAt).Format(time.RFC3339) m[names.AttrDuration] = []interface{}{flattenAutoTuneMaintenanceScheduleDuration(autoTuneMaintenanceSchedule.Duration)} @@ -226,16 +226,16 @@ func flattenAutoTuneMaintenanceSchedules(autoTuneMaintenanceSchedules []*elastic return tfList } -func flattenAutoTuneMaintenanceScheduleDuration(autoTuneMaintenanceScheduleDuration *elasticsearch.Duration) map[string]interface{} { +func flattenAutoTuneMaintenanceScheduleDuration(autoTuneMaintenanceScheduleDuration *awstypes.Duration) map[string]interface{} { m := map[string]interface{}{} m[names.AttrValue] = aws.ToInt64(autoTuneMaintenanceScheduleDuration.Value) - m[names.AttrUnit] = aws.ToString(autoTuneMaintenanceScheduleDuration.Unit) + m[names.AttrUnit] = string(autoTuneMaintenanceScheduleDuration.Unit) return m } -func flattenESSAMLOptions(d *schema.ResourceData, samlOptions *elasticsearch.SAMLOptionsOutput) []interface{} { +func flattenESSAMLOptions(d *schema.ResourceData, samlOptions *awstypes.SAMLOptionsOutput) []interface{} { if samlOptions == nil { return nil } @@ -246,7 +246,7 @@ func flattenESSAMLOptions(d *schema.ResourceData, samlOptions *elasticsearch.SAM } m["roles_key"] = aws.ToString(samlOptions.RolesKey) - m["session_timeout_minutes"] = aws.ToInt64(samlOptions.SessionTimeoutMinutes) + m["session_timeout_minutes"] = aws.ToInt32(samlOptions.SessionTimeoutMinutes) m["subject_key"] = aws.ToString(samlOptions.SubjectKey) // samlOptions.master_backend_role and samlOptions.master_user_name will be added to the @@ -259,7 +259,7 @@ func flattenESSAMLOptions(d *schema.ResourceData, samlOptions *elasticsearch.SAM return []interface{}{m} } -func flattenESSAMLIdpOptions(SAMLIdp *elasticsearch.SAMLIdp) []interface{} { +func flattenESSAMLIdpOptions(SAMLIdp *awstypes.SAMLIdp) []interface{} { if SAMLIdp == nil { return []interface{}{} } @@ -298,12 +298,12 @@ func getUserDBEnabled(d *schema.ResourceData) bool { return false } -func expandLogPublishingOptions(m *schema.Set) map[string]*elasticsearch.LogPublishingOption { - options := make(map[string]*elasticsearch.LogPublishingOption) +func expandLogPublishingOptions(m *schema.Set) map[string]awstypes.LogPublishingOption { + options := make(map[string]awstypes.LogPublishingOption) for _, vv := range m.List() { lo := vv.(map[string]interface{}) - options[lo["log_type"].(string)] = &elasticsearch.LogPublishingOption{ + options[lo["log_type"].(string)] = awstypes.LogPublishingOption{ CloudWatchLogsLogGroupArn: aws.String(lo[names.AttrCloudWatchLogGroupARN].(string)), Enabled: aws.Bool(lo[names.AttrEnabled].(bool)), } @@ -312,7 +312,7 @@ func expandLogPublishingOptions(m *schema.Set) map[string]*elasticsearch.LogPubl return options } -func flattenLogPublishingOptions(o map[string]*elasticsearch.LogPublishingOption) []map[string]interface{} { +func flattenLogPublishingOptions(o map[string]awstypes.LogPublishingOption) []map[string]interface{} { m := make([]map[string]interface{}, 0) for logType, val := range o { mm := map[string]interface{}{ diff --git a/internal/service/elasticsearch/flex.go b/internal/service/elasticsearch/flex.go index 483f6523c628..7d6a87b2fec2 100644 --- a/internal/service/elasticsearch/flex.go +++ b/internal/service/elasticsearch/flex.go @@ -5,14 +5,14 @@ package elasticsearch import ( "github.com/aws/aws-sdk-go-v2/aws" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/flex" "github.com/hashicorp/terraform-provider-aws/names" ) -func expandCognitoOptions(c []interface{}) *elasticsearch.CognitoOptions { - options := &elasticsearch.CognitoOptions{ +func expandCognitoOptions(c []interface{}) *awstypes.CognitoOptions { + options := &awstypes.CognitoOptions{ Enabled: aws.Bool(false), } if len(c) < 1 { @@ -40,13 +40,13 @@ func expandCognitoOptions(c []interface{}) *elasticsearch.CognitoOptions { return options } -func expandDomainEndpointOptions(l []interface{}) *elasticsearch.DomainEndpointOptions { +func expandDomainEndpointOptions(l []interface{}) *awstypes.DomainEndpointOptions { if len(l) == 0 || l[0] == nil { return nil } m := l[0].(map[string]interface{}) - domainEndpointOptions := &elasticsearch.DomainEndpointOptions{} + domainEndpointOptions := &awstypes.DomainEndpointOptions{} if v, ok := m["enforce_https"].(bool); ok { domainEndpointOptions.EnforceHTTPS = aws.Bool(v) @@ -73,15 +73,15 @@ func expandDomainEndpointOptions(l []interface{}) *elasticsearch.DomainEndpointO return domainEndpointOptions } -func expandEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions { - options := elasticsearch.EBSOptions{} +func expandEBSOptions(m map[string]interface{}) *awstypes.EBSOptions { + options := awstypes.EBSOptions{} if ebsEnabled, ok := m["ebs_enabled"]; ok { options.EBSEnabled = aws.Bool(ebsEnabled.(bool)) if ebsEnabled.(bool) { if v, ok := m[names.AttrVolumeSize]; ok && v.(int) > 0 { - options.VolumeSize = aws.Int64(int64(v.(int))) + options.VolumeSize = aws.Int32(int32(v.(int))) } var volumeType string if v, ok := m[names.AttrVolumeType]; ok && v.(string) != "" { @@ -89,10 +89,10 @@ func expandEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions { options.VolumeType = awstypes.VolumeType(volumeType) } if v, ok := m[names.AttrIOPS]; ok && v.(int) > 0 && EBSVolumeTypePermitsIopsInput(volumeType) { - options.Iops = aws.Int64(int64(v.(int))) + options.Iops = aws.Int32(int32(v.(int))) } if v, ok := m[names.AttrThroughput]; ok && v.(int) > 0 && EBSVolumeTypePermitsThroughputInput(volumeType) { - options.Throughput = aws.Int64(int64(v.(int))) + options.Throughput = aws.Int32(int32(v.(int))) } } } @@ -100,8 +100,8 @@ func expandEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions { return &options } -func expandEncryptAtRestOptions(m map[string]interface{}) *elasticsearch.EncryptionAtRestOptions { - options := elasticsearch.EncryptionAtRestOptions{} +func expandEncryptAtRestOptions(m map[string]interface{}) *awstypes.EncryptionAtRestOptions { + options := awstypes.EncryptionAtRestOptions{} if v, ok := m[names.AttrEnabled]; ok { options.Enabled = aws.Bool(v.(bool)) @@ -113,24 +113,24 @@ func expandEncryptAtRestOptions(m map[string]interface{}) *elasticsearch.Encrypt return &options } -func expandVPCOptions(m map[string]interface{}) *elasticsearch.VPCOptions { +func expandVPCOptions(m map[string]interface{}) *awstypes.VPCOptions { if m == nil { return nil } - options := elasticsearch.VPCOptions{} + options := awstypes.VPCOptions{} if v, ok := m[names.AttrSecurityGroupIDs].(*schema.Set); ok && v.Len() > 0 { - options.SecurityGroupIds = flex.ExpandStringSet(v) + options.SecurityGroupIds = flex.ExpandStringValueSet(v) } if v, ok := m[names.AttrSubnetIDs].(*schema.Set); ok && v.Len() > 0 { - options.SubnetIds = flex.ExpandStringSet(v) + options.SubnetIds = flex.ExpandStringValueSet(v) } return &options } -func flattenCognitoOptions(c *elasticsearch.CognitoOptions) []map[string]interface{} { +func flattenCognitoOptions(c *awstypes.CognitoOptions) []map[string]interface{} { m := map[string]interface{}{} m[names.AttrEnabled] = aws.ToBool(c.Enabled) @@ -144,7 +144,7 @@ func flattenCognitoOptions(c *elasticsearch.CognitoOptions) []map[string]interfa return []map[string]interface{}{m} } -func flattenDomainEndpointOptions(domainEndpointOptions *elasticsearch.DomainEndpointOptions) []interface{} { +func flattenDomainEndpointOptions(domainEndpointOptions *awstypes.DomainEndpointOptions) []interface{} { if domainEndpointOptions == nil { return nil } @@ -166,7 +166,7 @@ func flattenDomainEndpointOptions(domainEndpointOptions *elasticsearch.DomainEnd return []interface{}{m} } -func flattenEBSOptions(o *elasticsearch.EBSOptions) []map[string]interface{} { +func flattenEBSOptions(o *awstypes.EBSOptions) []map[string]interface{} { m := map[string]interface{}{} if o.EBSEnabled != nil { @@ -175,23 +175,21 @@ func flattenEBSOptions(o *elasticsearch.EBSOptions) []map[string]interface{} { if aws.ToBool(o.EBSEnabled) { if o.Iops != nil { - m[names.AttrIOPS] = aws.ToInt64(o.Iops) + m[names.AttrIOPS] = aws.ToInt32(o.Iops) } if o.Throughput != nil { - m[names.AttrThroughput] = aws.ToInt64(o.Throughput) + m[names.AttrThroughput] = aws.ToInt32(o.Throughput) } if o.VolumeSize != nil { - m[names.AttrVolumeSize] = aws.ToInt64(o.VolumeSize) - } - if o.VolumeType != nil { - m[names.AttrVolumeType] = string(o.VolumeType) + m[names.AttrVolumeSize] = aws.ToInt32(o.VolumeSize) } + m[names.AttrVolumeType] = string(o.VolumeType) } return []map[string]interface{}{m} } -func flattenEncryptAtRestOptions(o *elasticsearch.EncryptionAtRestOptions) []map[string]interface{} { +func flattenEncryptAtRestOptions(o *awstypes.EncryptionAtRestOptions) []map[string]interface{} { if o == nil { return []map[string]interface{}{} } @@ -208,19 +206,19 @@ func flattenEncryptAtRestOptions(o *elasticsearch.EncryptionAtRestOptions) []map return []map[string]interface{}{m} } -func flattenSnapshotOptions(snapshotOptions *elasticsearch.SnapshotOptions) []map[string]interface{} { +func flattenSnapshotOptions(snapshotOptions *awstypes.SnapshotOptions) []map[string]interface{} { if snapshotOptions == nil { return []map[string]interface{}{} } m := map[string]interface{}{ - "automated_snapshot_start_hour": int(aws.ToInt64(snapshotOptions.AutomatedSnapshotStartHour)), + "automated_snapshot_start_hour": int(aws.ToInt32(snapshotOptions.AutomatedSnapshotStartHour)), } return []map[string]interface{}{m} } -func flattenVPCDerivedInfo(o *elasticsearch.VPCDerivedInfo) map[string]interface{} { +func flattenVPCDerivedInfo(o *awstypes.VPCDerivedInfo) map[string]interface{} { if o == nil { return nil } @@ -228,13 +226,13 @@ func flattenVPCDerivedInfo(o *elasticsearch.VPCDerivedInfo) map[string]interface m := map[string]interface{}{} if o.AvailabilityZones != nil { - m[names.AttrAvailabilityZones] = flex.FlattenStringSet(o.AvailabilityZones) + m[names.AttrAvailabilityZones] = flex.FlattenStringValueSet(o.AvailabilityZones) } if o.SecurityGroupIds != nil { - m[names.AttrSecurityGroupIDs] = flex.FlattenStringSet(o.SecurityGroupIds) + m[names.AttrSecurityGroupIDs] = flex.FlattenStringValueSet(o.SecurityGroupIds) } if o.SubnetIds != nil { - m[names.AttrSubnetIDs] = flex.FlattenStringSet(o.SubnetIds) + m[names.AttrSubnetIDs] = flex.FlattenStringValueSet(o.SubnetIds) } if o.VPCId != nil { m[names.AttrVPCID] = aws.ToString(o.VPCId) From f8b4e0e10f3cb8b7de8e9c54b682830ee1e5b0c5 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Sun, 23 Jun 2024 21:18:17 +0100 Subject: [PATCH 08/24] status, sweep, wait: Migrate to AWS SDK v2 --- internal/service/elasticsearch/status.go | 15 ++++++++------- internal/service/elasticsearch/sweep.go | 11 +++-------- internal/service/elasticsearch/wait.go | 20 +++++++++++--------- 3 files changed, 22 insertions(+), 24 deletions(-) diff --git a/internal/service/elasticsearch/status.go b/internal/service/elasticsearch/status.go index 3dcc0f791ae6..b456f01b8ede 100644 --- a/internal/service/elasticsearch/status.go +++ b/internal/service/elasticsearch/status.go @@ -8,8 +8,9 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/errs" ) const ( @@ -19,7 +20,7 @@ const ( ConfigStatusExists = "Exists" ) -func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.ElasticsearchService, name string) retry.StateRefreshFunc { +func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { out, err := conn.GetUpgradeStatus(ctx, &elasticsearch.GetUpgradeStatusInput{ DomainName: aws.String(name), @@ -31,21 +32,21 @@ func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.ElasticsearchS // Elasticsearch upgrades consist of multiple steps: // https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-version-migration.html // Prevent false positive completion where the UpgradeStep is not the final UPGRADE step. - if aws.ToString(out.StepStatus) == elasticsearch.UpgradeStatusSucceeded && string(out.UpgradeStep) != elasticsearch.UpgradeStepUpgrade { - return out, elasticsearch.UpgradeStatusInProgress, nil + if out.StepStatus == awstypes.UpgradeStatusSucceeded && out.UpgradeStep != awstypes.UpgradeStepUpgrade { + return out, string(awstypes.UpgradeStatusInProgress), nil } - return out, aws.ToString(out.StepStatus), nil + return out, string(out.StepStatus), nil } } -func domainConfigStatus(ctx context.Context, conn *elasticsearch.ElasticsearchService, name string) retry.StateRefreshFunc { +func domainConfigStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { out, err := conn.DescribeElasticsearchDomainConfig(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ DomainName: aws.String(name), }) - if tfawserr.ErrCodeEquals(err, elasticsearch.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { // if first return value is nil, WaitForState treats as not found - here not found is treated differently return "not nil", ConfigStatusNotFound, nil } diff --git a/internal/service/elasticsearch/sweep.go b/internal/service/elasticsearch/sweep.go index 9338564dbe3a..03071f8110f5 100644 --- a/internal/service/elasticsearch/sweep.go +++ b/internal/service/elasticsearch/sweep.go @@ -12,7 +12,6 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/sweep" "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv1" "github.com/hashicorp/terraform-provider-aws/names" @@ -33,7 +32,7 @@ func sweepDomains(region string) error { return fmt.Errorf("error getting client: %w", err) } - conn := client.ElasticsearchConn(ctx) + conn := client.ElasticsearchClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var errs *multierror.Error @@ -60,14 +59,10 @@ func sweepDomains(region string) error { } for _, domainInfo := range output.DomainNames { - if domainInfo == nil { - continue - } - name := aws.ToString(domainInfo.DomainName) - if engineType := string(domainInfo.EngineType); engineType != awstypes.EngineTypeElasticsearch { - log.Printf("[INFO] Skipping Elasticsearch Domain %s: EngineType = %s", name, engineType) + if domainInfo.EngineType != awstypes.EngineTypeElasticsearch { + log.Printf("[INFO] Skipping Elasticsearch Domain %s: EngineType = %s", name, string(domainInfo.EngineType)) continue } diff --git a/internal/service/elasticsearch/wait.go b/internal/service/elasticsearch/wait.go index 0e18fa144360..00514517d748 100644 --- a/internal/service/elasticsearch/wait.go +++ b/internal/service/elasticsearch/wait.go @@ -10,7 +10,9 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" + awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -20,10 +22,10 @@ const ( ) // UpgradeSucceeded waits for an Upgrade to return Success -func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.ElasticsearchService, name string, timeout time.Duration) (*elasticsearch.GetUpgradeStatusOutput, error) { +func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Client, name string, timeout time.Duration) (*elasticsearch.GetUpgradeStatusOutput, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{elasticsearch.UpgradeStatusInProgress}, - Target: []string{elasticsearch.UpgradeStatusSucceeded}, + Pending: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusInProgress), + Target: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusSucceeded), Refresh: statusUpgradeStatus(ctx, conn, name), Timeout: timeout, MinTimeout: domainUpgradeSuccessMinTimeout, @@ -39,8 +41,8 @@ func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Elasticsearch return nil, err } -func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.ElasticsearchService, domainName string, timeout time.Duration) error { - var out *elasticsearch.ElasticsearchDomainStatus +func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { + var out *awstypes.ElasticsearchDomainStatus err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { var err error out, err = FindDomainByName(ctx, conn, domainName) @@ -68,8 +70,8 @@ func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.Elasticsearc return err } -func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.ElasticsearchService, domainName string, timeout time.Duration) error { - var out *elasticsearch.ElasticsearchDomainStatus +func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { + var out *awstypes.ElasticsearchDomainStatus err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { var err error out, err = FindDomainByName(ctx, conn, domainName) @@ -97,8 +99,8 @@ func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.ElasticsearchS return err } -func waitForDomainDelete(ctx context.Context, conn *elasticsearch.ElasticsearchService, domainName string, timeout time.Duration) error { - var out *elasticsearch.ElasticsearchDomainStatus +func waitForDomainDelete(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { + var out *awstypes.ElasticsearchDomainStatus err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { var err error out, err = FindDomainByName(ctx, conn, domainName) From 3bd7874ca7e7a762b4619da3d1fc1a1183b6e746 Mon Sep 17 00:00:00 2001 From: Matt Burgess <549318+mattburgess@users.noreply.github.com> Date: Sun, 23 Jun 2024 21:33:50 +0100 Subject: [PATCH 09/24] r/elasticsearch_vpc_endpoint: Migrate to AWS SDK v2 --- .../service/elasticsearch/vpc_endpoint.go | 38 +++++++++---------- .../elasticsearch/vpc_endpoint_test.go | 31 +++++++-------- 2 files changed, 30 insertions(+), 39 deletions(-) diff --git a/internal/service/elasticsearch/vpc_endpoint.go b/internal/service/elasticsearch/vpc_endpoint.go index 201965a747a2..1d00654e54a4 100644 --- a/internal/service/elasticsearch/vpc_endpoint.go +++ b/internal/service/elasticsearch/vpc_endpoint.go @@ -13,11 +13,11 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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/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/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -89,7 +89,7 @@ func ResourceVPCEndpoint() *schema.Resource { func resourceVPCEndpointCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) input := &elasticsearchservice.CreateVpcEndpointInput{ DomainArn: aws.String(d.Get("domain_arn").(string)), @@ -113,7 +113,7 @@ func resourceVPCEndpointCreate(ctx context.Context, d *schema.ResourceData, meta func resourceVPCEndpointRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) endpoint, err := findVPCEndpointByID(ctx, conn, d.Id()) @@ -142,7 +142,7 @@ func resourceVPCEndpointRead(ctx context.Context, d *schema.ResourceData, meta i func resourceVPCEndpointUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) input := &elasticsearchservice.UpdateVpcEndpointInput{ VpcOptions: expandVPCOptions(d.Get("vpc_options").([]interface{})[0].(map[string]interface{})), @@ -164,7 +164,7 @@ func resourceVPCEndpointUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceVPCEndpointDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ElasticsearchConn(ctx) + conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) log.Printf("[DEBUG] Deleting Elasticsearch VPC Endpoint: %s", d.Id()) _, err := conn.DeleteVpcEndpoint(ctx, &elasticsearchservice.DeleteVpcEndpointInput{ @@ -216,23 +216,19 @@ func (e *vpcEndpointNotFoundError) As(target any) bool { return true } -func vpcEndpointError(apiObject *awstypes.VpcEndpointError) error { - if apiObject == nil { - return nil - } - - errorCode := aws.ToString(apiObject.ErrorCode) +func vpcEndpointError(apiObject awstypes.VpcEndpointError) error { + errorCode := string(apiObject.ErrorCode) innerError := fmt.Errorf("%s: %s", errorCode, aws.ToString(apiObject.ErrorMessage)) err := fmt.Errorf("%s: %w", aws.ToString(apiObject.VpcEndpointId), innerError) - if errorCode == awstypes.VpcEndpointErrorCodeEndpointNotFound { + if errorCode == string(awstypes.VpcEndpointErrorCodeEndpointNotFound) { err = &vpcEndpointNotFoundError{apiError: err} } return err } -func vpcEndpointsError(apiObjects []*awstypes.VpcEndpointError) error { +func vpcEndpointsError(apiObjects []awstypes.VpcEndpointError) error { var errs []error for _, apiObject := range apiObjects { @@ -257,10 +253,10 @@ func findVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Client, inp return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func findVPCEndpoints(ctx context.Context, conn *elasticsearchservice.Client, input *elasticsearchservice.DescribeVpcEndpointsInput) ([]*awstypes.VpcEndpoint, error) { +func findVPCEndpoints(ctx context.Context, conn *elasticsearchservice.Client, input *elasticsearchservice.DescribeVpcEndpointsInput) ([]awstypes.VpcEndpoint, error) { output, err := conn.DescribeVpcEndpoints(ctx, input) if err != nil { @@ -290,14 +286,14 @@ func statusVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Client, i return nil, "", err } - return output, aws.ToString(output.Status), nil + return output, string(output.Status), nil } } func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{awstypes.VpcEndpointStatusCreating}, - Target: []string{awstypes.VpcEndpointStatusActive}, + Pending: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusCreating), + Target: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusActive), Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } @@ -309,8 +305,8 @@ func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.Clie func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{awstypes.VpcEndpointStatusUpdating}, - Target: []string{awstypes.VpcEndpointStatusActive}, + Pending: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusUpdating), + Target: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusActive), Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } @@ -322,7 +318,7 @@ func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.Clie func waitVPCEndpointDeleted(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{awstypes.VpcEndpointStatusDeleting}, + Pending: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusDeleting), Target: []string{}, Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, diff --git a/internal/service/elasticsearch/vpc_endpoint_test.go b/internal/service/elasticsearch/vpc_endpoint_test.go index 8eab1ae83c04..1b81d8aa3ffc 100644 --- a/internal/service/elasticsearch/vpc_endpoint_test.go +++ b/internal/service/elasticsearch/vpc_endpoint_test.go @@ -9,7 +9,6 @@ import ( "testing" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -26,28 +25,24 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { testCases := []struct { name string - apiObjects []*awstypes.VpcEndpointError + apiObjects []awstypes.VpcEndpointError notFound bool }{ { name: "nil input", }, - { - name: "slice of nil input", - apiObjects: []*awstypes.VpcEndpointError{nil, nil}, - }, { name: "single SERVER_ERROR", - apiObjects: []*awstypes.VpcEndpointError{{ - ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), + apiObjects: []awstypes.VpcEndpointError{{ + ErrorCode: awstypes.VpcEndpointErrorCodeServerError, ErrorMessage: aws.String("fail"), VpcEndpointId: aws.String("aos-12345678"), }}, }, { name: "single ENDPOINT_NOT_FOUND", - apiObjects: []*awstypes.VpcEndpointError{{ - ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeEndpointNotFound), + apiObjects: []awstypes.VpcEndpointError{{ + ErrorCode: awstypes.VpcEndpointErrorCodeEndpointNotFound, ErrorMessage: aws.String("Endpoint does not exist"), VpcEndpointId: aws.String("aos-12345678"), }}, @@ -55,14 +50,14 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { }, { name: "no ENDPOINT_NOT_FOUND in many", - apiObjects: []*awstypes.VpcEndpointError{ + apiObjects: []awstypes.VpcEndpointError{ { - ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), + ErrorCode: awstypes.VpcEndpointErrorCodeServerError, ErrorMessage: aws.String("fail"), VpcEndpointId: aws.String("aos-abcd0123"), }, { - ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), + ErrorCode: awstypes.VpcEndpointErrorCodeServerError, ErrorMessage: aws.String("crash"), VpcEndpointId: aws.String("aos-12345678"), }, @@ -70,14 +65,14 @@ func TestVPCEndpointErrorsNotFound(t *testing.T) { }, { name: "single ENDPOINT_NOT_FOUND in many", - apiObjects: []*awstypes.VpcEndpointError{ + apiObjects: []awstypes.VpcEndpointError{ { - ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeServerError), + ErrorCode: awstypes.VpcEndpointErrorCodeServerError, ErrorMessage: aws.String("fail"), VpcEndpointId: aws.String("aos-abcd0123"), }, { - ErrorCode: aws.String(awstypes.VpcEndpointErrorCodeEndpointNotFound), + ErrorCode: awstypes.VpcEndpointErrorCodeEndpointNotFound, ErrorMessage: aws.String("Endpoint does not exist"), VpcEndpointId: aws.String("aos-12345678"), }, @@ -217,7 +212,7 @@ func testAccCheckVPCEndpointExists(ctx context.Context, n string, v *awstypes.Vp return fmt.Errorf("Not found: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) output, err := tfelasticsearch.FindVPCEndpointByID(ctx, conn, rs.Primary.ID) @@ -238,7 +233,7 @@ func testAccCheckVPCEndpointDestroy(ctx context.Context) resource.TestCheckFunc continue } - conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) _, err := tfelasticsearch.FindVPCEndpointByID(ctx, conn, rs.Primary.ID) From 00d2b84ccf982c200ffe0a23daa75fdc2b71df5a Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 21 Aug 2024 16:51:32 -0400 Subject: [PATCH 10/24] r/aws_elasticsearch_domain_saml_options: Handle 'ResourceNotFoundException' on Delete. --- internal/service/elasticsearch/domain_saml_options.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index c1c2eec5b04a..ad55e092b847 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -15,6 +15,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/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" @@ -185,6 +186,11 @@ func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData DomainName: aws.String(domainName), AdvancedSecurityOptions: &config, }) + + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return diags + } + if err != nil { return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) } From 84f4f05f3a85ddf935302ff8f4ae50802e191ee0 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 21 Aug 2024 16:57:45 -0400 Subject: [PATCH 11/24] elasticsearch: Reduce visibility. --- internal/service/elasticsearch/domain.go | 10 +++++----- .../service/elasticsearch/domain_data_source.go | 6 +++--- internal/service/elasticsearch/domain_policy.go | 6 +++--- .../service/elasticsearch/domain_saml_options.go | 6 +++--- internal/service/elasticsearch/exports_test.go | 11 +++++++++-- internal/service/elasticsearch/find.go | 2 +- .../service/elasticsearch/service_package_gen.go | 14 +++++++++----- internal/service/elasticsearch/sweep.go | 4 ++-- internal/service/elasticsearch/vpc_endpoint.go | 4 ++-- internal/service/elasticsearch/wait.go | 14 +++++++------- 10 files changed, 44 insertions(+), 33 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index 7a20e62d85d6..8e377ecf9e96 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -34,7 +34,7 @@ import ( // @SDKResource("aws_elasticsearch_domain", name="Domain") // @Tags(identifierAttribute="id") -func ResourceDomain() *schema.Resource { +func resourceDomain() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceDomainCreate, ReadWithoutTimeout: resourceDomainRead, @@ -548,7 +548,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte // so w/out this check Create would act as upsert // and might cause duplicate domain to appear in state. name := d.Get(names.AttrDomainName).(string) - _, err := FindDomainByName(ctx, conn, name) + _, err := findDomainByName(ctx, conn, name) if err == nil { return sdkdiag.AppendErrorf(diags, "Elasticsearch Domain (%s) already exists", name) @@ -692,7 +692,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte d.SetId(aws.ToString(outputRaw.(*elasticsearch.CreateElasticsearchDomainOutput).DomainStatus.ARN)) - if err := WaitForDomainCreation(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { + if err := waitForDomainCreation(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) create: %s", d.Id(), err) } @@ -722,7 +722,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) name := d.Get(names.AttrDomainName).(string) - ds, err := FindDomainByName(ctx, conn, name) + ds, err := findDomainByName(ctx, conn, name) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Elasticsearch Domain (%s) not found, removing from state", d.Id()) @@ -1017,7 +1017,7 @@ func resourceDomainImport(ctx context.Context, d *schema.ResourceData, meta inte d.Set(names.AttrDomainName, d.Id()) - ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) + ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) if err != nil { return nil, err diff --git a/internal/service/elasticsearch/domain_data_source.go b/internal/service/elasticsearch/domain_data_source.go index 2f67efb96c73..ba4a9d5410cf 100644 --- a/internal/service/elasticsearch/domain_data_source.go +++ b/internal/service/elasticsearch/domain_data_source.go @@ -18,8 +18,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_elasticsearch_domain") -func DataSourceDomain() *schema.Resource { +// @SDKDataSource("aws_elasticsearch_domain", name="Domain") +func dataSourceDomain() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceDomainRead, @@ -350,7 +350,7 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) + ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) if err != nil { return sdkdiag.AppendErrorf(diags, "your query returned no results") } diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index b0bcba76736e..cf33dda58f6b 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -22,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_elasticsearch_domain_policy") -func ResourceDomainPolicy() *schema.Resource { +// @SDKResource("aws_elasticsearch_domain_policy", name="Domain Policy") +func resourceDomainPolicy() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceDomainPolicyUpsert, ReadWithoutTimeout: resourceDomainPolicyRead, @@ -59,7 +59,7 @@ func resourceDomainPolicyRead(ctx context.Context, d *schema.ResourceData, meta var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) + ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Elasticsearch Domain Policy (%s) not found, removing from state", d.Id()) diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index ad55e092b847..1c2fb256d7be 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -21,8 +21,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_elasticsearch_domain_saml_options") -func ResourceDomainSAMLOptions() *schema.Resource { +// @SDKResource("aws_elasticsearch_domain_saml_options", name="Domain SAML Options") +func resourceDomainSAMLOptions() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceDomainSAMLOptionsPut, ReadWithoutTimeout: resourceDomainSAMLOptionsRead, @@ -123,7 +123,7 @@ func resourceDomainSAMLOptionsRead(ctx context.Context, d *schema.ResourceData, var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - ds, err := FindDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) + ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Elasticsearch Domain SAML Options (%s) not found, removing from state", d.Id()) diff --git a/internal/service/elasticsearch/exports_test.go b/internal/service/elasticsearch/exports_test.go index 8e98793e4243..130d053d82e7 100644 --- a/internal/service/elasticsearch/exports_test.go +++ b/internal/service/elasticsearch/exports_test.go @@ -4,6 +4,13 @@ package elasticsearch // Exports for use in tests only. var ( - FindVPCEndpointByID = findVPCEndpointByID - VPCEndpointsError = vpcEndpointsError + ResourceDomain = resourceDomain + ResourceDomainPolicy = resourceDomainPolicy + ResourceDomainSAMLOptions = resourceDomainSAMLOptions + ResourceVPCEndpoint = resourceVPCEndpoint + + FindDomainByName = findDomainByName + FindVPCEndpointByID = findVPCEndpointByID + VPCEndpointsError = vpcEndpointsError + WaitForDomainCreation = waitForDomainCreation ) diff --git a/internal/service/elasticsearch/find.go b/internal/service/elasticsearch/find.go index e748bac217df..7038ee82da4a 100644 --- a/internal/service/elasticsearch/find.go +++ b/internal/service/elasticsearch/find.go @@ -14,7 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func FindDomainByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainStatus, error) { +func findDomainByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainStatus, error) { input := &elasticsearch.DescribeElasticsearchDomainInput{ DomainName: aws.String(name), } diff --git a/internal/service/elasticsearch/service_package_gen.go b/internal/service/elasticsearch/service_package_gen.go index c8416f5deb96..b10afe5c8ba7 100644 --- a/internal/service/elasticsearch/service_package_gen.go +++ b/internal/service/elasticsearch/service_package_gen.go @@ -25,8 +25,9 @@ func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.Servic func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePackageSDKDataSource { return []*types.ServicePackageSDKDataSource{ { - Factory: DataSourceDomain, + Factory: dataSourceDomain, TypeName: "aws_elasticsearch_domain", + Name: "Domain", }, } } @@ -34,7 +35,7 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePackageSDKResource { return []*types.ServicePackageSDKResource{ { - Factory: ResourceDomain, + Factory: resourceDomain, TypeName: "aws_elasticsearch_domain", Name: "Domain", Tags: &types.ServicePackageResourceTags{ @@ -42,16 +43,19 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceDomainPolicy, + Factory: resourceDomainPolicy, TypeName: "aws_elasticsearch_domain_policy", + Name: "Domain Policy", }, { - Factory: ResourceDomainSAMLOptions, + Factory: resourceDomainSAMLOptions, TypeName: "aws_elasticsearch_domain_saml_options", + Name: "Domain SAML Options", }, { - Factory: ResourceVPCEndpoint, + Factory: resourceVPCEndpoint, TypeName: "aws_elasticsearch_vpc_endpoint", + Name: "VPC Endpoint", }, } } diff --git a/internal/service/elasticsearch/sweep.go b/internal/service/elasticsearch/sweep.go index 03071f8110f5..1ca44031c635 100644 --- a/internal/service/elasticsearch/sweep.go +++ b/internal/service/elasticsearch/sweep.go @@ -70,7 +70,7 @@ func sweepDomains(region string) error { // e.g. Deleted and Processing are both true for days in the API // Filter out domains that are Deleted already. - output, err := FindDomainByName(ctx, conn, name) + output, err := findDomainByName(ctx, conn, name) if err != nil { sweeperErr := fmt.Errorf("error describing Elasticsearch Domain (%s): %w", name, err) log.Printf("[ERROR] %s", sweeperErr) @@ -83,7 +83,7 @@ func sweepDomains(region string) error { continue } - r := ResourceDomain() + r := resourceDomain() d := r.Data(nil) d.SetId(name) d.Set(names.AttrDomainName, name) diff --git a/internal/service/elasticsearch/vpc_endpoint.go b/internal/service/elasticsearch/vpc_endpoint.go index 1d00654e54a4..892d33cae507 100644 --- a/internal/service/elasticsearch/vpc_endpoint.go +++ b/internal/service/elasticsearch/vpc_endpoint.go @@ -25,8 +25,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_elasticsearch_vpc_endpoint") -func ResourceVPCEndpoint() *schema.Resource { +// @SDKResource("aws_elasticsearch_vpc_endpoint", name="VPC Endpoint") +func resourceVPCEndpoint() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointCreate, ReadWithoutTimeout: resourceVPCEndpointRead, diff --git a/internal/service/elasticsearch/wait.go b/internal/service/elasticsearch/wait.go index 00514517d748..f78af6e0c7a5 100644 --- a/internal/service/elasticsearch/wait.go +++ b/internal/service/elasticsearch/wait.go @@ -41,11 +41,11 @@ func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Client, name return nil, err } -func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { +func waitForDomainCreation(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { var out *awstypes.ElasticsearchDomainStatus err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { var err error - out, err = FindDomainByName(ctx, conn, domainName) + out, err = findDomainByName(ctx, conn, domainName) if err != nil { return retry.NonRetryableError(err) } @@ -58,7 +58,7 @@ func WaitForDomainCreation(ctx context.Context, conn *elasticsearch.Client, doma fmt.Errorf("%q: Timeout while waiting for the domain to be created", domainName)) }) if tfresource.TimedOut(err) { - out, err = FindDomainByName(ctx, conn, domainName) + out, err = findDomainByName(ctx, conn, domainName) if err != nil { return fmt.Errorf("describing Elasticsearch domain: %w", err) } @@ -74,7 +74,7 @@ func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.Client, domain var out *awstypes.ElasticsearchDomainStatus err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { var err error - out, err = FindDomainByName(ctx, conn, domainName) + out, err = findDomainByName(ctx, conn, domainName) if err != nil { return retry.NonRetryableError(err) } @@ -87,7 +87,7 @@ func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.Client, domain fmt.Errorf("%q: Timeout while waiting for changes to be processed", domainName)) }) if tfresource.TimedOut(err) { - out, err = FindDomainByName(ctx, conn, domainName) + out, err = findDomainByName(ctx, conn, domainName) if err != nil { return fmt.Errorf("describing Elasticsearch domain: %w", err) } @@ -103,7 +103,7 @@ func waitForDomainDelete(ctx context.Context, conn *elasticsearch.Client, domain var out *awstypes.ElasticsearchDomainStatus err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { var err error - out, err = FindDomainByName(ctx, conn, domainName) + out, err = findDomainByName(ctx, conn, domainName) if err != nil { if tfresource.NotFound(err) { @@ -119,7 +119,7 @@ func waitForDomainDelete(ctx context.Context, conn *elasticsearch.Client, domain return retry.RetryableError(fmt.Errorf("timeout while waiting for the domain %q to be deleted", domainName)) }) if tfresource.TimedOut(err) { - out, err = FindDomainByName(ctx, conn, domainName) + out, err = findDomainByName(ctx, conn, domainName) if err != nil { if tfresource.NotFound(err) { return nil From 091d86622b6b2a1f8abc7c549ad0c25361d5d027 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 07:56:56 -0400 Subject: [PATCH 12/24] Fix semgrep 'ci.typed-enum-conversion'. --- internal/service/elasticsearch/domain.go | 193 +++++++++--------- .../elasticsearch/domain_data_source.go | 2 +- internal/service/elasticsearch/domain_test.go | 52 ----- internal/service/elasticsearch/flex.go | 4 +- 4 files changed, 96 insertions(+), 155 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index 8e377ecf9e96..badb9344c2f1 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -7,6 +7,7 @@ import ( "context" "fmt" "log" + "slices" "strings" "time" @@ -26,6 +27,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" "github.com/hashicorp/terraform-provider-aws/internal/semver" + 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" @@ -274,13 +276,9 @@ func resourceDomain() *schema.Resource { Optional: true, }, "warm_type": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(awstypes.ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch), - string(awstypes.ESWarmPartitionInstanceTypeUltrawarm1LargeElasticsearch), - "ultrawarm1.xlarge.elasticsearch", - }, false), + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice(warmPartitionInstanceType_Values(), false), }, "zone_awareness_config": { Type: schema.TypeList, @@ -613,7 +611,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "At least one field is expected inside cluster_config") } m := config[0].(map[string]interface{}) - input.ElasticsearchClusterConfig = expandClusterConfig(m) + input.ElasticsearchClusterConfig = expandElasticsearchClusterConfig(m) } } @@ -771,7 +769,7 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf return sdkdiag.AppendErrorf(diags, "setting encrypt_at_rest: %s", err) } - if err := d.Set("cluster_config", flattenClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { + if err := d.Set("cluster_config", flattenElasticsearchClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { return sdkdiag.AppendErrorf(diags, "setting cluster_config: %s", err) } @@ -891,7 +889,7 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte if len(config) == 1 { m := config[0].(map[string]interface{}) - input.ElasticsearchClusterConfig = expandClusterConfig(m) + input.ElasticsearchClusterConfig = expandElasticsearchClusterConfig(m) // Work around "ValidationException: Your domain's Elasticsearch version does not support cold storage options. Upgrade to Elasticsearch 7.9 or later.". if semver.LessThan(d.Get("elasticsearch_version").(string), "7.9") { @@ -1028,6 +1026,10 @@ func resourceDomainImport(ctx context.Context, d *schema.ResourceData, meta inte return []*schema.ResourceData{d}, nil } +func warmPartitionInstanceType_Values() []string { + return tfslices.AppendUnique(enum.Values[awstypes.ESWarmPartitionInstanceType](), "ultrawarm1.xlarge.elasticsearch") +} + // inPlaceEncryptionEnableVersion returns true if, based on version, encryption // can be enabled in place (without ForceNew) func inPlaceEncryptionEnableVersion(version string) bool { @@ -1063,83 +1065,85 @@ func isCustomEndpointDisabled(k, old, new string, d *schema.ResourceData) bool { return false } -func expandNodeToNodeEncryptionOptions(s map[string]interface{}) *awstypes.NodeToNodeEncryptionOptions { - options := awstypes.NodeToNodeEncryptionOptions{} +func expandNodeToNodeEncryptionOptions(tfMap map[string]interface{}) *awstypes.NodeToNodeEncryptionOptions { + apiObject := &awstypes.NodeToNodeEncryptionOptions{} - if v, ok := s[names.AttrEnabled]; ok { - options.Enabled = aws.Bool(v.(bool)) + if v, ok := tfMap[names.AttrEnabled]; ok { + apiObject.Enabled = aws.Bool(v.(bool)) } - return &options + + return apiObject } -func flattenNodeToNodeEncryptionOptions(o *awstypes.NodeToNodeEncryptionOptions) []map[string]interface{} { - if o == nil { - return []map[string]interface{}{} +func flattenNodeToNodeEncryptionOptions(apiObject *awstypes.NodeToNodeEncryptionOptions) []interface{} { + if apiObject == nil { + return []interface{}{} } - m := map[string]interface{}{} - if o.Enabled != nil { - m[names.AttrEnabled] = aws.ToBool(o.Enabled) + tfMap := map[string]interface{}{} + + if apiObject.Enabled != nil { + tfMap[names.AttrEnabled] = aws.ToBool(apiObject.Enabled) } - return []map[string]interface{}{m} + return []interface{}{tfMap} } -func expandClusterConfig(m map[string]interface{}) *awstypes.ElasticsearchClusterConfig { - config := awstypes.ElasticsearchClusterConfig{} +func expandElasticsearchClusterConfig(tfMap map[string]interface{}) *awstypes.ElasticsearchClusterConfig { // nosemgrep:ci.elasticsearch-in-func-name + apiObject := &awstypes.ElasticsearchClusterConfig{} - if v, ok := m["cold_storage_options"].([]interface{}); ok && len(v) > 0 { - config.ColdStorageOptions = expandColdStorageOptions(v[0].(map[string]interface{})) + if v, ok := tfMap["cold_storage_options"].([]interface{}); ok && len(v) > 0 { + apiObject.ColdStorageOptions = expandColdStorageOptions(v[0].(map[string]interface{})) } - if v, ok := m["dedicated_master_enabled"]; ok { + if v, ok := tfMap["dedicated_master_enabled"]; ok { isEnabled := v.(bool) - config.DedicatedMasterEnabled = aws.Bool(isEnabled) + apiObject.DedicatedMasterEnabled = aws.Bool(isEnabled) if isEnabled { - if v, ok := m["dedicated_master_count"]; ok && v.(int) > 0 { - config.DedicatedMasterCount = aws.Int32(int32(v.(int))) + if v, ok := tfMap["dedicated_master_count"]; ok && v.(int) > 0 { + apiObject.DedicatedMasterCount = aws.Int32(int32(v.(int))) } - if v, ok := m["dedicated_master_type"]; ok && v.(string) != "" { - config.DedicatedMasterType = awstypes.ESPartitionInstanceType(v.(string)) + if v, ok := tfMap["dedicated_master_type"]; ok && v.(string) != "" { + apiObject.DedicatedMasterType = awstypes.ESPartitionInstanceType(v.(string)) } } } - if v, ok := m[names.AttrInstanceCount]; ok { - config.InstanceCount = aws.Int32(int32(v.(int))) + if v, ok := tfMap[names.AttrInstanceCount]; ok { + apiObject.InstanceCount = aws.Int32(int32(v.(int))) } - if v, ok := m[names.AttrInstanceType]; ok { - config.InstanceType = awstypes.ESPartitionInstanceType(v.(string)) + if v, ok := tfMap[names.AttrInstanceType]; ok { + apiObject.InstanceType = awstypes.ESPartitionInstanceType(v.(string)) } - if v, ok := m["zone_awareness_enabled"]; ok { + if v, ok := tfMap["zone_awareness_enabled"]; ok { isEnabled := v.(bool) - config.ZoneAwarenessEnabled = aws.Bool(isEnabled) + apiObject.ZoneAwarenessEnabled = aws.Bool(isEnabled) if isEnabled { - if v, ok := m["zone_awareness_config"]; ok { - config.ZoneAwarenessConfig = expandZoneAwarenessConfig(v.([]interface{})) + if v, ok := tfMap["zone_awareness_config"]; ok { + apiObject.ZoneAwarenessConfig = expandZoneAwarenessConfig(v.([]interface{})) } } } - if v, ok := m["warm_enabled"]; ok { + if v, ok := tfMap["warm_enabled"]; ok { isEnabled := v.(bool) - config.WarmEnabled = aws.Bool(isEnabled) + apiObject.WarmEnabled = aws.Bool(isEnabled) if isEnabled { - if v, ok := m["warm_count"]; ok { - config.WarmCount = aws.Int32(int32(v.(int))) + if v, ok := tfMap["warm_count"]; ok { + apiObject.WarmCount = aws.Int32(int32(v.(int))) } - if v, ok := m["warm_type"]; ok { - config.WarmType = awstypes.ESWarmPartitionInstanceType(v.(string)) + if v, ok := tfMap["warm_type"]; ok { + apiObject.WarmType = awstypes.ESWarmPartitionInstanceType(v.(string)) } } } - return &config + return apiObject } func expandColdStorageOptions(tfMap map[string]interface{}) *awstypes.ColdStorageOptions { @@ -1156,75 +1160,74 @@ func expandColdStorageOptions(tfMap map[string]interface{}) *awstypes.ColdStorag return apiObject } -func expandZoneAwarenessConfig(l []interface{}) *awstypes.ZoneAwarenessConfig { - if len(l) == 0 || l[0] == nil { +func expandZoneAwarenessConfig(tfList []interface{}) *awstypes.ZoneAwarenessConfig { + if len(tfList) == 0 || tfList[0] == nil { return nil } - m := l[0].(map[string]interface{}) - - zoneAwarenessConfig := &awstypes.ZoneAwarenessConfig{} + tfMap := tfList[0].(map[string]interface{}) + apiObject := &awstypes.ZoneAwarenessConfig{} - if v, ok := m["availability_zone_count"]; ok && v.(int) > 0 { - zoneAwarenessConfig.AvailabilityZoneCount = aws.Int32(int32(v.(int))) + if v, ok := tfMap["availability_zone_count"]; ok && v.(int) > 0 { + apiObject.AvailabilityZoneCount = aws.Int32(int32(v.(int))) } - return zoneAwarenessConfig + return apiObject } -func flattenClusterConfig(c *awstypes.ElasticsearchClusterConfig) []map[string]interface{} { - m := map[string]interface{}{ - "zone_awareness_config": flattenZoneAwarenessConfig(c.ZoneAwarenessConfig), - "zone_awareness_enabled": aws.ToBool(c.ZoneAwarenessEnabled), +func flattenElasticsearchClusterConfig(apiObject *awstypes.ElasticsearchClusterConfig) []interface{} { // nosemgrep:ci.elasticsearch-in-func-name + tfMap := map[string]interface{}{ + "zone_awareness_config": flattenZoneAwarenessConfig(apiObject.ZoneAwarenessConfig), + "zone_awareness_enabled": aws.ToBool(apiObject.ZoneAwarenessEnabled), } - if c.ColdStorageOptions != nil { - m["cold_storage_options"] = flattenColdStorageOptions(c.ColdStorageOptions) + if apiObject.ColdStorageOptions != nil { + tfMap["cold_storage_options"] = flattenColdStorageOptions(apiObject.ColdStorageOptions) } - if c.DedicatedMasterCount != nil { - m["dedicated_master_count"] = aws.ToInt32(c.DedicatedMasterCount) + if apiObject.DedicatedMasterCount != nil { + tfMap["dedicated_master_count"] = aws.ToInt32(apiObject.DedicatedMasterCount) } - if c.DedicatedMasterEnabled != nil { - m["dedicated_master_enabled"] = aws.ToBool(c.DedicatedMasterEnabled) + if apiObject.DedicatedMasterEnabled != nil { + tfMap["dedicated_master_enabled"] = aws.ToBool(apiObject.DedicatedMasterEnabled) } - m["dedicated_master_type"] = string(c.DedicatedMasterType) - if c.InstanceCount != nil { - m[names.AttrInstanceCount] = aws.ToInt32(c.InstanceCount) + tfMap["dedicated_master_type"] = apiObject.DedicatedMasterType + if apiObject.InstanceCount != nil { + tfMap[names.AttrInstanceCount] = aws.ToInt32(apiObject.InstanceCount) } - m[names.AttrInstanceType] = string(c.InstanceType) - if c.WarmEnabled != nil { - m["warm_enabled"] = aws.ToBool(c.WarmEnabled) + tfMap[names.AttrInstanceType] = apiObject.InstanceType + if apiObject.WarmEnabled != nil { + tfMap["warm_enabled"] = aws.ToBool(apiObject.WarmEnabled) } - if c.WarmCount != nil { - m["warm_count"] = aws.ToInt32(c.WarmCount) + if apiObject.WarmCount != nil { + tfMap["warm_count"] = aws.ToInt32(apiObject.WarmCount) } - m["warm_type"] = string(c.WarmType) + tfMap["warm_type"] = string(apiObject.WarmType) - return []map[string]interface{}{m} + return []interface{}{tfMap} } -func flattenColdStorageOptions(coldStorageOptions *awstypes.ColdStorageOptions) []interface{} { - if coldStorageOptions == nil { +func flattenColdStorageOptions(apiObject *awstypes.ColdStorageOptions) []interface{} { + if apiObject == nil { return []interface{}{} } - m := map[string]interface{}{ - names.AttrEnabled: aws.ToBool(coldStorageOptions.Enabled), + tfMap := map[string]interface{}{ + names.AttrEnabled: aws.ToBool(apiObject.Enabled), } - return []interface{}{m} + return []interface{}{tfMap} } -func flattenZoneAwarenessConfig(zoneAwarenessConfig *awstypes.ZoneAwarenessConfig) []interface{} { - if zoneAwarenessConfig == nil { +func flattenZoneAwarenessConfig(apiObject *awstypes.ZoneAwarenessConfig) []interface{} { + if apiObject == nil { return []interface{}{} } - m := map[string]interface{}{ - "availability_zone_count": aws.ToInt32(zoneAwarenessConfig.AvailabilityZoneCount), + tfMap := map[string]interface{}{ + "availability_zone_count": aws.ToInt32(apiObject.AvailabilityZoneCount), } - return []interface{}{m} + return []interface{}{tfMap} } // advancedOptionsIgnoreDefault checks for defaults in the n map and, if @@ -1247,30 +1250,20 @@ func advancedOptionsIgnoreDefault(o map[string]interface{}, n map[string]interfa return n } -// EBSVolumeTypePermitsIopsInput returns true if the volume type supports the Iops input +// ebsVolumeTypePermitsIopsInput returns true if the volume type supports the Iops input // // This check prevents a ValidationException when updating EBS volume types from a value // that supports IOPS (ex. gp3) to one that doesn't (ex. gp2). -func EBSVolumeTypePermitsIopsInput(volumeType string) bool { +func ebsVolumeTypePermitsIopsInput(volumeType string) bool { permittedTypes := enum.Slice(awstypes.VolumeTypeGp3, awstypes.VolumeTypeIo1) - for _, t := range permittedTypes { - if volumeType == t { - return true - } - } - return false + return slices.Contains(permittedTypes, volumeType) } // EBSVolumeTypePermitsIopsInput returns true if the volume type supports the Throughput input // // This check prevents a ValidationException when updating EBS volume types from a value // that supports Throughput (ex. gp3) to one that doesn't (ex. gp2). -func EBSVolumeTypePermitsThroughputInput(volumeType string) bool { +func ebsVolumeTypePermitsThroughputInput(volumeType string) bool { permittedTypes := enum.Slice(awstypes.VolumeTypeGp3) - for _, t := range permittedTypes { - if volumeType == t { - return true - } - } - return false + return slices.Contains(permittedTypes, volumeType) } diff --git a/internal/service/elasticsearch/domain_data_source.go b/internal/service/elasticsearch/domain_data_source.go index ba4a9d5410cf..b410fe7be9ba 100644 --- a/internal/service/elasticsearch/domain_data_source.go +++ b/internal/service/elasticsearch/domain_data_source.go @@ -411,7 +411,7 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "setting node_to_node_encryption: %s", err) } - if err := d.Set("cluster_config", flattenClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { + if err := d.Set("cluster_config", flattenElasticsearchClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { return sdkdiag.AppendErrorf(diags, "setting cluster_config: %s", err) } diff --git a/internal/service/elasticsearch/domain_test.go b/internal/service/elasticsearch/domain_test.go index 66f27dc55b13..76460a6acf50 100644 --- a/internal/service/elasticsearch/domain_test.go +++ b/internal/service/elasticsearch/domain_test.go @@ -23,58 +23,6 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func TestEBSVolumeTypePermitsIopsInput(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - volumeType string - want bool - }{ - {"empty", "", false}, - {"gp2", string(awstypes.VolumeTypeGp2), false}, - {"gp3", string(awstypes.VolumeTypeGp3), true}, - {"io1", string(awstypes.VolumeTypeIo1), true}, - {"standard", string(awstypes.VolumeTypeStandard), false}, - } - for _, testCase := range testCases { - testCase := testCase - t.Run(testCase.name, func(t *testing.T) { - t.Parallel() - - if got := tfelasticsearch.EBSVolumeTypePermitsIopsInput(testCase.volumeType); got != testCase.want { - t.Errorf("EBSVolumeTypePermitsIopsInput() = %v, want %v", got, testCase.want) - } - }) - } -} - -func TestEBSVolumeTypePermitsThroughputInput(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - volumeType string - want bool - }{ - {"empty", "", false}, - {"gp2", string(awstypes.VolumeTypeGp2), false}, - {"gp3", string(awstypes.VolumeTypeGp3), true}, - {"io1", string(awstypes.VolumeTypeIo1), false}, - {"standard", string(awstypes.VolumeTypeStandard), false}, - } - for _, testCase := range testCases { - testCase := testCase - t.Run(testCase.name, func(t *testing.T) { - t.Parallel() - - if got := tfelasticsearch.EBSVolumeTypePermitsThroughputInput(testCase.volumeType); got != testCase.want { - t.Errorf("EBSVolumeTypePermitsThroughputInput() = %v, want %v", got, testCase.want) - } - }) - } -} - func TestAccElasticsearchDomain_basic(t *testing.T) { ctx := acctest.Context(t) if testing.Short() { diff --git a/internal/service/elasticsearch/flex.go b/internal/service/elasticsearch/flex.go index 7d6a87b2fec2..af918d0f40a3 100644 --- a/internal/service/elasticsearch/flex.go +++ b/internal/service/elasticsearch/flex.go @@ -88,10 +88,10 @@ func expandEBSOptions(m map[string]interface{}) *awstypes.EBSOptions { volumeType = v.(string) options.VolumeType = awstypes.VolumeType(volumeType) } - if v, ok := m[names.AttrIOPS]; ok && v.(int) > 0 && EBSVolumeTypePermitsIopsInput(volumeType) { + if v, ok := m[names.AttrIOPS]; ok && v.(int) > 0 && ebsVolumeTypePermitsIopsInput(volumeType) { options.Iops = aws.Int32(int32(v.(int))) } - if v, ok := m[names.AttrThroughput]; ok && v.(int) > 0 && EBSVolumeTypePermitsThroughputInput(volumeType) { + if v, ok := m[names.AttrThroughput]; ok && v.(int) > 0 && ebsVolumeTypePermitsThroughputInput(volumeType) { options.Throughput = aws.Int32(int32(v.(int))) } } From 9deb2bfda8f01e143d5fb0f1bb6a8a313bb3b6bf Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 10:37:46 -0400 Subject: [PATCH 13/24] r/aws_elasticsearch_domain_policy: Tidy up. --- .../service/elasticsearch/domain_policy.go | 77 ++++++++++--------- 1 file changed, 41 insertions(+), 36 deletions(-) diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index cf33dda58f6b..63f6c90e4c4c 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -16,6 +16,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -55,80 +56,84 @@ func resourceDomainPolicy() *schema.Resource { } } -func resourceDomainPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) - - if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Elasticsearch Domain Policy (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags - } - + domainName := d.Get(names.AttrDomainName).(string) + policy, err := structure.NormalizeJsonString(d.Get("access_policies").(string)) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain Policy (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) + } + input := &elasticsearch.UpdateElasticsearchDomainConfigInput{ + AccessPolicies: aws.String(policy), + DomainName: aws.String(domainName), } - policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.ToString(ds.AccessPolicies)) + _, err = tfresource.RetryWhenIsAErrorMessageContains[*awstypes.ValidationException](ctx, propagationTimeout, + func() (interface{}, error) { + return conn.UpdateElasticsearchDomainConfig(ctx, input) + }, "A change/update is in progress") if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain Policy (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain Policy (%s): %s", d.Id(), err) } - d.Set("access_policies", policies) + d.SetId("esd-policy-" + domainName) - return diags + if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + } + + return append(diags, resourceDomainPolicyRead(ctx, d, meta)...) } -func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceDomainPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - domainName := d.Get(names.AttrDomainName).(string) - policy, err := structure.NormalizeJsonString(d.Get("access_policies").(string)) + ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) - if err != nil { - return sdkdiag.AppendErrorf(diags, "policy (%s) is invalid JSON: %s", policy, err) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Elasticsearch Domain Policy (%s) not found, removing from state", d.Id()) + d.SetId("") + return diags } - _, err = tfresource.RetryWhenIsAErrorMessageContains[*awstypes.ValidationException](ctx, propagationTimeout, - func() (interface{}, error) { - return conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ - DomainName: aws.String(domainName), - AccessPolicies: aws.String(policy), - }) - }, "A change/update is in progress") if err != nil { - return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain Policy (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain Policy (%s): %s", d.Id(), err) } - d.SetId("esd-policy-" + domainName) - - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain Policy (%s): waiting for completion: %s", d.Id(), err) + policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.ToString(ds.AccessPolicies)) + if err != nil { + return sdkdiag.AppendFromErr(diags, err) } - return append(diags, resourceDomainPolicyRead(ctx, d, meta)...) + d.Set("access_policies", policies) + + return diags } func resourceDomainPolicyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) + log.Printf("[DEBUG] Deleting Elasticsearch Domain Policy: %s", d.Id()) _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ - DomainName: aws.String(d.Get(names.AttrDomainName).(string)), AccessPolicies: aws.String(""), + DomainName: aws.String(d.Get(names.AttrDomainName).(string)), }) + + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return diags + } + if err != nil { return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain Policy (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Waiting for Elasticsearch domain policy %q to be deleted", d.Get(names.AttrDomainName).(string)) - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain Policy (%s): waiting for completion: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) } return diags From 351551b3381503f0e94df80e8a88e8474a6fa832 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 10:43:19 -0400 Subject: [PATCH 14/24] r/aws_elasticsearch_domain_policy: Change 'domain_name' to ForceNew. --- .changelog/38086.txt | 3 +++ internal/service/elasticsearch/domain_policy.go | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 .changelog/38086.txt diff --git a/.changelog/38086.txt b/.changelog/38086.txt new file mode 100644 index 000000000000..9a14305499e4 --- /dev/null +++ b/.changelog/38086.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_elasticsearch_domain_policy: Change `domain_name` to [ForceNew](https://developer.hashicorp.com/terraform/plugin/sdkv2/schemas/schema-behaviors#forcenew) +``` \ No newline at end of file diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index 63f6c90e4c4c..350bdfce4344 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -51,6 +51,7 @@ func resourceDomainPolicy() *schema.Resource { names.AttrDomainName: { Type: schema.TypeString, Required: true, + ForceNew: true, }, }, } @@ -79,7 +80,9 @@ func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain Policy (%s): %s", d.Id(), err) } - d.SetId("esd-policy-" + domainName) + if d.IsNewResource() { + d.SetId("esd-policy-" + domainName) + } if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) From 58914e6ce4d5fbd46fbce0ef531d5fd00352b6d0 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 11:03:21 -0400 Subject: [PATCH 15/24] r/aws_elasticsearch_domain_saml_options: Tidy up. --- .../elasticsearch/domain_saml_options.go | 109 +++++++++--------- .../elasticsearch/domain_saml_options_test.go | 60 +++------- .../service/elasticsearch/domain_structure.go | 34 +++--- .../service/elasticsearch/exports_test.go | 9 +- internal/service/elasticsearch/find.go | 4 + 5 files changed, 102 insertions(+), 114 deletions(-) diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 1c2fb256d7be..9b35d94b28f9 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -30,10 +30,7 @@ func resourceDomainSAMLOptions() *schema.Resource { DeleteWithoutTimeout: resourceDomainSAMLOptionsDelete, Importer: &schema.ResourceImporter{ - StateContext: func(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - d.Set(names.AttrDomainName, d.Id()) - return []*schema.ResourceData{d}, nil - }, + StateContext: schema.ImportStatePassthroughContext, }, Timeouts: &schema.ResourceTimeout{ @@ -110,81 +107,68 @@ func resourceDomainSAMLOptions() *schema.Resource { }, } } -func domainSamlOptionsDiffSupress(k, old, new string, d *schema.ResourceData) bool { - if v, ok := d.Get("saml_options").([]interface{}); ok && len(v) > 0 { - if enabled, ok := v[0].(map[string]interface{})[names.AttrEnabled].(bool); ok && !enabled { - return true - } - } - return false -} -func resourceDomainSAMLOptionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) - - if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Elasticsearch Domain SAML Options (%s) not found, removing from state", d.Id()) - d.SetId("") - return diags + domainName := d.Get(names.AttrDomainName).(string) + input := &elasticsearch.UpdateElasticsearchDomainConfigInput{ + AdvancedSecurityOptions: &awstypes.AdvancedSecurityOptionsInput{ + SAMLOptions: expandESSAMLOptions(d.Get("saml_options").([]interface{})), + }, + DomainName: aws.String(domainName), } + _, err := conn.UpdateElasticsearchDomainConfig(ctx, input) + if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Received Elasticsearch domain: %+v", ds) - - options := ds.AdvancedSecurityOptions.SAMLOptions + if d.IsNewResource() { + d.SetId(domainName) + } - if err := d.Set("saml_options", flattenESSAMLOptions(d, options)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting saml_options for Elasticsearch Configuration: %s", err) + if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) } - return diags + return append(diags, resourceDomainSAMLOptionsRead(ctx, d, meta)...) } -func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { +func resourceDomainSAMLOptionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - domainName := d.Get(names.AttrDomainName).(string) - config := awstypes.AdvancedSecurityOptionsInput{} - config.SAMLOptions = expandESSAMLOptions(d.Get("saml_options").([]interface{})) - - log.Printf("[DEBUG] Updating Elasticsearch domain SAML Options %+v", config) + output, err := findDomainSAMLOptionByDomainName(ctx, conn, d.Id()) - _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ - DomainName: aws.String(domainName), - AdvancedSecurityOptions: &config, - }) + if !d.IsNewResource() && tfresource.NotFound(err) { + log.Printf("[WARN] Elasticsearch Domain SAML Options (%s) not found, removing from state", d.Id()) + d.SetId("") + return diags + } if err != nil { - return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) } - d.SetId(domainName) - - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain SAML Options (%s): waiting for completion: %s", d.Id(), err) + d.Set(names.AttrDomainName, d.Id()) + if err := d.Set("saml_options", flattenSAMLOptionsOutput(d, output)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting saml_options: %s", err) } - return append(diags, resourceDomainSAMLOptionsRead(ctx, d, meta)...) + return diags } func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) - domainName := d.Get(names.AttrDomainName).(string) - config := awstypes.AdvancedSecurityOptionsInput{} - config.SAMLOptions = nil - + log.Printf("[DEBUG] Deleting Elasticsearch Domain SAML Options: %s", d.Id()) _, err := conn.UpdateElasticsearchDomainConfig(ctx, &elasticsearch.UpdateElasticsearchDomainConfigInput{ - DomainName: aws.String(domainName), - AdvancedSecurityOptions: &config, + AdvancedSecurityOptions: &awstypes.AdvancedSecurityOptionsInput{}, + DomainName: aws.String(d.Id()), }) if errs.IsA[*awstypes.ResourceNotFoundException](err) { @@ -195,11 +179,32 @@ func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Waiting for Elasticsearch domain SAML Options %q to be deleted", d.Get(names.AttrDomainName).(string)) - - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain SAML Options (%s): waiting for completion: %s", d.Id(), err) + if err := waitForDomainUpdate(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) } return diags } + +func domainSamlOptionsDiffSupress(k, old, new string, d *schema.ResourceData) bool { + if v, ok := d.Get("saml_options").([]interface{}); ok && len(v) > 0 { + if enabled, ok := v[0].(map[string]interface{})[names.AttrEnabled].(bool); ok && !enabled { + return true + } + } + return false +} + +func findDomainSAMLOptionByDomainName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.SAMLOptionsOutput, error) { + output, err := findDomainByName(ctx, conn, name) + + if err != nil { + return nil, err + } + + if output.AdvancedSecurityOptions == nil || output.AdvancedSecurityOptions.SAMLOptions == nil { + return nil, tfresource.NewEmptyResultError(name) + } + + return output.AdvancedSecurityOptions.SAMLOptions, nil +} diff --git a/internal/service/elasticsearch/domain_saml_options_test.go b/internal/service/elasticsearch/domain_saml_options_test.go index 2453946b5c9e..bd5d24e2ae1d 100644 --- a/internal/service/elasticsearch/domain_saml_options_test.go +++ b/internal/service/elasticsearch/domain_saml_options_test.go @@ -8,7 +8,6 @@ import ( "fmt" "testing" - awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/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" @@ -21,26 +20,21 @@ import ( func TestAccElasticsearchDomainSAMLOptions_basic(t *testing.T) { ctx := acctest.Context(t) - var domain awstypes.ElasticsearchDomainStatus - rName := sdkacctest.RandomWithPrefix("acc-test") rUserName := sdkacctest.RandomWithPrefix("es-master-user") idpEntityId := fmt.Sprintf("https://%s", acctest.RandomDomainName()) - resourceName := "aws_elasticsearch_domain_saml_options.main" - esDomainResourceName := "aws_elasticsearch_domain.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ElasticsearchServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy(ctx), + CheckDestroy: testAccCheckDomainSAMLOptionsDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( - testAccCheckDomainExists(ctx, esDomainResourceName, &domain), - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "saml_options.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "saml_options.0.enabled", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "saml_options.0.idp.#", acctest.Ct1), @@ -61,20 +55,18 @@ func TestAccElasticsearchDomainSAMLOptions_disappears(t *testing.T) { rName := sdkacctest.RandomWithPrefix("acc-test") rUserName := sdkacctest.RandomWithPrefix("es-master-user") idpEntityId := fmt.Sprintf("https://%s", acctest.RandomDomainName()) - resourceName := "aws_elasticsearch_domain_saml_options.main" - esDomainResourceName := "aws_elasticsearch_domain.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ElasticsearchServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy(ctx), + CheckDestroy: testAccCheckDomainSAMLOptionsDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), acctest.CheckResourceDisappears(ctx, acctest.Provider, tfelasticsearch.ResourceDomainSAMLOptions(), resourceName), ), }, @@ -87,7 +79,6 @@ func TestAccElasticsearchDomainSAMLOptions_disappears_Domain(t *testing.T) { rName := sdkacctest.RandomWithPrefix("acc-test") rUserName := sdkacctest.RandomWithPrefix("es-master-user") idpEntityId := fmt.Sprintf("https://%s", acctest.RandomDomainName()) - resourceName := "aws_elasticsearch_domain_saml_options.main" esDomainResourceName := "aws_elasticsearch_domain.example" @@ -95,12 +86,12 @@ func TestAccElasticsearchDomainSAMLOptions_disappears_Domain(t *testing.T) { PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ElasticsearchServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy(ctx), + CheckDestroy: testAccCheckDomainSAMLOptionsDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), acctest.CheckResourceDisappears(ctx, acctest.Provider, tfelasticsearch.ResourceDomain(), esDomainResourceName), ), ExpectNonEmptyPlan: true, @@ -114,30 +105,28 @@ func TestAccElasticsearchDomainSAMLOptions_Update(t *testing.T) { rName := sdkacctest.RandomWithPrefix("acc-test") rUserName := sdkacctest.RandomWithPrefix("es-master-user") idpEntityId := fmt.Sprintf("https://%s", acctest.RandomDomainName()) - resourceName := "aws_elasticsearch_domain_saml_options.main" - esDomainResourceName := "aws_elasticsearch_domain.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ElasticsearchServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy(ctx), + CheckDestroy: testAccCheckDomainSAMLOptionsDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "saml_options.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "60"), - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), ), }, { Config: testAccDomainSAMLOptionsConfig_update(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "saml_options.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "180"), - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), ), }, }, @@ -149,37 +138,35 @@ func TestAccElasticsearchDomainSAMLOptions_Disabled(t *testing.T) { rName := sdkacctest.RandomWithPrefix("acc-test") rUserName := sdkacctest.RandomWithPrefix("es-master-user") idpEntityId := fmt.Sprintf("https://%s", acctest.RandomDomainName()) - resourceName := "aws_elasticsearch_domain_saml_options.main" - esDomainResourceName := "aws_elasticsearch_domain.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ElasticsearchServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckESDomainSAMLOptionsDestroy(ctx), + CheckDestroy: testAccCheckDomainSAMLOptionsDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccDomainSAMLOptionsConfig_basic(rUserName, rName, idpEntityId), Check: resource.ComposeTestCheckFunc( + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "saml_options.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", "60"), - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), ), }, { Config: testAccDomainSAMLOptionsConfig_disabled(rUserName, rName), Check: resource.ComposeTestCheckFunc( + testAccCheckDomainSAMLOptionsExist(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "saml_options.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "saml_options.0.session_timeout_minutes", acctest.Ct0), - testAccCheckESDomainSAMLOptions(ctx, esDomainResourceName, resourceName), ), }, }, }) } -func testAccCheckESDomainSAMLOptionsDestroy(ctx context.Context) resource.TestCheckFunc { +func testAccCheckDomainSAMLOptionsDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_elasticsearch_domain_saml_options" { @@ -188,7 +175,7 @@ func testAccCheckESDomainSAMLOptionsDestroy(ctx context.Context) resource.TestCh conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) - _, err := tfelasticsearch.FindDomainByName(ctx, conn, rs.Primary.Attributes[names.AttrDomainName]) + _, err := tfelasticsearch.FindDomainSAMLOptionByDomainName(ctx, conn, rs.Primary.Attributes[names.AttrDomainName]) if tfresource.NotFound(err) { continue @@ -198,32 +185,23 @@ func testAccCheckESDomainSAMLOptionsDestroy(ctx context.Context) resource.TestCh return err } - return fmt.Errorf("Elasticsearch domain saml options %s still exists", rs.Primary.ID) + return fmt.Errorf("Elasticsearch Domain SAML Options %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckESDomainSAMLOptions(ctx context.Context, esResource string, samlOptionsResource string) resource.TestCheckFunc { +func testAccCheckDomainSAMLOptionsExist(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[esResource] - if !ok { - return fmt.Errorf("Not found: %s", esResource) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No ID is set") - } - - options, ok := s.RootModule().Resources[samlOptionsResource] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("Not found: %s", samlOptionsResource) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ElasticsearchClient(ctx) - _, err := tfelasticsearch.FindDomainByName(ctx, conn, options.Primary.Attributes[names.AttrDomainName]) + _, err := tfelasticsearch.FindDomainSAMLOptionByDomainName(ctx, conn, rs.Primary.ID) return err } diff --git a/internal/service/elasticsearch/domain_structure.go b/internal/service/elasticsearch/domain_structure.go index c0345a57338f..4fad2c878d77 100644 --- a/internal/service/elasticsearch/domain_structure.go +++ b/internal/service/elasticsearch/domain_structure.go @@ -235,41 +235,41 @@ func flattenAutoTuneMaintenanceScheduleDuration(autoTuneMaintenanceScheduleDurat return m } -func flattenESSAMLOptions(d *schema.ResourceData, samlOptions *awstypes.SAMLOptionsOutput) []interface{} { - if samlOptions == nil { +func flattenSAMLOptionsOutput(d *schema.ResourceData, apiObject *awstypes.SAMLOptionsOutput) []interface{} { + if apiObject == nil { return nil } - m := map[string]interface{}{ - names.AttrEnabled: aws.ToBool(samlOptions.Enabled), - "idp": flattenESSAMLIdpOptions(samlOptions.Idp), + tfMap := map[string]interface{}{ + names.AttrEnabled: aws.ToBool(apiObject.Enabled), + "idp": flattenSAMLIdp(apiObject.Idp), } - m["roles_key"] = aws.ToString(samlOptions.RolesKey) - m["session_timeout_minutes"] = aws.ToInt32(samlOptions.SessionTimeoutMinutes) - m["subject_key"] = aws.ToString(samlOptions.SubjectKey) + tfMap["roles_key"] = aws.ToString(apiObject.RolesKey) + tfMap["session_timeout_minutes"] = aws.ToInt32(apiObject.SessionTimeoutMinutes) + tfMap["subject_key"] = aws.ToString(apiObject.SubjectKey) // samlOptions.master_backend_role and samlOptions.master_user_name will be added to the // all_access role in kibana's security manager. These values cannot be read or // modified by the elasticsearch API. So, we ignore it on read and let persist // the value already in the state. - m["master_backend_role"] = d.Get("saml_options.0.master_backend_role").(string) - m["master_user_name"] = d.Get("saml_options.0.master_user_name").(string) + tfMap["master_backend_role"] = d.Get("saml_options.0.master_backend_role").(string) + tfMap["master_user_name"] = d.Get("saml_options.0.master_user_name").(string) - return []interface{}{m} + return []interface{}{tfMap} } -func flattenESSAMLIdpOptions(SAMLIdp *awstypes.SAMLIdp) []interface{} { - if SAMLIdp == nil { +func flattenSAMLIdp(apiObject *awstypes.SAMLIdp) []interface{} { + if apiObject == nil { return []interface{}{} } - m := map[string]interface{}{ - "entity_id": aws.ToString(SAMLIdp.EntityId), - "metadata_content": aws.ToString(SAMLIdp.MetadataContent), + tfMap := map[string]interface{}{ + "entity_id": aws.ToString(apiObject.EntityId), + "metadata_content": aws.ToString(apiObject.MetadataContent), } - return []interface{}{m} + return []interface{}{tfMap} } func getMasterUserOptions(d *schema.ResourceData) []interface{} { diff --git a/internal/service/elasticsearch/exports_test.go b/internal/service/elasticsearch/exports_test.go index 130d053d82e7..6cde9dda1b0c 100644 --- a/internal/service/elasticsearch/exports_test.go +++ b/internal/service/elasticsearch/exports_test.go @@ -9,8 +9,9 @@ var ( ResourceDomainSAMLOptions = resourceDomainSAMLOptions ResourceVPCEndpoint = resourceVPCEndpoint - FindDomainByName = findDomainByName - FindVPCEndpointByID = findVPCEndpointByID - VPCEndpointsError = vpcEndpointsError - WaitForDomainCreation = waitForDomainCreation + FindDomainByName = findDomainByName + FindDomainSAMLOptionByDomainName = findDomainSAMLOptionByDomainName + FindVPCEndpointByID = findVPCEndpointByID + VPCEndpointsError = vpcEndpointsError + WaitForDomainCreation = waitForDomainCreation ) diff --git a/internal/service/elasticsearch/find.go b/internal/service/elasticsearch/find.go index 7038ee82da4a..72262a8a24bb 100644 --- a/internal/service/elasticsearch/find.go +++ b/internal/service/elasticsearch/find.go @@ -19,6 +19,10 @@ func findDomainByName(ctx context.Context, conn *elasticsearch.Client, name stri DomainName: aws.String(name), } + return findDomain(ctx, conn, input) +} + +func findDomain(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.DescribeElasticsearchDomainInput) (*awstypes.ElasticsearchDomainStatus, error) { output, err := conn.DescribeElasticsearchDomain(ctx, input) if errs.IsA[*awstypes.ResourceNotFoundException](err) { From 0eb7dccde404b375084809594e78372d2ef6924f Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 11:35:33 -0400 Subject: [PATCH 16/24] d/aws_elasticsearch_domain: Tidy up. --- .../elasticsearch/domain_data_source.go | 95 ++++++------------- internal/service/elasticsearch/find.go | 29 ++++++ 2 files changed, 59 insertions(+), 65 deletions(-) diff --git a/internal/service/elasticsearch/domain_data_source.go b/internal/service/elasticsearch/domain_data_source.go index b410fe7be9ba..23340b9147a0 100644 --- a/internal/service/elasticsearch/domain_data_source.go +++ b/internal/service/elasticsearch/domain_data_source.go @@ -7,13 +7,11 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-provider-aws/internal/conns" "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" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -350,117 +348,84 @@ func dataSourceDomainRead(ctx context.Context, d *schema.ResourceData, meta inte conn := meta.(*conns.AWSClient).ElasticsearchClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - ds, err := findDomainByName(ctx, conn, d.Get(names.AttrDomainName).(string)) + domainName := d.Get(names.AttrDomainName).(string) + ds, err := findDomainByName(ctx, conn, domainName) + if err != nil { - return sdkdiag.AppendErrorf(diags, "your query returned no results") + return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain (%s): %s", domainName, err) } - reqDescribeDomainConfig := &elasticsearchservice.DescribeElasticsearchDomainConfigInput{ - DomainName: aws.String(d.Get(names.AttrDomainName).(string)), - } + dc, err := findDomainConfigByName(ctx, conn, domainName) - respDescribeDomainConfig, err := conn.DescribeElasticsearchDomainConfig(ctx, reqDescribeDomainConfig) if err != nil { - return sdkdiag.AppendErrorf(diags, "querying config for elasticsearch_domain: %s", err) - } - - if respDescribeDomainConfig.DomainConfig == nil { - return sdkdiag.AppendErrorf(diags, "your query returned no results") + return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain (%s) Config: %s", domainName, err) } - dc := respDescribeDomainConfig.DomainConfig - d.SetId(aws.ToString(ds.ARN)) if ds.AccessPolicies != nil && aws.ToString(ds.AccessPolicies) != "" { policies, err := structure.NormalizeJsonString(*ds.AccessPolicies) if err != nil { - return sdkdiag.AppendErrorf(diags, "access policies contain an invalid JSON: %s", err) + return sdkdiag.AppendFromErr(diags, err) } d.Set("access_policies", policies) } - - if err := d.Set("advanced_options", flex.FlattenStringValueMap(ds.AdvancedOptions)); err != nil { + if err := d.Set("advanced_options", ds.AdvancedOptions); err != nil { return sdkdiag.AppendErrorf(diags, "setting advanced_options: %s", err) } - - d.Set(names.AttrARN, ds.ARN) - d.Set("domain_id", ds.DomainId) - d.Set(names.AttrEndpoint, ds.Endpoint) - d.Set("kibana_endpoint", getKibanaEndpoint(d)) - if err := d.Set("advanced_security_options", flattenAdvancedSecurityOptions(ds.AdvancedSecurityOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting advanced_security_options: %s", err) } - + d.Set(names.AttrARN, ds.ARN) if dc.AutoTuneOptions != nil { if err := d.Set("auto_tune_options", []interface{}{flattenAutoTuneOptions(dc.AutoTuneOptions.Options)}); err != nil { return sdkdiag.AppendErrorf(diags, "setting auto_tune_options: %s", err) } } - + if err := d.Set("cluster_config", flattenElasticsearchClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting cluster_config: %s", err) + } + if err := d.Set("cognito_options", flattenCognitoOptions(ds.CognitoOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting cognito_options: %s", err) + } + d.Set("created", ds.Created) + d.Set("deleted", ds.Deleted) + d.Set("domain_id", ds.DomainId) if err := d.Set("ebs_options", flattenEBSOptions(ds.EBSOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting ebs_options: %s", err) } - + d.Set("elasticsearch_version", ds.ElasticsearchVersion) if err := d.Set("encryption_at_rest", flattenEncryptAtRestOptions(ds.EncryptionAtRestOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting encryption_at_rest: %s", err) } - + d.Set(names.AttrEndpoint, ds.Endpoint) + d.Set("kibana_endpoint", getKibanaEndpoint(d)) + if err := d.Set("log_publishing_options", flattenLogPublishingOptions(ds.LogPublishingOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting log_publishing_options: %s", err) + } if err := d.Set("node_to_node_encryption", flattenNodeToNodeEncryptionOptions(ds.NodeToNodeEncryptionOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting node_to_node_encryption: %s", err) } - - if err := d.Set("cluster_config", flattenElasticsearchClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting cluster_config: %s", err) - } - + d.Set("processing", ds.Processing) if err := d.Set("snapshot_options", flattenSnapshotOptions(ds.SnapshotOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting snapshot_options: %s", err) } - if ds.VPCOptions != nil { if err := d.Set("vpc_options", []interface{}{flattenVPCDerivedInfo(ds.VPCOptions)}); err != nil { return sdkdiag.AppendErrorf(diags, "setting vpc_options: %s", err) } - endpoints := flex.FlattenStringValueMap(ds.Endpoints) - if err := d.Set(names.AttrEndpoint, endpoints["vpc"]); err != nil { - return sdkdiag.AppendErrorf(diags, "setting endpoint: %s", err) - } + d.Set(names.AttrEndpoint, ds.Endpoints["vpc"]) + d.Set("kibana_endpoint", getKibanaEndpoint(d)) + } else if ds.Endpoint != nil { + d.Set(names.AttrEndpoint, ds.Endpoint) d.Set("kibana_endpoint", getKibanaEndpoint(d)) - if ds.Endpoint != nil { - return sdkdiag.AppendErrorf(diags, "%q: Elasticsearch domain in VPC expected to have null Endpoint value", d.Id()) - } - } else { - if ds.Endpoint != nil { - d.Set(names.AttrEndpoint, ds.Endpoint) - d.Set("kibana_endpoint", getKibanaEndpoint(d)) - } - if ds.Endpoints != nil { - return sdkdiag.AppendErrorf(diags, "%q: Elasticsearch domain not in VPC expected to have null Endpoints value", d.Id()) - } - } - - if err := d.Set("log_publishing_options", flattenLogPublishingOptions(ds.LogPublishingOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting log_publishing_options: %s", err) - } - - d.Set("elasticsearch_version", ds.ElasticsearchVersion) - - if err := d.Set("cognito_options", flattenCognitoOptions(ds.CognitoOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting cognito_options: %s", err) } - d.Set("created", ds.Created) - d.Set("deleted", ds.Deleted) - - d.Set("processing", ds.Processing) - tags, err := listTags(ctx, conn, d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "listing tags for Elasticsearch Cluster (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "listing tags for Elasticsearch Domain (%s): %s", d.Id(), err) } if err := d.Set(names.AttrTags, tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { diff --git a/internal/service/elasticsearch/find.go b/internal/service/elasticsearch/find.go index 72262a8a24bb..a2d53189dfc2 100644 --- a/internal/service/elasticsearch/find.go +++ b/internal/service/elasticsearch/find.go @@ -42,3 +42,32 @@ func findDomain(ctx context.Context, conn *elasticsearch.Client, input *elastics return output.DomainStatus, nil } + +func findDomainConfigByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainConfig, error) { + input := &elasticsearch.DescribeElasticsearchDomainConfigInput{ + DomainName: aws.String(name), + } + + return findDomainConfig(ctx, conn, input) +} + +func findDomainConfig(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.DescribeElasticsearchDomainConfigInput) (*awstypes.ElasticsearchDomainConfig, error) { + output, err := conn.DescribeElasticsearchDomainConfig(ctx, input) + + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.DomainConfig == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.DomainConfig, nil +} From 879fa676897e09bf2f94bf01d23c31a448ec6c65 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 14:09:02 -0400 Subject: [PATCH 17/24] r/aws_elasticsearch_domain: Tidy up Create and Delete. --- internal/service/elasticsearch/domain.go | 438 +++++++++++++++--- .../service/elasticsearch/domain_policy.go | 4 +- .../elasticsearch/domain_saml_options.go | 4 +- internal/service/elasticsearch/domain_test.go | 2 +- .../service/elasticsearch/exports_test.go | 2 +- internal/service/elasticsearch/find.go | 73 --- internal/service/elasticsearch/status.go | 60 --- internal/service/elasticsearch/wait.go | 150 ------ 8 files changed, 373 insertions(+), 360 deletions(-) delete mode 100644 internal/service/elasticsearch/find.go delete mode 100644 internal/service/elasticsearch/status.go delete mode 100644 internal/service/elasticsearch/wait.go diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index badb9344c2f1..e4d1a0cfb1a7 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -18,6 +18,7 @@ import ( awspolicy "github.com/hashicorp/awspolicyequivalence" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -560,9 +561,8 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte if v, ok := d.GetOk("access_policies"); ok { policy, err := structure.NormalizeJsonString(v.(string)) - if err != nil { - return sdkdiag.AppendErrorf(diags, "policy (%s) is invalid JSON: %s", policy, err) + return sdkdiag.AppendFromErr(diags, err) } input.AccessPolicies = aws.String(policy) @@ -580,90 +580,82 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte input.AutoTuneOptions = expandAutoTuneOptionsInput(v.([]interface{})[0].(map[string]interface{})) } - if v, ok := d.GetOk("ebs_options"); ok { - options := v.([]interface{}) - - if len(options) == 1 { - if options[0] == nil { - return sdkdiag.AppendErrorf(diags, "At least one field is expected inside ebs_options") + if v, ok := d.GetOk("cluster_config"); ok { + if v := v.([]interface{}); len(v) == 1 { + if v[0] == nil { + return sdkdiag.AppendErrorf(diags, "At least one field is expected inside cluster_config") } - s := options[0].(map[string]interface{}) - input.EBSOptions = expandEBSOptions(s) + input.ElasticsearchClusterConfig = expandElasticsearchClusterConfig(v[0].(map[string]interface{})) } } - if v, ok := d.GetOk("encrypt_at_rest"); ok { - options := v.([]interface{}) - if options[0] == nil { - return sdkdiag.AppendErrorf(diags, "At least one field is expected inside encrypt_at_rest") - } + if v, ok := d.GetOk("cognito_options"); ok { + input.CognitoOptions = expandCognitoOptions(v.([]interface{})) + } - s := options[0].(map[string]interface{}) - input.EncryptionAtRestOptions = expandEncryptAtRestOptions(s) + if v, ok := d.GetOk("domain_endpoint_options"); ok { + input.DomainEndpointOptions = expandDomainEndpointOptions(v.([]interface{})) } - if v, ok := d.GetOk("cluster_config"); ok { - config := v.([]interface{}) + if v, ok := d.GetOk("ebs_options"); ok { + if v := v.([]interface{}); len(v) == 1 { + if v[0] == nil { + return sdkdiag.AppendErrorf(diags, "At least one field is expected inside ebs_options") + } - if len(config) == 1 { - if config[0] == nil { - return sdkdiag.AppendErrorf(diags, "At least one field is expected inside cluster_config") + input.EBSOptions = expandEBSOptions(v[0].(map[string]interface{})) + } + } + + if v, ok := d.GetOk("encrypt_at_rest"); ok { + if v := v.([]interface{}); len(v) == 1 { + if v[0] == nil { + return sdkdiag.AppendErrorf(diags, "At least one field is expected inside encrypt_at_rest") } - m := config[0].(map[string]interface{}) - input.ElasticsearchClusterConfig = expandElasticsearchClusterConfig(m) + + input.EncryptionAtRestOptions = expandEncryptAtRestOptions(v[0].(map[string]interface{})) } } + if v, ok := d.GetOk("log_publishing_options"); ok { + input.LogPublishingOptions = expandLogPublishingOptions(v.(*schema.Set)) + } + if v, ok := d.GetOk("node_to_node_encryption"); ok { - options := v.([]interface{}) + if v := v.([]interface{}); len(v) == 1 { + if v[0] == nil { + return sdkdiag.AppendErrorf(diags, "At least one field is expected inside node_to_node_encryption") + } - s := options[0].(map[string]interface{}) - input.NodeToNodeEncryptionOptions = expandNodeToNodeEncryptionOptions(s) + input.NodeToNodeEncryptionOptions = expandNodeToNodeEncryptionOptions(v[0].(map[string]interface{})) + } } if v, ok := d.GetOk("snapshot_options"); ok { - options := v.([]interface{}) - - if len(options) == 1 { - if options[0] == nil { + if v := v.([]interface{}); len(v) == 1 { + if v[0] == nil { return sdkdiag.AppendErrorf(diags, "At least one field is expected inside snapshot_options") } - o := options[0].(map[string]interface{}) + tfMap := v[0].(map[string]interface{}) - snapshotOptions := awstypes.SnapshotOptions{ - AutomatedSnapshotStartHour: aws.Int32(int32(o["automated_snapshot_start_hour"].(int))), + input.SnapshotOptions = &awstypes.SnapshotOptions{ + AutomatedSnapshotStartHour: aws.Int32(int32(tfMap["automated_snapshot_start_hour"].(int))), } - - input.SnapshotOptions = &snapshotOptions } } if v, ok := d.GetOk("vpc_options"); ok { - options := v.([]interface{}) - if options[0] == nil { - return sdkdiag.AppendErrorf(diags, "At least one field is expected inside vpc_options") - } - - s := options[0].(map[string]interface{}) - input.VPCOptions = expandVPCOptions(s) - } - - if v, ok := d.GetOk("log_publishing_options"); ok { - input.LogPublishingOptions = expandLogPublishingOptions(v.(*schema.Set)) - } - - if v, ok := d.GetOk("domain_endpoint_options"); ok { - input.DomainEndpointOptions = expandDomainEndpointOptions(v.([]interface{})) - } + if v := v.([]interface{}); len(v) == 1 { + if v[0] == nil { + return sdkdiag.AppendErrorf(diags, "At least one field is expected inside vpc_options") + } - if v, ok := d.GetOk("cognito_options"); ok { - input.CognitoOptions = expandCognitoOptions(v.([]interface{})) + input.VPCOptions = expandVPCOptions(v[0].(map[string]interface{})) + } } - log.Printf("[DEBUG] Creating Elasticsearch Domain: %+v", input) - outputRaw, err := tfresource.RetryWhen(ctx, propagationTimeout, func() (interface{}, error) { return conn.CreateElasticsearchDomain(ctx, input) @@ -690,7 +682,7 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte d.SetId(aws.ToString(outputRaw.(*elasticsearch.CreateElasticsearchDomainOutput).DomainStatus.ARN)) - if err := waitForDomainCreation(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { + if _, err := waitDomainCreated(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) create: %s", d.Id(), err) } @@ -700,15 +692,14 @@ func resourceDomainCreate(ctx context.Context, d *schema.ResourceData, meta inte DomainName: aws.String(name), } - log.Printf("[DEBUG] Updating Elasticsearch Domain config: %+v", input) _, err = conn.UpdateElasticsearchDomainConfig(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "updating Elasticsearch Domain (%s) config: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "updating Elasticsearch Domain (%s) Config: %s", d.Id(), err) } - if err := waitForDomainUpdate(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + if _, err := waitDomainConfigUpdated(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) Config update: %s", d.Id(), err) } } @@ -1003,7 +994,7 @@ func resourceDomainDelete(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain (%s): %s", d.Id(), err) } - if err := waitForDomainDelete(ctx, conn, name, d.Timeout(schema.TimeoutDelete)); err != nil { + if _, err := waitDomainDeleted(ctx, conn, name, d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) delete: %s", d.Id(), err) } @@ -1026,6 +1017,313 @@ func resourceDomainImport(ctx context.Context, d *schema.ResourceData, meta inte return []*schema.ResourceData{d}, nil } +func findDomainByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainStatus, error) { + input := &elasticsearch.DescribeElasticsearchDomainInput{ + DomainName: aws.String(name), + } + output, err := findDomain(ctx, conn, input) + + if err != nil { + return nil, err + } + + if aws.ToBool(output.Deleted) { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findDomain(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.DescribeElasticsearchDomainInput) (*awstypes.ElasticsearchDomainStatus, error) { + output, err := conn.DescribeElasticsearchDomain(ctx, input) + + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.DomainStatus == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.DomainStatus, nil +} + +func findDomainChangeProgressDetailsByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ChangeProgressDetails, error) { + output, err := findDomainByName(ctx, conn, name) + + if err != nil { + return nil, err + } + + if output.ChangeProgressDetails == nil { + return nil, tfresource.NewEmptyResultError(nil) + } + + return output.ChangeProgressDetails, nil +} + +func findDomainConfigByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainConfig, error) { + input := &elasticsearch.DescribeElasticsearchDomainConfigInput{ + DomainName: aws.String(name), + } + + return findDomainConfig(ctx, conn, input) +} + +func findDomainConfig(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.DescribeElasticsearchDomainConfigInput) (*awstypes.ElasticsearchDomainConfig, error) { + output, err := conn.DescribeElasticsearchDomainConfig(ctx, input) + + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.DomainConfig == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.DomainConfig, nil +} + +func findDomainUpgradeStatusByName(ctx context.Context, conn *elasticsearch.Client, name string) (*elasticsearch.GetUpgradeStatusOutput, error) { + input := &elasticsearch.GetUpgradeStatusInput{ + DomainName: aws.String(name), + } + + return findDomainUpgradeStatus(ctx, conn, input) +} + +func findDomainUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.GetUpgradeStatusInput) (*elasticsearch.GetUpgradeStatusOutput, error) { + output, err := conn.GetUpgradeStatus(ctx, input) + + if errs.IsA[*awstypes.ResourceNotFoundException](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 statusDomainConfigChange(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findDomainChangeProgressDetailsByName(ctx, conn, name) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.ConfigChangeStatus), nil + } +} + +func statusDomainProcessing(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findDomainByName(ctx, conn, name) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.DomainProcessingStatus), nil + } +} + +const ( + UpgradeStatusUnknown = "Unknown" + ConfigStatusNotFound = "NotFound" + ConfigStatusUnknown = "Unknown" + ConfigStatusExists = "Exists" +) + +func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + out, err := conn.GetUpgradeStatus(ctx, &elasticsearch.GetUpgradeStatusInput{ + DomainName: aws.String(name), + }) + if err != nil { + return nil, UpgradeStatusUnknown, err + } + + // Elasticsearch upgrades consist of multiple steps: + // https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-version-migration.html + // Prevent false positive completion where the UpgradeStep is not the final UPGRADE step. + if out.StepStatus == awstypes.UpgradeStatusSucceeded && out.UpgradeStep != awstypes.UpgradeStepUpgrade { + return out, string(awstypes.UpgradeStatusInProgress), nil + } + + return out, string(out.StepStatus), nil + } +} + +func domainConfigStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + out, err := conn.DescribeElasticsearchDomainConfig(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ + DomainName: aws.String(name), + }) + + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + // if first return value is nil, WaitForState treats as not found - here not found is treated differently + return "not nil", ConfigStatusNotFound, nil + } + + if err != nil { + return nil, ConfigStatusUnknown, err + } + + return out, ConfigStatusExists, nil + } +} + +const ( + domainUpgradeSuccessMinTimeout = 10 * time.Second + domainUpgradeSuccessDelay = 30 * time.Second +) + +// UpgradeSucceeded waits for an Upgrade to return Success +func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Client, name string, timeout time.Duration) (*elasticsearch.GetUpgradeStatusOutput, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusInProgress), + Target: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusSucceeded), + Refresh: statusUpgradeStatus(ctx, conn, name), + Timeout: timeout, + MinTimeout: domainUpgradeSuccessMinTimeout, + Delay: domainUpgradeSuccessDelay, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*elasticsearch.GetUpgradeStatusOutput); ok { + return output, err + } + + return nil, err +} + +func waitDomainCreated(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) (*awstypes.ElasticsearchDomainStatus, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.DomainProcessingStatusTypeCreating), + Target: enum.Slice(awstypes.DomainProcessingStatusTypeActive), + Refresh: statusDomainProcessing(ctx, conn, domainName), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ElasticsearchDomainStatus); ok { + if v := output.ChangeProgressDetails; v != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", v.ConfigChangeStatus, aws.ToString(v.Message))) + } + + return output, err + } + + return nil, err +} + +func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { + var out *awstypes.ElasticsearchDomainStatus + err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { + var err error + out, err = findDomainByName(ctx, conn, domainName) + if err != nil { + return retry.NonRetryableError(err) + } + + if !aws.ToBool(out.Processing) { + return nil + } + + return retry.RetryableError( + fmt.Errorf("%q: Timeout while waiting for changes to be processed", domainName)) + }) + if tfresource.TimedOut(err) { + out, err = findDomainByName(ctx, conn, domainName) + if err != nil { + return fmt.Errorf("describing Elasticsearch domain: %w", err) + } + if !aws.ToBool(out.Processing) { + return nil + } + } + + return err +} + +func waitDomainConfigUpdated(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) (*awstypes.ElasticsearchDomainStatus, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.DomainProcessingStatusTypeModifying), + Target: enum.Slice(awstypes.DomainProcessingStatusTypeActive), + Refresh: statusDomainProcessing(ctx, conn, domainName), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ElasticsearchDomainStatus); ok { + if v := output.ChangeProgressDetails; v != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", v.ConfigChangeStatus, aws.ToString(v.Message))) + } + + return output, err + } + + return nil, err +} + +func waitDomainDeleted(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) (*awstypes.ElasticsearchDomainStatus, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.DomainProcessingStatusTypeDeleting), + Target: []string{}, + Refresh: statusDomainProcessing(ctx, conn, domainName), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ElasticsearchDomainStatus); ok { + if v := output.ChangeProgressDetails; v != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", v.ConfigChangeStatus, aws.ToString(v.Message))) + } + + return output, err + } + + return nil, err +} + func warmPartitionInstanceType_Values() []string { return tfslices.AppendUnique(enum.Values[awstypes.ESWarmPartitionInstanceType](), "ultrawarm1.xlarge.elasticsearch") } @@ -1048,19 +1346,17 @@ func getKibanaEndpoint(d *schema.ResourceData) string { } func isDedicatedMasterDisabled(k, old, new string, d *schema.ResourceData) bool { - v, ok := d.GetOk("cluster_config") - if ok { - clusterConfig := v.([]interface{})[0].(map[string]interface{}) - return !clusterConfig["dedicated_master_enabled"].(bool) + if v, ok := d.GetOk("cluster_config"); ok { + tfMap := v.([]interface{})[0].(map[string]interface{}) + return !tfMap["dedicated_master_enabled"].(bool) } return false } func isCustomEndpointDisabled(k, old, new string, d *schema.ResourceData) bool { - v, ok := d.GetOk("domain_endpoint_options") - if ok { - domainEndpointOptions := v.([]interface{})[0].(map[string]interface{}) - return !domainEndpointOptions["custom_endpoint_enabled"].(bool) + if v, ok := d.GetOk("domain_endpoint_options"); ok { + tfMap := v.([]interface{})[0].(map[string]interface{}) + return !tfMap["custom_endpoint_enabled"].(bool) } return false } @@ -1259,7 +1555,7 @@ func ebsVolumeTypePermitsIopsInput(volumeType string) bool { return slices.Contains(permittedTypes, volumeType) } -// EBSVolumeTypePermitsIopsInput returns true if the volume type supports the Throughput input +// ebsVolumeTypePermitsThroughputInput returns true if the volume type supports the Throughput input // // This check prevents a ValidationException when updating EBS volume types from a value // that supports Throughput (ex. gp3) to one that doesn't (ex. gp2). diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index 350bdfce4344..6dbc995ad5e8 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -135,8 +135,8 @@ func resourceDomainPolicyDelete(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain Policy (%s): %s", d.Id(), err) } - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + if _, err := waitDomainConfigUpdated(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutDelete)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) Config update: %s", d.Id(), err) } return diags diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 9b35d94b28f9..6f242ddb1d7b 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -179,8 +179,8 @@ func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) } - if err := waitForDomainUpdate(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + if _, err := waitDomainConfigUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) Config update: %s", d.Id(), err) } return diags diff --git a/internal/service/elasticsearch/domain_test.go b/internal/service/elasticsearch/domain_test.go index 76460a6acf50..cbc43aeecb7c 100644 --- a/internal/service/elasticsearch/domain_test.go +++ b/internal/service/elasticsearch/domain_test.go @@ -383,7 +383,7 @@ func TestAccElasticsearchDomain_duplicate(t *testing.T) { t.Fatal(err) } - err = tfelasticsearch.WaitForDomainCreation(ctx, conn, rName, 60*time.Minute) + _, err = tfelasticsearch.WaitDomainCreated(ctx, conn, rName, 60*time.Minute) if err != nil { t.Fatal(err) } diff --git a/internal/service/elasticsearch/exports_test.go b/internal/service/elasticsearch/exports_test.go index 6cde9dda1b0c..411b4d659d8b 100644 --- a/internal/service/elasticsearch/exports_test.go +++ b/internal/service/elasticsearch/exports_test.go @@ -13,5 +13,5 @@ var ( FindDomainSAMLOptionByDomainName = findDomainSAMLOptionByDomainName FindVPCEndpointByID = findVPCEndpointByID VPCEndpointsError = vpcEndpointsError - WaitForDomainCreation = waitForDomainCreation + WaitDomainCreated = waitDomainCreated ) diff --git a/internal/service/elasticsearch/find.go b/internal/service/elasticsearch/find.go deleted file mode 100644 index a2d53189dfc2..000000000000 --- a/internal/service/elasticsearch/find.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package elasticsearch - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" - "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" -) - -func findDomainByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainStatus, error) { - input := &elasticsearch.DescribeElasticsearchDomainInput{ - DomainName: aws.String(name), - } - - return findDomain(ctx, conn, input) -} - -func findDomain(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.DescribeElasticsearchDomainInput) (*awstypes.ElasticsearchDomainStatus, error) { - output, err := conn.DescribeElasticsearchDomain(ctx, input) - - if errs.IsA[*awstypes.ResourceNotFoundException](err) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || output.DomainStatus == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.DomainStatus, nil -} - -func findDomainConfigByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainConfig, error) { - input := &elasticsearch.DescribeElasticsearchDomainConfigInput{ - DomainName: aws.String(name), - } - - return findDomainConfig(ctx, conn, input) -} - -func findDomainConfig(ctx context.Context, conn *elasticsearch.Client, input *elasticsearch.DescribeElasticsearchDomainConfigInput) (*awstypes.ElasticsearchDomainConfig, error) { - output, err := conn.DescribeElasticsearchDomainConfig(ctx, input) - - if errs.IsA[*awstypes.ResourceNotFoundException](err) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || output.DomainConfig == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.DomainConfig, nil -} diff --git a/internal/service/elasticsearch/status.go b/internal/service/elasticsearch/status.go deleted file mode 100644 index b456f01b8ede..000000000000 --- a/internal/service/elasticsearch/status.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package elasticsearch - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/errs" -) - -const ( - UpgradeStatusUnknown = "Unknown" - ConfigStatusNotFound = "NotFound" - ConfigStatusUnknown = "Unknown" - ConfigStatusExists = "Exists" -) - -func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - out, err := conn.GetUpgradeStatus(ctx, &elasticsearch.GetUpgradeStatusInput{ - DomainName: aws.String(name), - }) - if err != nil { - return nil, UpgradeStatusUnknown, err - } - - // Elasticsearch upgrades consist of multiple steps: - // https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-version-migration.html - // Prevent false positive completion where the UpgradeStep is not the final UPGRADE step. - if out.StepStatus == awstypes.UpgradeStatusSucceeded && out.UpgradeStep != awstypes.UpgradeStepUpgrade { - return out, string(awstypes.UpgradeStatusInProgress), nil - } - - return out, string(out.StepStatus), nil - } -} - -func domainConfigStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - out, err := conn.DescribeElasticsearchDomainConfig(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ - DomainName: aws.String(name), - }) - - if errs.IsA[*awstypes.ResourceNotFoundException](err) { - // if first return value is nil, WaitForState treats as not found - here not found is treated differently - return "not nil", ConfigStatusNotFound, nil - } - - if err != nil { - return nil, ConfigStatusUnknown, err - } - - return out, ConfigStatusExists, nil - } -} diff --git a/internal/service/elasticsearch/wait.go b/internal/service/elasticsearch/wait.go deleted file mode 100644 index f78af6e0c7a5..000000000000 --- a/internal/service/elasticsearch/wait.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package elasticsearch - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - elasticsearch "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" - awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" -) - -const ( - domainUpgradeSuccessMinTimeout = 10 * time.Second - domainUpgradeSuccessDelay = 30 * time.Second -) - -// UpgradeSucceeded waits for an Upgrade to return Success -func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Client, name string, timeout time.Duration) (*elasticsearch.GetUpgradeStatusOutput, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusInProgress), - Target: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusSucceeded), - Refresh: statusUpgradeStatus(ctx, conn, name), - Timeout: timeout, - MinTimeout: domainUpgradeSuccessMinTimeout, - Delay: domainUpgradeSuccessDelay, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*elasticsearch.GetUpgradeStatusOutput); ok { - return output, err - } - - return nil, err -} - -func waitForDomainCreation(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { - var out *awstypes.ElasticsearchDomainStatus - err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { - var err error - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - return retry.NonRetryableError(err) - } - - if !aws.ToBool(out.Processing) && (out.Endpoint != nil || out.Endpoints != nil) { - return nil - } - - return retry.RetryableError( - fmt.Errorf("%q: Timeout while waiting for the domain to be created", domainName)) - }) - if tfresource.TimedOut(err) { - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - return fmt.Errorf("describing Elasticsearch domain: %w", err) - } - if !aws.ToBool(out.Processing) && (out.Endpoint != nil || out.Endpoints != nil) { - return nil - } - } - - return err -} - -func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { - var out *awstypes.ElasticsearchDomainStatus - err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { - var err error - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - return retry.NonRetryableError(err) - } - - if !aws.ToBool(out.Processing) { - return nil - } - - return retry.RetryableError( - fmt.Errorf("%q: Timeout while waiting for changes to be processed", domainName)) - }) - if tfresource.TimedOut(err) { - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - return fmt.Errorf("describing Elasticsearch domain: %w", err) - } - if !aws.ToBool(out.Processing) { - return nil - } - } - - return err -} - -func waitForDomainDelete(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { - var out *awstypes.ElasticsearchDomainStatus - err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { - var err error - out, err = findDomainByName(ctx, conn, domainName) - - if err != nil { - if tfresource.NotFound(err) { - return nil - } - return retry.NonRetryableError(err) - } - - if out != nil && !aws.ToBool(out.Processing) { - return nil - } - - return retry.RetryableError(fmt.Errorf("timeout while waiting for the domain %q to be deleted", domainName)) - }) - if tfresource.TimedOut(err) { - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - if tfresource.NotFound(err) { - return nil - } - return fmt.Errorf("describing Elasticsearch domain: %s", err) - } - if out != nil && !aws.ToBool(out.Processing) { - return nil - } - } - - if err != nil { - return err - } - - stateConf := &retry.StateChangeConf{ - Pending: []string{ConfigStatusUnknown, ConfigStatusExists}, - Target: []string{ConfigStatusNotFound}, - Refresh: domainConfigStatus(ctx, conn, domainName), - Timeout: timeout, - MinTimeout: 10 * time.Second, - ContinuousTargetOccurence: 3, - } - - _, err = stateConf.WaitForStateContext(ctx) - - return err -} From c5c1352bfb452056ce5c28e0f28979c9684ded66 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Thu, 22 Aug 2024 14:28:59 -0400 Subject: [PATCH 18/24] r/aws_elasticsearch_vpc_endpoint: Tidy up. --- .../service/elasticsearch/vpc_endpoint.go | 46 ++++++++++++------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/internal/service/elasticsearch/vpc_endpoint.go b/internal/service/elasticsearch/vpc_endpoint.go index 892d33cae507..473dac469470 100644 --- a/internal/service/elasticsearch/vpc_endpoint.go +++ b/internal/service/elasticsearch/vpc_endpoint.go @@ -104,7 +104,7 @@ func resourceVPCEndpointCreate(ctx context.Context, d *schema.ResourceData, meta d.SetId(aws.ToString(output.VpcEndpoint.VpcEndpointId)) - if err := waitVPCEndpointCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + if _, err := waitVPCEndpointCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch VPC Endpoint (%s) create: %s", d.Id(), err) } @@ -155,7 +155,7 @@ func resourceVPCEndpointUpdate(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "updating Elasticsearch VPC Endpoint (%s): %s", d.Id(), err) } - if err := waitVPCEndpointUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + if _, err := waitVPCEndpointUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch VPC Endpoint (%s) update: %s", d.Id(), err) } @@ -179,7 +179,7 @@ func resourceVPCEndpointDelete(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "deleting Elasticsearch VPC Endpoint (%s): %s", d.Id(), err) } - if err := waitVPCEndpointDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + if _, err := waitVPCEndpointDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch VPC Endpoint (%s) delete: %s", d.Id(), err) } @@ -290,41 +290,53 @@ func statusVPCEndpoint(ctx context.Context, conn *elasticsearchservice.Client, i } } -func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { +func waitVPCEndpointCreated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { stateConf := &retry.StateChangeConf{ - Pending: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusCreating), - Target: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusActive), + Pending: enum.Slice(awstypes.VpcEndpointStatusCreating), + Target: enum.Slice(awstypes.VpcEndpointStatusActive), Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } - _, err := stateConf.WaitForStateContext(ctx) + outputRaw, err := stateConf.WaitForStateContext(ctx) - return err + if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { + return output, err + } + + return nil, err } -func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { +func waitVPCEndpointUpdated(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { stateConf := &retry.StateChangeConf{ - Pending: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusUpdating), - Target: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusActive), + Pending: enum.Slice(awstypes.VpcEndpointStatusUpdating), + Target: enum.Slice(awstypes.VpcEndpointStatusActive), Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } - _, err := stateConf.WaitForStateContext(ctx) + outputRaw, err := stateConf.WaitForStateContext(ctx) - return err + if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { + return output, err + } + + return nil, err } -func waitVPCEndpointDeleted(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) error { +func waitVPCEndpointDeleted(ctx context.Context, conn *elasticsearchservice.Client, id string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { stateConf := &retry.StateChangeConf{ - Pending: enum.Slice[awstypes.VpcEndpointStatus](awstypes.VpcEndpointStatusDeleting), + Pending: enum.Slice(awstypes.VpcEndpointStatusDeleting), Target: []string{}, Refresh: statusVPCEndpoint(ctx, conn, id), Timeout: timeout, } - _, err := stateConf.WaitForStateContext(ctx) + outputRaw, err := stateConf.WaitForStateContext(ctx) - return err + if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { + return output, err + } + + return nil, err } From f720a3d1798d29c7ad21118180a43e6200770e2d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 23 Aug 2024 10:24:50 -0400 Subject: [PATCH 19/24] Fix 'TestAccElasticsearchDomainSAMLOptions_disappears_Domain'. --- internal/service/elasticsearch/domain_saml_options.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 6f242ddb1d7b..3f3b2539d29e 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -171,7 +171,7 @@ func resourceDomainSAMLOptionsDelete(ctx context.Context, d *schema.ResourceData DomainName: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) || errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "Domain is being deleted") { return diags } From d13a494f4921dc0be2c9b2c2145a59ce7ba72b8e Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 23 Aug 2024 11:50:08 -0400 Subject: [PATCH 20/24] r/aws_elasticsearch_domain: Tidy up. --- internal/service/elasticsearch/domain.go | 240 +++++------------- .../service/elasticsearch/domain_policy.go | 4 +- .../elasticsearch/domain_saml_options.go | 9 +- 3 files changed, 69 insertions(+), 184 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index e4d1a0cfb1a7..30195f82cf09 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -735,43 +735,15 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf if v := aws.ToString(ds.AccessPolicies); v != "" { policies, err := verify.PolicyToSet(d.Get("access_policies").(string), v) - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Elasticsearch Domain (%s) config: setting policy: %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } d.Set("access_policies", policies) } - - options := advancedOptionsIgnoreDefault(d.Get("advanced_options").(map[string]interface{}), flex.FlattenStringValueMap(ds.AdvancedOptions)) - if err = d.Set("advanced_options", options); err != nil { + if err := d.Set("advanced_options", advancedOptionsIgnoreDefault(d.Get("advanced_options").(map[string]interface{}), flex.FlattenStringValueMap(ds.AdvancedOptions))); err != nil { return sdkdiag.AppendErrorf(diags, "setting advanced_options: %s", err) } - - d.Set("domain_id", ds.DomainId) - d.Set(names.AttrDomainName, ds.DomainName) - d.Set("elasticsearch_version", ds.ElasticsearchVersion) - - if err := d.Set("ebs_options", flattenEBSOptions(ds.EBSOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting ebs_options: %s", err) - } - - if err := d.Set("encrypt_at_rest", flattenEncryptAtRestOptions(ds.EncryptionAtRestOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting encrypt_at_rest: %s", err) - } - - if err := d.Set("cluster_config", flattenElasticsearchClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting cluster_config: %s", err) - } - - if err := d.Set("cognito_options", flattenCognitoOptions(ds.CognitoOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting cognito_options: %s", err) - } - - if err := d.Set("node_to_node_encryption", flattenNodeToNodeEncryptionOptions(ds.NodeToNodeEncryptionOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting node_to_node_encryption: %s", err) - } - // Populate AdvancedSecurityOptions with values returned from // DescribeElasticsearchDomainConfig, if enabled, else use // values from resource; additionally, append MasterUserOptions @@ -787,17 +759,39 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf return sdkdiag.AppendErrorf(diags, "setting advanced_security_options: %s", err) } } - + d.Set(names.AttrARN, ds.ARN) if v := dc.AutoTuneOptions; v != nil { if err := d.Set("auto_tune_options", []interface{}{flattenAutoTuneOptions(v.Options)}); err != nil { return sdkdiag.AppendErrorf(diags, "setting auto_tune_options: %s", err) } } - + if err := d.Set("cluster_config", flattenElasticsearchClusterConfig(ds.ElasticsearchClusterConfig)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting cluster_config: %s", err) + } + if err := d.Set("cognito_options", flattenCognitoOptions(ds.CognitoOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting cognito_options: %s", err) + } + if err := d.Set("domain_endpoint_options", flattenDomainEndpointOptions(ds.DomainEndpointOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting domain_endpoint_options: %s", err) + } + d.Set("domain_id", ds.DomainId) + d.Set(names.AttrDomainName, ds.DomainName) + if err := d.Set("ebs_options", flattenEBSOptions(ds.EBSOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting ebs_options: %s", err) + } + d.Set("elasticsearch_version", ds.ElasticsearchVersion) + if err := d.Set("encrypt_at_rest", flattenEncryptAtRestOptions(ds.EncryptionAtRestOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting encrypt_at_rest: %s", err) + } + if err := d.Set("log_publishing_options", flattenLogPublishingOptions(ds.LogPublishingOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting log_publishing_options: %s", err) + } + if err := d.Set("node_to_node_encryption", flattenNodeToNodeEncryptionOptions(ds.NodeToNodeEncryptionOptions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting node_to_node_encryption: %s", err) + } if err := d.Set("snapshot_options", flattenSnapshotOptions(ds.SnapshotOptions)); err != nil { return sdkdiag.AppendErrorf(diags, "setting snapshot_options: %s", err) } - if ds.VPCOptions != nil { if err := d.Set("vpc_options", []interface{}{flattenVPCDerivedInfo(ds.VPCOptions)}); err != nil { return sdkdiag.AppendErrorf(diags, "setting vpc_options: %s", err) @@ -820,16 +814,6 @@ func resourceDomainRead(ctx context.Context, d *schema.ResourceData, meta interf } } - if err := d.Set("log_publishing_options", flattenLogPublishingOptions(ds.LogPublishingOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting log_publishing_options: %s", err) - } - - if err := d.Set("domain_endpoint_options", flattenDomainEndpointOptions(ds.DomainEndpointOptions)); err != nil { - return sdkdiag.AppendErrorf(diags, "setting domain_endpoint_options: %s", err) - } - - d.Set(names.AttrARN, ds.ARN) - return diags } @@ -868,19 +852,13 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte } if d.HasChanges("ebs_options", "cluster_config") { - options := d.Get("ebs_options").([]interface{}) - - if len(options) == 1 { - s := options[0].(map[string]interface{}) - input.EBSOptions = expandEBSOptions(s) + if v := d.Get("ebs_options").([]interface{}); len(v) == 1 { + input.EBSOptions = expandEBSOptions(v[0].(map[string]interface{})) } if d.HasChange("cluster_config") { - config := d.Get("cluster_config").([]interface{}) - - if len(config) == 1 { - m := config[0].(map[string]interface{}) - input.ElasticsearchClusterConfig = expandElasticsearchClusterConfig(m) + if v := d.Get("cluster_config").([]interface{}); len(v) == 1 { + input.ElasticsearchClusterConfig = expandElasticsearchClusterConfig(v[0].(map[string]interface{})) // Work around "ValidationException: Your domain's Elasticsearch version does not support cold storage options. Upgrade to Elasticsearch 7.9 or later.". if semver.LessThan(d.Get("elasticsearch_version").(string), "7.9") { @@ -893,64 +871,56 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte if d.HasChange("encrypt_at_rest") { input.EncryptionAtRestOptions = nil if v, ok := d.GetOk("encrypt_at_rest"); ok { - options := v.([]interface{}) - if options[0] == nil { + v := v.([]interface{}) + if v[0] == nil { return sdkdiag.AppendErrorf(diags, "At least one field is expected inside encrypt_at_rest") } - s := options[0].(map[string]interface{}) - input.EncryptionAtRestOptions = expandEncryptAtRestOptions(s) + input.EncryptionAtRestOptions = expandEncryptAtRestOptions(v[0].(map[string]interface{})) } } if d.HasChange("node_to_node_encryption") { input.NodeToNodeEncryptionOptions = nil if v, ok := d.GetOk("node_to_node_encryption"); ok { - options := v.([]interface{}) - - s := options[0].(map[string]interface{}) - input.NodeToNodeEncryptionOptions = expandNodeToNodeEncryptionOptions(s) + v := v.([]interface{}) + input.NodeToNodeEncryptionOptions = expandNodeToNodeEncryptionOptions(v[0].(map[string]interface{})) } } if d.HasChange("snapshot_options") { - options := d.Get("snapshot_options").([]interface{}) - - if len(options) == 1 { - o := options[0].(map[string]interface{}) + if v := d.Get("snapshot_options").([]interface{}); len(v) == 1 { + tfMap := v[0].(map[string]interface{}) - snapshotOptions := awstypes.SnapshotOptions{ - AutomatedSnapshotStartHour: aws.Int32(int32(o["automated_snapshot_start_hour"].(int))), + snapshotOptions := &awstypes.SnapshotOptions{ + AutomatedSnapshotStartHour: aws.Int32(int32(tfMap["automated_snapshot_start_hour"].(int))), } - input.SnapshotOptions = &snapshotOptions + input.SnapshotOptions = snapshotOptions } } if d.HasChange("vpc_options") { - options := d.Get("vpc_options").([]interface{}) - s := options[0].(map[string]interface{}) - input.VPCOptions = expandVPCOptions(s) + v := d.Get("vpc_options").([]interface{}) + input.VPCOptions = expandVPCOptions(v[0].(map[string]interface{})) } if d.HasChange("cognito_options") { - options := d.Get("cognito_options").([]interface{}) - input.CognitoOptions = expandCognitoOptions(options) + input.CognitoOptions = expandCognitoOptions(d.Get("cognito_options").([]interface{})) } if d.HasChange("log_publishing_options") { input.LogPublishingOptions = expandLogPublishingOptions(d.Get("log_publishing_options").(*schema.Set)) } - log.Printf("[DEBUG] Updating Elasticsearch Domain config: %+v", input) _, err := conn.UpdateElasticsearchDomainConfig(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "updating Elasticsearch Domain (%s) config: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "updating Elasticsearch Domain (%s) Config: %s", d.Id(), err) } - if err := waitForDomainUpdate(ctx, conn, name, d.Timeout(schema.TimeoutUpdate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + if _, err := waitDomainConfigUpdated(ctx, conn, name, d.Timeout(schema.TimeoutUpdate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) Config update: %s", d.Id(), err) } if d.HasChange("elasticsearch_version") { @@ -959,7 +929,6 @@ func resourceDomainUpdate(ctx context.Context, d *schema.ResourceData, meta inte TargetVersion: aws.String(d.Get("elasticsearch_version").(string)), } - log.Printf("[DEBUG] Upgrading Elasticsearch Domain: %+v", input) _, err := conn.UpgradeElasticsearchDomain(ctx, input) if err != nil { @@ -1057,20 +1026,6 @@ func findDomain(ctx context.Context, conn *elasticsearch.Client, input *elastics return output.DomainStatus, nil } -func findDomainChangeProgressDetailsByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ChangeProgressDetails, error) { - output, err := findDomainByName(ctx, conn, name) - - if err != nil { - return nil, err - } - - if output.ChangeProgressDetails == nil { - return nil, tfresource.NewEmptyResultError(nil) - } - - return output.ChangeProgressDetails, nil -} - func findDomainConfigByName(ctx context.Context, conn *elasticsearch.Client, name string) (*awstypes.ElasticsearchDomainConfig, error) { input := &elasticsearch.DescribeElasticsearchDomainConfigInput{ DomainName: aws.String(name), @@ -1129,9 +1084,9 @@ func findDomainUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, in return output, nil } -func statusDomainConfigChange(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { +func statusDomainProcessing(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := findDomainChangeProgressDetailsByName(ctx, conn, name) + output, err := findDomainByName(ctx, conn, name) if tfresource.NotFound(err) { return nil, "", nil @@ -1141,13 +1096,13 @@ func statusDomainConfigChange(ctx context.Context, conn *elasticsearch.Client, n return nil, "", err } - return output, string(output.ConfigChangeStatus), nil + return output, string(output.DomainProcessingStatus), nil } } -func statusDomainProcessing(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { +func statusDomainUpgrade(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := findDomainByName(ctx, conn, name) + output, err := findDomainUpgradeStatusByName(ctx, conn, name) if tfresource.NotFound(err) { return nil, "", nil @@ -1157,70 +1112,26 @@ func statusDomainProcessing(ctx context.Context, conn *elasticsearch.Client, nam return nil, "", err } - return output, string(output.DomainProcessingStatus), nil - } -} - -const ( - UpgradeStatusUnknown = "Unknown" - ConfigStatusNotFound = "NotFound" - ConfigStatusUnknown = "Unknown" - ConfigStatusExists = "Exists" -) - -func statusUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - out, err := conn.GetUpgradeStatus(ctx, &elasticsearch.GetUpgradeStatusInput{ - DomainName: aws.String(name), - }) - if err != nil { - return nil, UpgradeStatusUnknown, err - } - // Elasticsearch upgrades consist of multiple steps: // https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-version-migration.html // Prevent false positive completion where the UpgradeStep is not the final UPGRADE step. - if out.StepStatus == awstypes.UpgradeStatusSucceeded && out.UpgradeStep != awstypes.UpgradeStepUpgrade { - return out, string(awstypes.UpgradeStatusInProgress), nil - } - - return out, string(out.StepStatus), nil - } -} - -func domainConfigStatus(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - out, err := conn.DescribeElasticsearchDomainConfig(ctx, &elasticsearch.DescribeElasticsearchDomainConfigInput{ - DomainName: aws.String(name), - }) - - if errs.IsA[*awstypes.ResourceNotFoundException](err) { - // if first return value is nil, WaitForState treats as not found - here not found is treated differently - return "not nil", ConfigStatusNotFound, nil - } - - if err != nil { - return nil, ConfigStatusUnknown, err + status := output.StepStatus + if status == awstypes.UpgradeStatusSucceeded && output.UpgradeStep != awstypes.UpgradeStepUpgrade { + status = awstypes.UpgradeStatusInProgress } - return out, ConfigStatusExists, nil + return output, string(status), nil } } -const ( - domainUpgradeSuccessMinTimeout = 10 * time.Second - domainUpgradeSuccessDelay = 30 * time.Second -) - -// UpgradeSucceeded waits for an Upgrade to return Success func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Client, name string, timeout time.Duration) (*elasticsearch.GetUpgradeStatusOutput, error) { stateConf := &retry.StateChangeConf{ - Pending: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusInProgress), - Target: enum.Slice[awstypes.UpgradeStatus](awstypes.UpgradeStatusSucceeded), - Refresh: statusUpgradeStatus(ctx, conn, name), + Pending: enum.Slice(awstypes.UpgradeStatusInProgress), + Target: enum.Slice(awstypes.UpgradeStatusSucceeded), + Refresh: statusDomainUpgrade(ctx, conn, name), Timeout: timeout, - MinTimeout: domainUpgradeSuccessMinTimeout, - Delay: domainUpgradeSuccessDelay, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) @@ -1253,35 +1164,6 @@ func waitDomainCreated(ctx context.Context, conn *elasticsearch.Client, domainNa return nil, err } -func waitForDomainUpdate(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) error { - var out *awstypes.ElasticsearchDomainStatus - err := retry.RetryContext(ctx, timeout, func() *retry.RetryError { - var err error - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - return retry.NonRetryableError(err) - } - - if !aws.ToBool(out.Processing) { - return nil - } - - return retry.RetryableError( - fmt.Errorf("%q: Timeout while waiting for changes to be processed", domainName)) - }) - if tfresource.TimedOut(err) { - out, err = findDomainByName(ctx, conn, domainName) - if err != nil { - return fmt.Errorf("describing Elasticsearch domain: %w", err) - } - if !aws.ToBool(out.Processing) { - return nil - } - } - - return err -} - func waitDomainConfigUpdated(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) (*awstypes.ElasticsearchDomainStatus, error) { stateConf := &retry.StateChangeConf{ Pending: enum.Slice(awstypes.DomainProcessingStatusTypeModifying), diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index 6dbc995ad5e8..52c8878ef051 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -84,8 +84,8 @@ func resourceDomainPolicyUpsert(ctx context.Context, d *schema.ResourceData, met d.SetId("esd-policy-" + domainName) } - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + if _, err := waitDomainConfigUpdated(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) Config update: %s", d.Id(), err) } return append(diags, resourceDomainPolicyRead(ctx, d, meta)...) diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 3f3b2539d29e..c95f21845b52 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -120,7 +120,10 @@ func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, m DomainName: aws.String(domainName), } - _, err := conn.UpdateElasticsearchDomainConfig(ctx, input) + _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.ValidationException](ctx, propagationTimeout, + func() (interface{}, error) { + return conn.UpdateElasticsearchDomainConfig(ctx, input) + }, "A change/update is in progress") if err != nil { return sdkdiag.AppendErrorf(diags, "setting Elasticsearch Domain SAML Options (%s): %s", d.Id(), err) @@ -130,8 +133,8 @@ func resourceDomainSAMLOptionsPut(ctx context.Context, d *schema.ResourceData, m d.SetId(domainName) } - if err := waitForDomainUpdate(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) update: %s", d.Id(), err) + if _, err := waitDomainConfigUpdated(ctx, conn, d.Get(names.AttrDomainName).(string), d.Timeout(schema.TimeoutUpdate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for Elasticsearch Domain (%s) Config update: %s", d.Id(), err) } return append(diags, resourceDomainSAMLOptionsRead(ctx, d, meta)...) From 2840da09d37a3ed97bba28b4aef2e093bdeb9395 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 23 Aug 2024 11:54:02 -0400 Subject: [PATCH 21/24] r/aws_elasticsearch_domain: Treat `SUCCEEDED_WITH_ISSUES` status as success when upgrading cluster. --- .changelog/38086.txt | 6 +++++- internal/service/elasticsearch/domain.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.changelog/38086.txt b/.changelog/38086.txt index 9a14305499e4..846194526f66 100644 --- a/.changelog/38086.txt +++ b/.changelog/38086.txt @@ -1,3 +1,7 @@ -```release-note:enhancement +```release-note:bug resource/aws_elasticsearch_domain_policy: Change `domain_name` to [ForceNew](https://developer.hashicorp.com/terraform/plugin/sdkv2/schemas/schema-behaviors#forcenew) +``` + +```release-note:enhancement +resource/aws_elasticsearch_domain: Treat `SUCCEEDED_WITH_ISSUES` status as success when upgrading cluster ``` \ No newline at end of file diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index 30195f82cf09..d745f73cd25a 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -1127,7 +1127,7 @@ func statusDomainUpgrade(ctx context.Context, conn *elasticsearch.Client, name s func waitUpgradeSucceeded(ctx context.Context, conn *elasticsearch.Client, name string, timeout time.Duration) (*elasticsearch.GetUpgradeStatusOutput, error) { stateConf := &retry.StateChangeConf{ Pending: enum.Slice(awstypes.UpgradeStatusInProgress), - Target: enum.Slice(awstypes.UpgradeStatusSucceeded), + Target: enum.Slice(awstypes.UpgradeStatusSucceeded, awstypes.UpgradeStatusSucceededWithIssues), Refresh: statusDomainUpgrade(ctx, conn, name), Timeout: timeout, MinTimeout: 10 * time.Second, From b989b33336ddcc0e3639369de60074feb66d69ff Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 23 Aug 2024 11:56:55 -0400 Subject: [PATCH 22/24] Fix golangci-lint 'unparam'. --- internal/service/elasticsearch/domain.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index d745f73cd25a..efd9aba7b4c0 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -514,19 +514,16 @@ func resourceDomain() *schema.Resource { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, names.AttrSecurityGroupIDs: { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, names.AttrSubnetIDs: { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, names.AttrVPCID: { Type: schema.TypeString, @@ -1164,7 +1161,7 @@ func waitDomainCreated(ctx context.Context, conn *elasticsearch.Client, domainNa return nil, err } -func waitDomainConfigUpdated(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) (*awstypes.ElasticsearchDomainStatus, error) { +func waitDomainConfigUpdated(ctx context.Context, conn *elasticsearch.Client, domainName string, timeout time.Duration) (*awstypes.ElasticsearchDomainStatus, error) { //nolint:unparam stateConf := &retry.StateChangeConf{ Pending: enum.Slice(awstypes.DomainProcessingStatusTypeModifying), Target: enum.Slice(awstypes.DomainProcessingStatusTypeActive), From 5a493436a57dcb43177a7b32e99ccdef57b8ede5 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 23 Aug 2024 16:28:36 -0400 Subject: [PATCH 23/24] elasticsearch: Migrate sweepers to AWS SDK for Go v2. --- internal/service/elasticsearch/sweep.go | 57 ++++++++----------------- 1 file changed, 18 insertions(+), 39 deletions(-) diff --git a/internal/service/elasticsearch/sweep.go b/internal/service/elasticsearch/sweep.go index 1ca44031c635..2680f4e1db00 100644 --- a/internal/service/elasticsearch/sweep.go +++ b/internal/service/elasticsearch/sweep.go @@ -10,10 +10,9 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice" awstypes "github.com/aws/aws-sdk-go-v2/service/elasticsearchservice/types" - "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/sweep" - "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv1" + "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv2" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -27,59 +26,42 @@ func RegisterSweepers() { func sweepDomains(region string) error { ctx := sweep.Context(region) client, err := sweep.SharedRegionalSweepClient(ctx, region) - if err != nil { return fmt.Errorf("error getting client: %w", err) } - + input := &elasticsearchservice.ListDomainNamesInput{ + EngineType: awstypes.EngineTypeElasticsearch, + } conn := client.ElasticsearchClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - var errs *multierror.Error - input := &elasticsearchservice.ListDomainNamesInput{} - - // ListDomainNames has no pagination support whatsoever output, err := conn.ListDomainNames(ctx, input) - if awsv1.SkipSweepError(err) { + if awsv2.SkipSweepError(err) { log.Printf("[WARN] Skipping Elasticsearch Domain sweep for %s: %s", region, err) - return errs.ErrorOrNil() + return nil } if err != nil { - sweeperErr := fmt.Errorf("error listing Elasticsearch Domains: %w", err) - log.Printf("[ERROR] %s", sweeperErr) - errs = multierror.Append(errs, sweeperErr) - return errs.ErrorOrNil() - } - - if output == nil { - log.Printf("[WARN] Skipping Elasticsearch Domain sweep for %s: empty response", region) - return errs.ErrorOrNil() + return fmt.Errorf("error listing MSK Clusters (%s): %w", region, err) } - for _, domainInfo := range output.DomainNames { - name := aws.ToString(domainInfo.DomainName) + for _, v := range output.DomainNames { + name := aws.ToString(v.DomainName) - if domainInfo.EngineType != awstypes.EngineTypeElasticsearch { - log.Printf("[INFO] Skipping Elasticsearch Domain %s: EngineType = %s", name, string(domainInfo.EngineType)) + if engineType := v.EngineType; engineType != awstypes.EngineTypeElasticsearch { + log.Printf("[INFO] Skipping Elasticsearch Domain %s: EngineType=%s", name, engineType) continue } - // Elasticsearch Domains have regularly gotten stuck in a "being deleted" state - // e.g. Deleted and Processing are both true for days in the API - // Filter out domains that are Deleted already. - output, err := findDomainByName(ctx, conn, name) + if err != nil { - sweeperErr := fmt.Errorf("error describing Elasticsearch Domain (%s): %w", name, err) - log.Printf("[ERROR] %s", sweeperErr) - errs = multierror.Append(errs, sweeperErr) continue } - if output != nil && aws.ToBool(output.Deleted) { - log.Printf("[INFO] Skipping Elasticsearch Domain (%s) with deleted status", name) + if aws.ToBool(output.Deleted) { + log.Printf("[INFO] Skipping Elasticsearch Domain %s: Deleted", name) continue } @@ -91,14 +73,11 @@ func sweepDomains(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } - if err = sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - errs = multierror.Append(errs, fmt.Errorf("error sweeping Elasticsearch Domains for %s: %w", region, err)) - } + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(errs.ErrorOrNil()) { - log.Printf("[WARN] Skipping Elasticsearch Domain sweep for %s: %s", region, errs) - return nil + if err != nil { + return fmt.Errorf("error sweeping Elasticsearch Domains (%s): %w", region, err) } - return errs.ErrorOrNil() + return nil } From f48e9ae65024d8390b7c8683cbe9a72fdf308d79 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Sat, 24 Aug 2024 16:31:06 -0400 Subject: [PATCH 24/24] statusDomainProcessing: Correct handling for deleted clusters. --- internal/service/elasticsearch/domain.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index efd9aba7b4c0..8c32a55fe5ab 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -1083,7 +1083,11 @@ func findDomainUpgradeStatus(ctx context.Context, conn *elasticsearch.Client, in func statusDomainProcessing(ctx context.Context, conn *elasticsearch.Client, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := findDomainByName(ctx, conn, name) + // Don't call findDomainByName here as the domain's Deleted flag will be set while DomainProcessingStatus is "Deleting". + input := &elasticsearch.DescribeElasticsearchDomainInput{ + DomainName: aws.String(name), + } + output, err := findDomain(ctx, conn, input) if tfresource.NotFound(err) { return nil, "", nil