diff --git a/.changelog/37871.txt b/.changelog/37871.txt index b57f9d058cb..01b2077bf9f 100644 --- a/.changelog/37871.txt +++ b/.changelog/37871.txt @@ -1,3 +1,3 @@ -`release-note:enhancement +```release-note:enhancement resource/aws_batch_job_definition: Add `ecs_properties` argument ``` diff --git a/go.mod b/go.mod index 6053937e36b..c15001cae41 100644 --- a/go.mod +++ b/go.mod @@ -168,6 +168,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/oam v1.13.5 github.com/aws/aws-sdk-go-v2/service/opensearch v1.39.3 github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.13.4 + github.com/aws/aws-sdk-go-v2/service/opsworks v1.24.4 github.com/aws/aws-sdk-go-v2/service/organizations v1.30.3 github.com/aws/aws-sdk-go-v2/service/osis v1.12.4 github.com/aws/aws-sdk-go-v2/service/outposts v1.42.1 diff --git a/go.sum b/go.sum index b7278b76b34..5abfa42f422 100644 --- a/go.sum +++ b/go.sum @@ -366,6 +366,8 @@ github.com/aws/aws-sdk-go-v2/service/opensearch v1.39.3 h1:EoXdh45m+CNUmP1tRFz+S github.com/aws/aws-sdk-go-v2/service/opensearch v1.39.3/go.mod h1:dt1En8oUmuPUz5AZjWi+fBeekG3O8WejKi1wgoafwNk= github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.13.4 h1:3Y4N61NHpii/6m38masM+VYJgnHhGtktEyJVZcTv0nc= github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.13.4/go.mod h1:pQOhum5PBwXCSspA6bT4EZLhpawWF2aHTToUu/5vIBg= +github.com/aws/aws-sdk-go-v2/service/opsworks v1.24.4 h1:2bzNoZZWJ8+lRIBfY/FSOdcRIfMYAae9DFwcYxIwD5w= +github.com/aws/aws-sdk-go-v2/service/opsworks v1.24.4/go.mod h1:yjoW6GYtJ1dRtOth68jEL3gYgSXVJicc2Ljcjxt3s/4= github.com/aws/aws-sdk-go-v2/service/organizations v1.30.3 h1:gYS53GRIaSesL04BlZA9MEBzDlENidWR/JDBXhZonFs= github.com/aws/aws-sdk-go-v2/service/organizations v1.30.3/go.mod h1:qdJX3WZbuAan5dXCoinnJjuY1QERCpv3glXeI3+wbeA= github.com/aws/aws-sdk-go-v2/service/osis v1.12.4 h1:D1+hSpaeBVydbHUc86o1Yv3EhOcM0CRazxOokfpC33g= diff --git a/internal/conns/awsclient.go b/internal/conns/awsclient.go index f2a8e401828..4818e47550e 100644 --- a/internal/conns/awsclient.go +++ b/internal/conns/awsclient.go @@ -16,9 +16,7 @@ import ( config_sdkv2 "github.com/aws/aws-sdk-go-v2/config" apigatewayv2_types "github.com/aws/aws-sdk-go-v2/service/apigatewayv2/types" s3_sdkv2 "github.com/aws/aws-sdk-go-v2/service/s3" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - opsworks_sdkv1 "github.com/aws/aws-sdk-go/service/opsworks" baselogging "github.com/hashicorp/aws-sdk-go-base/v2/logging" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/errs" @@ -61,16 +59,6 @@ func (c *AWSClient) AwsConfig(context.Context) aws_sdkv2.Config { // nosemgrep:c return c.awsConfig.Copy() } -// OpsWorksConnForRegion returns an AWS SDK For Go v1 OpsWorks API client for the specified AWS Region. -// If the specified region is not the default a new "simple" client is created. -// This new client does not use any configured endpoint override. -func (c *AWSClient) OpsWorksConnForRegion(ctx context.Context, region string) *opsworks_sdkv1.OpsWorks { - if region == c.Region { - return c.OpsWorksConn(ctx) - } - return opsworks_sdkv1.New(c.session, aws_sdkv1.NewConfig().WithRegion(region)) -} - // PartitionHostname returns a hostname with the provider domain suffix for the partition // e.g. PREFIX.amazonaws.com // The prefix should not contain a trailing period. diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index a7bee9b5e15..27a5cb2552e 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -160,6 +160,7 @@ import ( oam_sdkv2 "github.com/aws/aws-sdk-go-v2/service/oam" opensearch_sdkv2 "github.com/aws/aws-sdk-go-v2/service/opensearch" opensearchserverless_sdkv2 "github.com/aws/aws-sdk-go-v2/service/opensearchserverless" + opsworks_sdkv2 "github.com/aws/aws-sdk-go-v2/service/opsworks" organizations_sdkv2 "github.com/aws/aws-sdk-go-v2/service/organizations" osis_sdkv2 "github.com/aws/aws-sdk-go-v2/service/osis" outposts_sdkv2 "github.com/aws/aws-sdk-go-v2/service/outposts" @@ -241,7 +242,6 @@ import ( lexmodelbuildingservice_sdkv1 "github.com/aws/aws-sdk-go/service/lexmodelbuildingservice" macie2_sdkv1 "github.com/aws/aws-sdk-go/service/macie2" neptune_sdkv1 "github.com/aws/aws-sdk-go/service/neptune" - opsworks_sdkv1 "github.com/aws/aws-sdk-go/service/opsworks" quicksight_sdkv1 "github.com/aws/aws-sdk-go/service/quicksight" simpledb_sdkv1 "github.com/aws/aws-sdk-go/service/simpledb" worklink_sdkv1 "github.com/aws/aws-sdk-go/service/worklink" @@ -905,8 +905,8 @@ func (c *AWSClient) OpenSearchServerlessClient(ctx context.Context) *opensearchs return errs.Must(client[*opensearchserverless_sdkv2.Client](ctx, c, names.OpenSearchServerless, make(map[string]any))) } -func (c *AWSClient) OpsWorksConn(ctx context.Context) *opsworks_sdkv1.OpsWorks { - return errs.Must(conn[*opsworks_sdkv1.OpsWorks](ctx, c, names.OpsWorks, make(map[string]any))) +func (c *AWSClient) OpsWorksClient(ctx context.Context) *opsworks_sdkv2.Client { + return errs.Must(client[*opsworks_sdkv2.Client](ctx, c, names.OpsWorks, make(map[string]any))) } func (c *AWSClient) OrganizationsClient(ctx context.Context) *organizations_sdkv2.Client { diff --git a/internal/service/opsworks/application.go b/internal/service/opsworks/application.go index 73cd1cf6c6e..89f9d95de66 100644 --- a/internal/service/opsworks/application.go +++ b/internal/service/opsworks/application.go @@ -9,21 +9,25 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "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/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_opsworks_application") -func ResourceApplication() *schema.Resource { +// @SDKResource("aws_opsworks_application", name="Application") +func resourceApplication() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceApplicationCreate, @@ -46,9 +50,9 @@ func ResourceApplication() *schema.Resource { ForceNew: true, }, names.AttrType: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(opsworks.AppType_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.AppType](), }, "stack_id": { Type: schema.TypeString, @@ -81,9 +85,11 @@ func ResourceApplication() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ names.AttrType: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(append(opsworks.SourceType_Values(), "other"), false), + Type: schema.TypeString, + Required: true, + // Because the SDK only accepts typed arguments from SourceType, we cannot add `other` even though the API will accept it. + // This service has been deprecated and will only for completeness sake be migrated, will remove the validation as to not cause a client validation exception but rather let AWS API handle it. + //ValidateFunc: validation.StringInSlice(append(opsworks.SourceType_Values(), "other"), false), }, names.AttrURL: { @@ -230,31 +236,32 @@ func resourceApplicationValidate(d *schema.ResourceData) error { return fmt.Errorf("Only one ssl_configuration is permitted.") } - if d.Get(names.AttrType) == opsworks.AppTypeNodejs || d.Get(names.AttrType) == opsworks.AppTypeJava { + attrType := awstypes.AppType(d.Get(names.AttrType).(string)) + if attrType == awstypes.AppTypeNodejs || attrType == awstypes.AppTypeJava { // allowed attributes: none if d.Get("document_root").(string) != "" || d.Get("rails_env").(string) != "" || d.Get("auto_bundle_on_deploy").(string) != "" || d.Get("aws_flow_ruby_settings").(string) != "" { - return fmt.Errorf("No additional attributes are allowed for app type '%s'.", d.Get(names.AttrType).(string)) + return fmt.Errorf("No additional attributes are allowed for app type '%s'.", attrType) } - } else if d.Get(names.AttrType) == opsworks.AppTypeRails { + } else if attrType == awstypes.AppTypeRails { // allowed attributes: document_root, rails_env, auto_bundle_on_deploy if d.Get("aws_flow_ruby_settings").(string) != "" { - return fmt.Errorf("Only 'document_root, rails_env, auto_bundle_on_deploy' are allowed for app type '%s'.", opsworks.AppTypeRails) + return fmt.Errorf("Only 'document_root, rails_env, auto_bundle_on_deploy' are allowed for app type '%s'.", awstypes.AppTypeRails) } // rails_env is required if _, ok := d.GetOk("rails_env"); !ok { return fmt.Errorf("Set rails_env must be set if type is set to rails.") } - } else if d.Get(names.AttrType) == opsworks.AppTypePhp || d.Get(names.AttrType) == opsworks.AppTypeStatic || d.Get(names.AttrType) == opsworks.AppTypeOther { - log.Printf("[DEBUG] the app type is : %s", d.Get(names.AttrType).(string)) + } else if attrType == awstypes.AppTypePhp || attrType == awstypes.AppTypeStatic || attrType == awstypes.AppTypeOther { + log.Printf("[DEBUG] the app type is : %s", attrType) log.Printf("[DEBUG] the attributes are: document_root '%s', rails_env '%s', auto_bundle_on_deploy '%s', aws_flow_ruby_settings '%s'", d.Get("document_root").(string), d.Get("rails_env").(string), d.Get("auto_bundle_on_deploy").(string), d.Get("aws_flow_ruby_settings").(string)) // allowed attributes: document_root if d.Get("rails_env").(string) != "" || d.Get("auto_bundle_on_deploy").(string) != "" || d.Get("aws_flow_ruby_settings").(string) != "" { - return fmt.Errorf("Only 'document_root' is allowed for app type '%s'.", d.Get(names.AttrType).(string)) + return fmt.Errorf("Only 'document_root' is allowed for app type '%s'.", attrType) } - } else if d.Get(names.AttrType) == opsworks.AppTypeAwsFlowRuby { + } else if attrType == awstypes.AppTypeAwsFlowRuby { // allowed attributes: aws_flow_ruby_settings if d.Get("document_root").(string) != "" || d.Get("rails_env").(string) != "" || d.Get("auto_bundle_on_deploy").(string) != "" { - return fmt.Errorf("Only 'aws_flow_ruby_settings' is allowed for app type '%s'.", d.Get(names.AttrType).(string)) + return fmt.Errorf("Only 'aws_flow_ruby_settings' is allowed for app type '%s'.", attrType) } } @@ -263,19 +270,13 @@ func resourceApplicationValidate(d *schema.ResourceData) error { func resourceApplicationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) - - req := &opsworks.DescribeAppsInput{ - AppIds: []*string{ - aws.String(d.Id()), - }, - } + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) log.Printf("[DEBUG] Reading OpsWorks Application: %s", d.Id()) - resp, err := conn.DescribeAppsWithContext(ctx, req) + output, err := findAppByID(ctx, conn, d.Id()) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { log.Printf("[DEBUG] OpsWorks Application (%s) not found", d.Id()) d.SetId("") return diags @@ -285,33 +286,30 @@ func resourceApplicationRead(ctx context.Context, d *schema.ResourceData, meta i return sdkdiag.AppendErrorf(diags, "reading OpsWorks Application (%s): %s", d.Id(), err) } - app := resp.Apps[0] - log.Printf("[DEBUG] Opsworks Application: %#v", app) - - d.Set(names.AttrName, app.Name) - d.Set("stack_id", app.StackId) - d.Set(names.AttrType, app.Type) - d.Set(names.AttrDescription, app.Description) - d.Set("domains", flex.FlattenStringList(app.Domains)) - d.Set("enable_ssl", app.EnableSsl) - err = resourceSetApplicationSSL(d, app.SslConfiguration) + d.Set(names.AttrName, output.Name) + d.Set("stack_id", output.StackId) + d.Set(names.AttrType, output.Type) + d.Set(names.AttrDescription, output.Description) + d.Set("domains", output.Domains) + d.Set("enable_ssl", output.EnableSsl) + err = resourceSetApplicationSSL(d, output.SslConfiguration) if err != nil { return sdkdiag.AppendErrorf(diags, "reading OpsWorks Application (%s): setting ssl_configuration: %s", d.Id(), err) } - err = resourceSetApplicationSource(d, app.AppSource) + err = resourceSetApplicationSource(d, output.AppSource) if err != nil { return sdkdiag.AppendErrorf(diags, "reading OpsWorks Application (%s): setting app_source: %s", d.Id(), err) } - resourceSetApplicationsDataSource(d, app.DataSources) - resourceSetApplicationEnvironmentVariable(d, app.Environment) - resourceSetApplicationAttributes(d, app.Attributes) + resourceSetApplicationsDataSource(d, output.DataSources) + resourceSetApplicationEnvironmentVariable(d, output.Environment) + resourceSetApplicationAttributes(d, output.Attributes) return diags } func resourceApplicationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) err := resourceApplicationValidate(d) if err != nil { @@ -322,9 +320,9 @@ func resourceApplicationCreate(ctx context.Context, d *schema.ResourceData, meta Name: aws.String(d.Get(names.AttrName).(string)), Shortname: aws.String(d.Get("short_name").(string)), StackId: aws.String(d.Get("stack_id").(string)), - Type: aws.String(d.Get(names.AttrType).(string)), + Type: awstypes.AppType(d.Get(names.AttrType).(string)), Description: aws.String(d.Get(names.AttrDescription).(string)), - Domains: flex.ExpandStringList(d.Get("domains").([]interface{})), + Domains: flex.ExpandStringValueList(d.Get("domains").([]interface{})), EnableSsl: aws.Bool(d.Get("enable_ssl").(bool)), SslConfiguration: resourceApplicationSSL(d), AppSource: resourceApplicationSource(d), @@ -333,19 +331,19 @@ func resourceApplicationCreate(ctx context.Context, d *schema.ResourceData, meta Attributes: resourceApplicationAttributes(d), } - resp, err := conn.CreateAppWithContext(ctx, req) + resp, err := conn.CreateApp(ctx, req) if err != nil { return sdkdiag.AppendErrorf(diags, "creating OpsWorks Application: %s", err) } - d.SetId(aws.StringValue(resp.AppId)) + d.SetId(aws.ToString(resp.AppId)) return append(diags, resourceApplicationRead(ctx, d, meta)...) } func resourceApplicationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) err := resourceApplicationValidate(d) if err != nil { @@ -355,9 +353,9 @@ func resourceApplicationUpdate(ctx context.Context, d *schema.ResourceData, meta req := &opsworks.UpdateAppInput{ AppId: aws.String(d.Id()), Name: aws.String(d.Get(names.AttrName).(string)), - Type: aws.String(d.Get(names.AttrType).(string)), + Type: awstypes.AppType(d.Get(names.AttrType).(string)), Description: aws.String(d.Get(names.AttrDescription).(string)), - Domains: flex.ExpandStringList(d.Get("domains").([]interface{})), + Domains: flex.ExpandStringValueList(d.Get("domains").([]interface{})), EnableSsl: aws.Bool(d.Get("enable_ssl").(bool)), SslConfiguration: resourceApplicationSSL(d), AppSource: resourceApplicationSource(d), @@ -368,7 +366,7 @@ func resourceApplicationUpdate(ctx context.Context, d *schema.ResourceData, meta log.Printf("[DEBUG] Updating OpsWorks Application: %s", d.Id()) - _, err = conn.UpdateAppWithContext(ctx, req) + _, err = conn.UpdateApp(ctx, req) if err != nil { return sdkdiag.AppendErrorf(diags, "updating OpsWorks Application (%s): %s", d.Id(), err) } @@ -378,14 +376,14 @@ func resourceApplicationUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceApplicationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) log.Printf("[DEBUG] Deleting OpsWorks Application: %s", d.Id()) - _, err := conn.DeleteAppWithContext(ctx, &opsworks.DeleteAppInput{ + _, err := conn.DeleteApp(ctx, &opsworks.DeleteAppInput{ AppId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -396,16 +394,40 @@ func resourceApplicationDelete(ctx context.Context, d *schema.ResourceData, meta return diags } -func resourceFindEnvironmentVariable(key string, vs []*opsworks.EnvironmentVariable) *opsworks.EnvironmentVariable { +func findAppByID(ctx context.Context, conn *opsworks.Client, id string) (*awstypes.App, error) { + input := &opsworks.DescribeAppsInput{ + AppIds: []string{id}, + } + + output, err := conn.DescribeApps(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.Apps == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return tfresource.AssertSingleValueResult(output.Apps) +} + +func resourceFindEnvironmentVariable(key string, vs []awstypes.EnvironmentVariable) *awstypes.EnvironmentVariable { for _, v := range vs { - if aws.StringValue(v.Key) == key { - return v + if aws.ToString(v.Key) == key { + return &v } } return nil } -func resourceSetApplicationEnvironmentVariable(d *schema.ResourceData, vs []*opsworks.EnvironmentVariable) { +func resourceSetApplicationEnvironmentVariable(d *schema.ResourceData, vs []awstypes.EnvironmentVariable) { if len(vs) == 0 { d.Set(names.AttrEnvironment, nil) return @@ -419,10 +441,10 @@ func resourceSetApplicationEnvironmentVariable(d *schema.ResourceData, vs []*ops for i := 0; i < len(values); i++ { value := values[i].(map[string]interface{}) if v := resourceFindEnvironmentVariable(value[names.AttrKey].(string), vs); v != nil { - if !aws.BoolValue(v.Secure) { - value["secure"] = aws.BoolValue(v.Secure) - value[names.AttrKey] = aws.StringValue(v.Key) - value[names.AttrValue] = aws.StringValue(v.Value) + if !aws.ToBool(v.Secure) { + value["secure"] = aws.ToBool(v.Secure) + value[names.AttrKey] = aws.ToString(v.Key) + value[names.AttrValue] = aws.ToString(v.Value) values[i] = value } } else { @@ -434,14 +456,14 @@ func resourceSetApplicationEnvironmentVariable(d *schema.ResourceData, vs []*ops d.Set(names.AttrEnvironment, values) } -func resourceApplicationEnvironmentVariable(d *schema.ResourceData) []*opsworks.EnvironmentVariable { +func resourceApplicationEnvironmentVariable(d *schema.ResourceData) []awstypes.EnvironmentVariable { environmentVariables := d.Get(names.AttrEnvironment).(*schema.Set).List() - result := make([]*opsworks.EnvironmentVariable, len(environmentVariables)) + result := make([]awstypes.EnvironmentVariable, len(environmentVariables)) for i := 0; i < len(environmentVariables); i++ { env := environmentVariables[i].(map[string]interface{}) - result[i] = &opsworks.EnvironmentVariable{ + result[i] = awstypes.EnvironmentVariable{ Key: aws.String(env[names.AttrKey].(string)), Value: aws.String(env[names.AttrValue].(string)), Secure: aws.Bool(env["secure"].(bool)), @@ -450,14 +472,14 @@ func resourceApplicationEnvironmentVariable(d *schema.ResourceData) []*opsworks. return result } -func resourceApplicationSource(d *schema.ResourceData) *opsworks.Source { +func resourceApplicationSource(d *schema.ResourceData) *awstypes.Source { count := d.Get("app_source.#").(int) if count == 0 { return nil } - return &opsworks.Source{ - Type: aws.String(d.Get("app_source.0.type").(string)), + return &awstypes.Source{ + Type: awstypes.SourceType(d.Get("app_source.0.type").(string)), Url: aws.String(d.Get("app_source.0.url").(string)), Username: aws.String(d.Get("app_source.0.username").(string)), Password: aws.String(d.Get("app_source.0.password").(string)), @@ -466,21 +488,21 @@ func resourceApplicationSource(d *schema.ResourceData) *opsworks.Source { } } -func resourceSetApplicationSource(d *schema.ResourceData, v *opsworks.Source) error { +func resourceSetApplicationSource(d *schema.ResourceData, v *awstypes.Source) error { nv := make([]interface{}, 0, 1) if v != nil { m := make(map[string]interface{}) - if v.Type != nil { - m[names.AttrType] = aws.StringValue(v.Type) - } + + m[names.AttrType] = v.Type + if v.Url != nil { - m[names.AttrURL] = aws.StringValue(v.Url) + m[names.AttrURL] = aws.ToString(v.Url) } if v.Username != nil { - m[names.AttrUsername] = aws.StringValue(v.Username) + m[names.AttrUsername] = aws.ToString(v.Username) } if v.Revision != nil { - m["revision"] = aws.StringValue(v.Revision) + m["revision"] = aws.ToString(v.Revision) } // v.Password and v.SshKey will, on read, contain the placeholder string @@ -495,15 +517,15 @@ func resourceSetApplicationSource(d *schema.ResourceData, v *opsworks.Source) er return d.Set("app_source", nv) } -func resourceApplicationsDataSource(d *schema.ResourceData) []*opsworks.DataSource { +func resourceApplicationsDataSource(d *schema.ResourceData) []awstypes.DataSource { arn := d.Get("data_source_arn").(string) databaseName := d.Get("data_source_database_name").(string) databaseType := d.Get("data_source_type").(string) - result := make([]*opsworks.DataSource, 1) + result := make([]awstypes.DataSource, 1) if len(arn) > 0 || len(databaseName) > 0 || len(databaseType) > 0 { - result[0] = &opsworks.DataSource{ + result[0] = awstypes.DataSource{ Arn: aws.String(arn), DatabaseName: aws.String(databaseName), Type: aws.String(databaseType), @@ -512,7 +534,7 @@ func resourceApplicationsDataSource(d *schema.ResourceData) []*opsworks.DataSour return result } -func resourceSetApplicationsDataSource(d *schema.ResourceData, v []*opsworks.DataSource) { +func resourceSetApplicationsDataSource(d *schema.ResourceData, v []awstypes.DataSource) { d.Set("data_source_arn", nil) d.Set("data_source_database_name", nil) d.Set("data_source_type", nil) @@ -526,34 +548,34 @@ func resourceSetApplicationsDataSource(d *schema.ResourceData, v []*opsworks.Dat d.Set("data_source_type", v[0].Type) } -func resourceApplicationSSL(d *schema.ResourceData) *opsworks.SslConfiguration { +func resourceApplicationSSL(d *schema.ResourceData) *awstypes.SslConfiguration { count := d.Get("ssl_configuration.#").(int) if count == 0 { return nil } - return &opsworks.SslConfiguration{ + return &awstypes.SslConfiguration{ PrivateKey: aws.String(d.Get("ssl_configuration.0.private_key").(string)), Certificate: aws.String(d.Get("ssl_configuration.0.certificate").(string)), Chain: aws.String(d.Get("ssl_configuration.0.chain").(string)), } } -func resourceSetApplicationSSL(d *schema.ResourceData, v *opsworks.SslConfiguration) error { +func resourceSetApplicationSSL(d *schema.ResourceData, v *awstypes.SslConfiguration) error { nv := make([]interface{}, 0, 1) set := false if v != nil { m := make(map[string]interface{}) if v.PrivateKey != nil { - m[names.AttrPrivateKey] = aws.StringValue(v.PrivateKey) + m[names.AttrPrivateKey] = aws.ToString(v.PrivateKey) set = true } if v.Certificate != nil { - m[names.AttrCertificate] = aws.StringValue(v.Certificate) + m[names.AttrCertificate] = aws.ToString(v.Certificate) set = true } if v.Chain != nil { - m["chain"] = aws.StringValue(v.Chain) + m["chain"] = aws.ToString(v.Chain) set = true } if set { @@ -564,17 +586,17 @@ func resourceSetApplicationSSL(d *schema.ResourceData, v *opsworks.SslConfigurat return d.Set("ssl_configuration", nv) } -func resourceApplicationAttributes(d *schema.ResourceData) map[string]*string { - attributes := make(map[string]*string) +func resourceApplicationAttributes(d *schema.ResourceData) map[string]string { + attributes := make(map[string]string) if val := d.Get("document_root").(string); len(val) > 0 { - attributes[opsworks.AppAttributesKeysDocumentRoot] = aws.String(val) + attributes[string(awstypes.AppAttributesKeysDocumentRoot)] = val } if val := d.Get("aws_flow_ruby_settings").(string); len(val) > 0 { - attributes[opsworks.AppAttributesKeysAwsFlowRubySettings] = aws.String(val) + attributes[string(awstypes.AppAttributesKeysAwsFlowRubySettings)] = val } if val := d.Get("rails_env").(string); len(val) > 0 { - attributes[opsworks.AppAttributesKeysRailsEnv] = aws.String(val) + attributes[string(awstypes.AppAttributesKeysRailsEnv)] = val } if val := d.Get("auto_bundle_on_deploy").(string); len(val) > 0 { if val == "1" { @@ -582,38 +604,39 @@ func resourceApplicationAttributes(d *schema.ResourceData) map[string]*string { } else if val == "0" { val = "false" } - attributes[opsworks.AppAttributesKeysAutoBundleOnDeploy] = aws.String(val) + attributes[string(awstypes.AppAttributesKeysAutoBundleOnDeploy)] = val } return attributes } -func resourceSetApplicationAttributes(d *schema.ResourceData, v map[string]*string) { +func resourceSetApplicationAttributes(d *schema.ResourceData, v map[string]string) { d.Set("document_root", nil) d.Set("rails_env", nil) d.Set("aws_flow_ruby_settings", nil) d.Set("auto_bundle_on_deploy", nil) - if d.Get(names.AttrType) == opsworks.AppTypeNodejs || d.Get(names.AttrType) == opsworks.AppTypeJava { + attrType := d.Get(names.AttrType) + if attrType == awstypes.AppTypeNodejs || attrType == awstypes.AppTypeJava { return - } else if d.Get(names.AttrType) == opsworks.AppTypeRails { - if val, ok := v[opsworks.AppAttributesKeysDocumentRoot]; ok { + } else if attrType == awstypes.AppTypeRails { + if val, ok := v[string(awstypes.AppAttributesKeysDocumentRoot)]; ok { d.Set("document_root", val) } - if val, ok := v[opsworks.AppAttributesKeysRailsEnv]; ok { + if val, ok := v[string(awstypes.AppAttributesKeysRailsEnv)]; ok { d.Set("rails_env", val) } - if val, ok := v[opsworks.AppAttributesKeysAutoBundleOnDeploy]; ok { + if val, ok := v[string(awstypes.AppAttributesKeysAutoBundleOnDeploy)]; ok { d.Set("auto_bundle_on_deploy", val) } return - } else if d.Get(names.AttrType) == opsworks.AppTypePhp || d.Get(names.AttrType) == opsworks.AppTypeStatic || d.Get(names.AttrType) == opsworks.AppTypeOther { - if val, ok := v[opsworks.AppAttributesKeysDocumentRoot]; ok { + } else if attrType == awstypes.AppTypePhp || attrType == awstypes.AppTypeStatic || attrType == awstypes.AppTypeOther { + if val, ok := v[string(awstypes.AppAttributesKeysDocumentRoot)]; ok { d.Set("document_root", val) } return - } else if d.Get(names.AttrType) == opsworks.AppTypeAwsFlowRuby { - if val, ok := v[opsworks.AppAttributesKeysAwsFlowRubySettings]; ok { + } else if attrType == awstypes.AppTypeAwsFlowRuby { + if val, ok := v[string(awstypes.AppAttributesKeysAwsFlowRubySettings)]; ok { d.Set("aws_flow_ruby_settings", val) } return diff --git a/internal/service/opsworks/application_test.go b/internal/service/opsworks/application_test.go index 570c120c335..d2d51e38fe6 100644 --- a/internal/service/opsworks/application_test.go +++ b/internal/service/opsworks/application_test.go @@ -9,26 +9,29 @@ import ( "reflect" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfopsworks "github.com/hashicorp/terraform-provider-aws/internal/service/opsworks" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) func TestAccOpsWorksApplication_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var opsapp opsworks.App + var opsapp awstypes.App rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_application.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckApplicationDestroy(ctx), @@ -97,8 +100,33 @@ func TestAccOpsWorksApplication_basic(t *testing.T) { }) } -func testAccCheckApplicationExists(ctx context.Context, - n string, opsapp *opsworks.App) resource.TestCheckFunc { +func testAccCheckApplicationDestroy(ctx context.Context) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_opsworks_application" { + continue + } + + _, err := tfopsworks.FindAppByID(ctx, conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("OpsWorks Application %s still exists", rs.Primary.ID) + } + + return nil + } +} + +func testAccCheckApplicationExists(ctx context.Context, n string, opsapp *awstypes.App) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -106,50 +134,42 @@ func testAccCheckApplicationExists(ctx context.Context, } if rs.Primary.ID == "" { - return fmt.Errorf("No ID is set") + return fmt.Errorf("No OpsWorks Channel with that ID exists") } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) - params := &opsworks.DescribeAppsInput{ - AppIds: []*string{&rs.Primary.ID}, - } - resp, err := conn.DescribeAppsWithContext(ctx, params) + output, err := tfopsworks.FindAppByID(ctx, conn, rs.Primary.ID) if err != nil { return err } - if v := len(resp.Apps); v != 1 { - return fmt.Errorf("Expected 1 response returned, got %d", v) - } - - *opsapp = *resp.Apps[0] + *opsapp = *output return nil } } -func testAccCheckCreateAppAttributes( - opsapp *opsworks.App) resource.TestCheckFunc { +func testAccCheckCreateAppAttributes(opsapp *awstypes.App) resource.TestCheckFunc { return func(s *terraform.State) error { - if *opsapp.EnableSsl { + if aws.ToBool(opsapp.EnableSsl) { return fmt.Errorf("Unexpected enable ssl: %t", *opsapp.EnableSsl) } - if *opsapp.Attributes["DocumentRoot"] != "foo" { - return fmt.Errorf("Unnexpected document root: %s", *opsapp.Attributes["DocumentRoot"]) + if opsapp.Attributes["DocumentRoot"] != "foo" { + return fmt.Errorf("Unexpected document root: %s", opsapp.Attributes["DocumentRoot"]) } - if *opsapp.Type != opsworks.AppTypeOther { - return fmt.Errorf("Unnexpected type: %s", *opsapp.Type) + if opsapp.Type != awstypes.AppTypeOther { + return fmt.Errorf("Unexpected type: %s", opsapp.Type) } - if *opsapp.AppSource.Type != "other" { - return fmt.Errorf("Unnexpected appsource type: %s", *opsapp.AppSource.Type) + if opsapp.AppSource.Type != "other" { + return fmt.Errorf("Unexpected appsource type: %s", opsapp.AppSource.Type) } - expectedEnv := []*opsworks.EnvironmentVariable{ + expectedEnv := []*awstypes.EnvironmentVariable{ { Key: aws.String(acctest.CtKey1), Value: aws.String(acctest.CtValue1), @@ -158,7 +178,7 @@ func testAccCheckCreateAppAttributes( } if !reflect.DeepEqual(expectedEnv, opsapp.Environment) { - return fmt.Errorf("Unnexpected environment: %s", opsapp.Environment) + return fmt.Errorf("Unexpected environment: %#v", opsapp.Environment) } if v := len(opsapp.Domains); v != 0 { @@ -169,23 +189,22 @@ func testAccCheckCreateAppAttributes( } } -func testAccCheckUpdateAppAttributes( - opsapp *opsworks.App) resource.TestCheckFunc { +func testAccCheckUpdateAppAttributes(opsapp *awstypes.App) resource.TestCheckFunc { return func(s *terraform.State) error { - if *opsapp.Type != "rails" { - return fmt.Errorf("Unnexpected type: %s", *opsapp.Type) + if opsapp.Type != awstypes.AppTypeRails { + return fmt.Errorf("Unexpected type: %s", opsapp.Type) } - if !*opsapp.EnableSsl { - return fmt.Errorf("Unexpected enable ssl: %t", *opsapp.EnableSsl) + if !aws.ToBool(opsapp.EnableSsl) { + return fmt.Errorf("Unexpected enable ssl: %t", aws.ToBool(opsapp.EnableSsl)) } - if *opsapp.SslConfiguration.Certificate != "-----BEGIN CERTIFICATE-----\nMIIBkDCB+gIJALoScFD0sJq3MA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNVBAYTAkRF\nMB4XDTE1MTIxOTIwMzU1MVoXDTE2MDExODIwMzU1MVowDTELMAkGA1UEBhMCREUw\ngZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKKQKbTTH/Julz16xY7ArYlzJYCP\nedTCx1bopuryCx/+d1gC94MtRdlPSpQl8mfc9iBdtXbJppp73Qh/DzLzO9Ns25xZ\n+kUQMhbIyLsaCBzuEGLgAaVdGpNvRBw++UoYtd0U7QczFAreTGLH8n8+FIzuI5Mc\n+MJ1TKbbt5gFfRSzAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEALARo96wCDmaHKCaX\nS0IGLGnZCfiIUfCmBxOXBSJxDBwter95QHR0dMGxYIujee5n4vvavpVsqZnfMC3I\nOZWPlwiUJbNIpK+04Bg2vd5m/NMMrvi75RfmyeMtSfq/NrIX2Q3+nyWI7DLq7yZI\nV/YEvOqdAiy5NEWBztHx8HvB9G4=\n-----END CERTIFICATE-----" { - return fmt.Errorf("Unexpected ssl configuration certificate: %s", *opsapp.SslConfiguration.Certificate) + if aws.ToString(opsapp.SslConfiguration.Certificate) != "-----BEGIN CERTIFICATE-----\nMIIBkDCB+gIJALoScFD0sJq3MA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNVBAYTAkRF\nMB4XDTE1MTIxOTIwMzU1MVoXDTE2MDExODIwMzU1MVowDTELMAkGA1UEBhMCREUw\ngZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKKQKbTTH/Julz16xY7ArYlzJYCP\nedTCx1bopuryCx/+d1gC94MtRdlPSpQl8mfc9iBdtXbJppp73Qh/DzLzO9Ns25xZ\n+kUQMhbIyLsaCBzuEGLgAaVdGpNvRBw++UoYtd0U7QczFAreTGLH8n8+FIzuI5Mc\n+MJ1TKbbt5gFfRSzAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEALARo96wCDmaHKCaX\nS0IGLGnZCfiIUfCmBxOXBSJxDBwter95QHR0dMGxYIujee5n4vvavpVsqZnfMC3I\nOZWPlwiUJbNIpK+04Bg2vd5m/NMMrvi75RfmyeMtSfq/NrIX2Q3+nyWI7DLq7yZI\nV/YEvOqdAiy5NEWBztHx8HvB9G4=\n-----END CERTIFICATE-----" { + return fmt.Errorf("Unexpected ssl configuration certificate: %#v", opsapp.SslConfiguration.Certificate) } - if *opsapp.SslConfiguration.PrivateKey != "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQCikCm00x/ybpc9esWOwK2JcyWAj3nUwsdW6Kbq8gsf/ndYAveD\nLUXZT0qUJfJn3PYgXbV2yaaae90Ifw8y8zvTbNucWfpFEDIWyMi7Gggc7hBi4AGl\nXRqTb0QcPvlKGLXdFO0HMxQK3kxix/J/PhSM7iOTHPjCdUym27eYBX0UswIDAQAB\nAoGBAIYcrvuqDboguI8U4TUjCkfSAgds1pLLWk79wu8jXkA329d1IyNKT0y3WIye\nPbyoEzmidZmZROQ/+ZsPz8c12Y0DrX73WSVzKNyJeP7XMk9HSzA1D9RX0U0S+5Kh\nFAMc2NEVVFIfQtVtoVmHdKDpnRYtOCHLW9rRpvqOOjd4mYk5AkEAzeiFr1mtlnsa\n67shMxzDaOTAFMchRz6G7aSovvCztxcB63ulFI/w9OTUMdTQ7ff7pet+lVihLc2W\nefIL0HvsjQJBAMocNTKaR/TnsV5GSk2kPAdR+zFP5sQy8sfMy0lEXTylc7zN4ajX\nMeHVoxp+GZgpfDcZ3ya808H1umyXh+xA1j8CQE9x9ZKQYT98RAjL7KVR5btk9w+N\nPTPF1j1+mHUDXfO4ds8qp6jlWKzEVXLcj7ghRADiebaZuaZ4eiSW1SQdjEkCQQC4\nwDhQ3X9RfEpCp3ZcqvjEqEg6t5N3XitYQPjDLN8eBRBbUsgpEy3iBuxl10eGNMX7\niIbYXlwkPYAArDPv3wT5AkAwp4vym+YKmDqh6gseKfRDuJqRiW9yD5A8VGr/w88k\n5rkuduVGP7tK3uIp00Its3aEyKF8mLGWYszVGeeLxAMH\n-----END RSA PRIVATE KEY-----" { - return fmt.Errorf("Unexpected ssl configuration private key: %s", *opsapp.SslConfiguration.PrivateKey) + if aws.ToString(opsapp.SslConfiguration.PrivateKey) != "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQCikCm00x/ybpc9esWOwK2JcyWAj3nUwsdW6Kbq8gsf/ndYAveD\nLUXZT0qUJfJn3PYgXbV2yaaae90Ifw8y8zvTbNucWfpFEDIWyMi7Gggc7hBi4AGl\nXRqTb0QcPvlKGLXdFO0HMxQK3kxix/J/PhSM7iOTHPjCdUym27eYBX0UswIDAQAB\nAoGBAIYcrvuqDboguI8U4TUjCkfSAgds1pLLWk79wu8jXkA329d1IyNKT0y3WIye\nPbyoEzmidZmZROQ/+ZsPz8c12Y0DrX73WSVzKNyJeP7XMk9HSzA1D9RX0U0S+5Kh\nFAMc2NEVVFIfQtVtoVmHdKDpnRYtOCHLW9rRpvqOOjd4mYk5AkEAzeiFr1mtlnsa\n67shMxzDaOTAFMchRz6G7aSovvCztxcB63ulFI/w9OTUMdTQ7ff7pet+lVihLc2W\nefIL0HvsjQJBAMocNTKaR/TnsV5GSk2kPAdR+zFP5sQy8sfMy0lEXTylc7zN4ajX\nMeHVoxp+GZgpfDcZ3ya808H1umyXh+xA1j8CQE9x9ZKQYT98RAjL7KVR5btk9w+N\nPTPF1j1+mHUDXfO4ds8qp6jlWKzEVXLcj7ghRADiebaZuaZ4eiSW1SQdjEkCQQC4\nwDhQ3X9RfEpCp3ZcqvjEqEg6t5N3XitYQPjDLN8eBRBbUsgpEy3iBuxl10eGNMX7\niIbYXlwkPYAArDPv3wT5AkAwp4vym+YKmDqh6gseKfRDuJqRiW9yD5A8VGr/w88k\n5rkuduVGP7tK3uIp00Its3aEyKF8mLGWYszVGeeLxAMH\n-----END RSA PRIVATE KEY-----" { + return fmt.Errorf("Unexpected ssl configuration private key: %#v", opsapp.SslConfiguration.PrivateKey) } expectedAttrs := map[string]*string{ @@ -196,20 +215,20 @@ func testAccCheckUpdateAppAttributes( } if !reflect.DeepEqual(expectedAttrs, opsapp.Attributes) { - return fmt.Errorf("Unnexpected Attributes: %v", aws.StringValueMap(opsapp.Attributes)) + return fmt.Errorf("Unnexpected Attributes: %v", aws.StringMap(opsapp.Attributes)) } - expectedAppSource := &opsworks.Source{ - Type: aws.String("git"), + expectedAppSource := &awstypes.Source{ + Type: awstypes.SourceTypeGit, Revision: aws.String("master"), Url: aws.String("https://github.com/aws/example.git"), } if !reflect.DeepEqual(expectedAppSource, opsapp.AppSource) { - return fmt.Errorf("Unnexpected appsource: %s", opsapp.AppSource) + return fmt.Errorf("Unnexpected appsource: %#v", opsapp.AppSource) } - expectedEnv := []*opsworks.EnvironmentVariable{ + expectedEnv := []*awstypes.EnvironmentVariable{ { Key: aws.String(acctest.CtKey2), Value: aws.String("*****FILTERED*****"), @@ -223,7 +242,7 @@ func testAccCheckUpdateAppAttributes( } if !reflect.DeepEqual(expectedEnv, opsapp.Environment) { - return fmt.Errorf("Unnexpected environment: %s", opsapp.Environment) + return fmt.Errorf("Unnexpected environment: %#v", opsapp.Environment) } expectedDomains := []*string{ @@ -232,38 +251,7 @@ func testAccCheckUpdateAppAttributes( } if !reflect.DeepEqual(expectedDomains, opsapp.Domains) { - return fmt.Errorf("Unnexpected Daomins : %v", aws.StringValueSlice(opsapp.Domains)) - } - - return nil - } -} - -func testAccCheckApplicationDestroy(ctx context.Context) resource.TestCheckFunc { - return func(s *terraform.State) error { - client := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) - - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_opsworks_application" { - continue - } - - req := &opsworks.DescribeAppsInput{ - AppIds: []*string{ - aws.String(rs.Primary.ID), - }, - } - - resp, err := client.DescribeAppsWithContext(ctx, req) - if err == nil { - if len(resp.Apps) > 0 { - return fmt.Errorf("OpsWorks App still exist.") - } - } - - if !tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { - return err - } + return fmt.Errorf("Unnexpected Daomins : %v", aws.StringSlice(opsapp.Domains)) } return nil diff --git a/internal/service/opsworks/custom_layer.go b/internal/service/opsworks/custom_layer.go index c6d12dbaa89..a2852e4d453 100644 --- a/internal/service/opsworks/custom_layer.go +++ b/internal/service/opsworks/custom_layer.go @@ -4,15 +4,15 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_custom_layer", name="Custom Layer") // @Tags(identifierAttribute="arn") -func ResourceCustomLayer() *schema.Resource { +func resourceCustomLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeCustom, + TypeName: awstypes.LayerTypeCustom, CustomShortName: true, // The "custom" layer type has no additional attributes. diff --git a/internal/service/opsworks/custom_layer_test.go b/internal/service/opsworks/custom_layer_test.go index 069c96ef729..58717db377e 100644 --- a/internal/service/opsworks/custom_layer_test.go +++ b/internal/service/opsworks/custom_layer_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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,13 +18,15 @@ import ( ) func TestAccOpsWorksCustomLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_custom_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckCustomLayerDestroy(ctx), @@ -78,16 +80,16 @@ func TestAccOpsWorksCustomLayer_basic(t *testing.T) { }) } -// _disappears and _tags for OpsWorks Layers are tested via aws_opsworks_rails_app_layer. - func TestAccOpsWorksCustomLayer_update(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_custom_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckCustomLayerDestroy(ctx), @@ -154,14 +156,16 @@ func TestAccOpsWorksCustomLayer_update(t *testing.T) { } func TestAccOpsWorksCustomLayer_cloudWatch(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_custom_layer.test" logGroupResourceName := "aws_cloudwatch_log_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckCustomLayerDestroy(ctx), @@ -237,13 +241,15 @@ func TestAccOpsWorksCustomLayer_cloudWatch(t *testing.T) { } func TestAccOpsWorksCustomLayer_loadBasedAutoScaling(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_custom_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckCustomLayerDestroy(ctx), diff --git a/internal/service/opsworks/ecs_cluster_layer.go b/internal/service/opsworks/ecs_cluster_layer.go index f596028940f..54b0569fb64 100644 --- a/internal/service/opsworks/ecs_cluster_layer.go +++ b/internal/service/opsworks/ecs_cluster_layer.go @@ -4,21 +4,21 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) // @SDKResource("aws_opsworks_ecs_cluster_layer", name="ECS Cluster Layer") // @Tags(identifierAttribute="arn") -func ResourceECSClusterLayer() *schema.Resource { +func resourceECSClusterLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeEcsCluster, + TypeName: awstypes.LayerTypeEcsCluster, DefaultLayerName: "Ecs Cluster", Attributes: map[string]*opsworksLayerTypeAttribute{ "ecs_cluster_arn": { - AttrName: opsworks.LayerAttributesKeysEcsClusterArn, + AttrName: awstypes.LayerAttributesKeysEcsClusterArn, Type: schema.TypeString, Required: true, ForceNew: true, diff --git a/internal/service/opsworks/ecs_cluster_layer_test.go b/internal/service/opsworks/ecs_cluster_layer_test.go index 2391d6f45da..3fcc1f0d2f9 100644 --- a/internal/service/opsworks/ecs_cluster_layer_test.go +++ b/internal/service/opsworks/ecs_cluster_layer_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -17,13 +17,15 @@ import ( ) func TestAccOpsWorksECSClusterLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer stackName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_ecs_cluster_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckECSClusterLayerDestroy(ctx), @@ -40,8 +42,6 @@ func TestAccOpsWorksECSClusterLayer_basic(t *testing.T) { }) } -// _disappears and _tags for OpsWorks Layers are tested via aws_opsworks_rails_app_layer. - func testAccCheckECSClusterLayerDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { return testAccCheckLayerDestroy(ctx, "aws_opsworks_ecs_cluster_layer", s) diff --git a/internal/service/opsworks/exports_test.go b/internal/service/opsworks/exports_test.go new file mode 100644 index 00000000000..bd103f625f5 --- /dev/null +++ b/internal/service/opsworks/exports_test.go @@ -0,0 +1,20 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package opsworks + +// Exports for use in tests only. +var ( + ResourceRailsAppLayer = resourceRailsAppLayer + ResourceRDSDBInstance = resourceRDSDBInstance + ResourceStack = resourceStack + ResourceUserProfile = resourceUserProfile + + FindAppByID = findAppByID + FindInstanceByID = findInstanceByID + FindLayerByID = findLayerByID + FindPermissionByTwoPartKey = findPermissionByTwoPartKey + FindRDSDBInstanceByTwoPartKey = findRDSDBInstanceByTwoPartKey + FindStackByID = findStackByID + FindUserProfileByARN = findUserProfileByARN +) diff --git a/internal/service/opsworks/ganglia_layer.go b/internal/service/opsworks/ganglia_layer.go index 80b3bf70bde..f7fb4154a3f 100644 --- a/internal/service/opsworks/ganglia_layer.go +++ b/internal/service/opsworks/ganglia_layer.go @@ -4,32 +4,32 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_opsworks_ganglia_layer", name="Ganglia Layer") // @Tags(identifierAttribute="arn") -func ResourceGangliaLayer() *schema.Resource { +func resourceGangliaLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeMonitoringMaster, + TypeName: awstypes.LayerTypeMonitoringMaster, DefaultLayerName: "Ganglia", Attributes: map[string]*opsworksLayerTypeAttribute{ names.AttrPassword: { - AttrName: opsworks.LayerAttributesKeysGangliaPassword, + AttrName: awstypes.LayerAttributesKeysGangliaPassword, Type: schema.TypeString, Required: true, WriteOnly: true, }, names.AttrURL: { - AttrName: opsworks.LayerAttributesKeysGangliaUrl, + AttrName: awstypes.LayerAttributesKeysGangliaUrl, Type: schema.TypeString, Default: "/ganglia", }, names.AttrUsername: { - AttrName: opsworks.LayerAttributesKeysGangliaUser, + AttrName: awstypes.LayerAttributesKeysGangliaUser, Type: schema.TypeString, Default: "opsworks", }, diff --git a/internal/service/opsworks/ganglia_layer_test.go b/internal/service/opsworks/ganglia_layer_test.go index 4bfa30c8d67..fe98efec061 100644 --- a/internal/service/opsworks/ganglia_layer_test.go +++ b/internal/service/opsworks/ganglia_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksGangliaLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_ganglia_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckGangliaLayerDestroy(ctx), diff --git a/internal/service/opsworks/generate.go b/internal/service/opsworks/generate.go index 5d496a90d2f..6bbefcc4ddc 100644 --- a/internal/service/opsworks/generate.go +++ b/internal/service/opsworks/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 -ServiceTagsMap -UpdateTags -CreateTags +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ListTags -ListTagsOp=ListTags -ServiceTagsMap -UpdateTags -CreateTags -SkipTypesImp -KVTValues //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/opsworks/haproxy_layer.go b/internal/service/opsworks/haproxy_layer.go index 485f6e8c599..9cb0f465726 100644 --- a/internal/service/opsworks/haproxy_layer.go +++ b/internal/service/opsworks/haproxy_layer.go @@ -4,46 +4,46 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_haproxy_layer", name="HAProxy Layer") // @Tags(identifierAttribute="arn") -func ResourceHAProxyLayer() *schema.Resource { +func resourceHAProxyLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeLb, + TypeName: awstypes.LayerTypeLb, DefaultLayerName: "HAProxy", Attributes: map[string]*opsworksLayerTypeAttribute{ "healthcheck_method": { - AttrName: opsworks.LayerAttributesKeysHaproxyHealthCheckMethod, + AttrName: awstypes.LayerAttributesKeysHaproxyHealthCheckMethod, Type: schema.TypeString, Default: "OPTIONS", }, "healthcheck_url": { - AttrName: opsworks.LayerAttributesKeysHaproxyHealthCheckUrl, + AttrName: awstypes.LayerAttributesKeysHaproxyHealthCheckUrl, Type: schema.TypeString, Default: "/", }, "stats_enabled": { - AttrName: opsworks.LayerAttributesKeysEnableHaproxyStats, + AttrName: awstypes.LayerAttributesKeysEnableHaproxyStats, Type: schema.TypeBool, Default: true, }, "stats_password": { - AttrName: opsworks.LayerAttributesKeysHaproxyStatsPassword, + AttrName: awstypes.LayerAttributesKeysHaproxyStatsPassword, Type: schema.TypeString, WriteOnly: true, Required: true, }, "stats_url": { - AttrName: opsworks.LayerAttributesKeysHaproxyStatsUrl, + AttrName: awstypes.LayerAttributesKeysHaproxyStatsUrl, Type: schema.TypeString, Default: "/haproxy?stats", }, "stats_user": { - AttrName: opsworks.LayerAttributesKeysHaproxyStatsUser, + AttrName: awstypes.LayerAttributesKeysHaproxyStatsUser, Type: schema.TypeString, Default: "opsworks", }, diff --git a/internal/service/opsworks/haproxy_layer_test.go b/internal/service/opsworks/haproxy_layer_test.go index 64233cefbc7..b5c86c096bf 100644 --- a/internal/service/opsworks/haproxy_layer_test.go +++ b/internal/service/opsworks/haproxy_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksHAProxyLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_haproxy_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckHAProxyLayerDestroy(ctx), diff --git a/internal/service/opsworks/instance.go b/internal/service/opsworks/instance.go index b4ae6ff6526..ad18f4ce955 100644 --- a/internal/service/opsworks/instance.go +++ b/internal/service/opsworks/instance.go @@ -10,22 +10,25 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "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/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_opsworks_instance") -func ResourceInstance() *schema.Resource { +// @SDKResource("aws_opsworks_instance", name="Instance") +func resourceInstance() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceInstanceCreate, ReadWithoutTimeout: resourceInstanceRead, @@ -56,16 +59,16 @@ func ResourceInstance() *schema.Resource { }, "architecture": { - Type: schema.TypeString, - Optional: true, - Default: "x86_64", - ValidateFunc: validation.StringInSlice(opsworks.Architecture_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: "x86_64", + ValidateDiagFunc: enum.Validate[awstypes.Architecture](), }, "auto_scaling_type": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice(opsworks.AutoScalingType_Values(), false), + Type: schema.TypeString, + Optional: true, + ValidateDiagFunc: enum.Validate[awstypes.AutoScalingType](), }, names.AttrAvailabilityZone: { @@ -216,11 +219,11 @@ func ResourceInstance() *schema.Resource { }, "root_device_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Computed: true, - ValidateFunc: validation.StringInSlice(opsworks.RootDeviceType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.RootDeviceType](), }, "root_device_volume_id": { @@ -292,11 +295,11 @@ func ResourceInstance() *schema.Resource { }, "virtualization_type": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(opsworks.VirtualizationType_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.VirtualizationType](), }, "ebs_block_device": { @@ -460,19 +463,11 @@ func resourceInstanceValidate(d *schema.ResourceData) error { func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) - req := &opsworks.DescribeInstancesInput{ - InstanceIds: []*string{ - aws.String(d.Id()), - }, - } - - log.Printf("[DEBUG] Reading OpsWorks instance: %s", d.Id()) + output, err := findInstanceByID(ctx, conn, d.Id()) - resp, err := conn.DescribeInstancesWithContext(ctx, req) - - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] OpsWorks instance %s not found, removing from state", d.Id()) d.SetId("") return diags @@ -482,67 +477,54 @@ func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta inte return sdkdiag.AppendErrorf(diags, "reading OpsWorks Instance (%s): %s", d.Id(), err) } - // If nothing was found, then return no state - if len(resp.Instances) == 0 || resp.Instances[0] == nil || resp.Instances[0].InstanceId == nil { - log.Printf("[WARN] OpsWorks instance %s not found, removing from state", d.Id()) - d.SetId("") - return diags - } - - instance := resp.Instances[0] - - d.SetId(aws.StringValue(instance.InstanceId)) - d.Set("agent_version", instance.AgentVersion) - d.Set("ami_id", instance.AmiId) - d.Set("architecture", instance.Architecture) - d.Set("auto_scaling_type", instance.AutoScalingType) - d.Set(names.AttrAvailabilityZone, instance.AvailabilityZone) - d.Set(names.AttrCreatedAt, instance.CreatedAt) - d.Set("ebs_optimized", instance.EbsOptimized) - d.Set("ec2_instance_id", instance.Ec2InstanceId) - d.Set("ecs_cluster_arn", instance.EcsClusterArn) - d.Set("elastic_ip", instance.ElasticIp) - d.Set("hostname", instance.Hostname) - d.Set("infrastructure_class", instance.InfrastructureClass) - d.Set("install_updates_on_boot", instance.InstallUpdatesOnBoot) - d.Set("instance_profile_arn", instance.InstanceProfileArn) - d.Set(names.AttrInstanceType, instance.InstanceType) - d.Set("last_service_error_id", instance.LastServiceErrorId) - var layerIds []string - for _, v := range instance.LayerIds { - layerIds = append(layerIds, aws.StringValue(v)) - } - layerIds, err = sortListBasedonTFFile(layerIds, d) + d.SetId(aws.ToString(output.InstanceId)) + d.Set("agent_version", output.AgentVersion) + d.Set("ami_id", output.AmiId) + d.Set("architecture", output.Architecture) + d.Set("auto_scaling_type", output.AutoScalingType) + d.Set(names.AttrAvailabilityZone, output.AvailabilityZone) + d.Set(names.AttrCreatedAt, output.CreatedAt) + d.Set("ebs_optimized", output.EbsOptimized) + d.Set("ec2_instance_id", output.Ec2InstanceId) + d.Set("ecs_cluster_arn", output.EcsClusterArn) + d.Set("elastic_ip", output.ElasticIp) + d.Set("hostname", output.Hostname) + d.Set("infrastructure_class", output.InfrastructureClass) + d.Set("install_updates_on_boot", output.InstallUpdatesOnBoot) + d.Set("instance_profile_arn", output.InstanceProfileArn) + d.Set(names.AttrInstanceType, output.InstanceType) + d.Set("last_service_error_id", output.LastServiceErrorId) + layerIds, err := sortListBasedonTFFile(output.LayerIds, d) if err != nil { return sdkdiag.AppendErrorf(diags, "sorting layer_ids attribute: %#v", err) } if err := d.Set("layer_ids", layerIds); err != nil { return sdkdiag.AppendErrorf(diags, "setting layer_ids attribute: %#v, error: %#v", layerIds, err) } - d.Set("os", instance.Os) - d.Set("platform", instance.Platform) - d.Set("private_dns", instance.PrivateDns) - d.Set("private_ip", instance.PrivateIp) - d.Set("public_dns", instance.PublicDns) - d.Set("public_ip", instance.PublicIp) - d.Set("registered_by", instance.RegisteredBy) - d.Set("reported_agent_version", instance.ReportedAgentVersion) - d.Set("reported_os_family", instance.ReportedOs.Family) - d.Set("reported_os_name", instance.ReportedOs.Name) - d.Set("reported_os_version", instance.ReportedOs.Version) - d.Set("root_device_type", instance.RootDeviceType) - d.Set("root_device_volume_id", instance.RootDeviceVolumeId) - d.Set("ssh_host_dsa_key_fingerprint", instance.SshHostDsaKeyFingerprint) - d.Set("ssh_host_rsa_key_fingerprint", instance.SshHostRsaKeyFingerprint) - d.Set("ssh_key_name", instance.SshKeyName) - d.Set("stack_id", instance.StackId) - d.Set(names.AttrStatus, instance.Status) - d.Set(names.AttrSubnetID, instance.SubnetId) - d.Set("tenancy", instance.Tenancy) - d.Set("virtualization_type", instance.VirtualizationType) + d.Set("os", output.Os) + d.Set("platform", output.Platform) + d.Set("private_dns", output.PrivateDns) + d.Set("private_ip", output.PrivateIp) + d.Set("public_dns", output.PublicDns) + d.Set("public_ip", output.PublicIp) + d.Set("registered_by", output.RegisteredBy) + d.Set("reported_agent_version", output.ReportedAgentVersion) + d.Set("reported_os_family", output.ReportedOs.Family) + d.Set("reported_os_name", output.ReportedOs.Name) + d.Set("reported_os_version", output.ReportedOs.Version) + d.Set("root_device_type", output.RootDeviceType) + d.Set("root_device_volume_id", output.RootDeviceVolumeId) + d.Set("ssh_host_dsa_key_fingerprint", output.SshHostDsaKeyFingerprint) + d.Set("ssh_host_rsa_key_fingerprint", output.SshHostRsaKeyFingerprint) + d.Set("ssh_key_name", output.SshKeyName) + d.Set("stack_id", output.StackId) + d.Set(names.AttrStatus, output.Status) + d.Set(names.AttrSubnetID, output.SubnetId) + d.Set("tenancy", output.Tenancy) + d.Set("virtualization_type", output.VirtualizationType) // Read BlockDeviceMapping - ibds := readBlockDevices(instance) + ibds := readBlockDevices(output) if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { return sdkdiag.AppendErrorf(diags, "reading OpsWorks Instance (%s): setting ebs_block_device: %s", d.Id(), err) @@ -559,10 +541,8 @@ func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta inte } // Read Security Groups - sgs := make([]string, 0, len(instance.SecurityGroupIds)) - for _, sg := range instance.SecurityGroupIds { - sgs = append(sgs, *sg) - } + sgs := make([]string, 0, len(output.SecurityGroupIds)) + sgs = append(sgs, output.SecurityGroupIds...) if err := d.Set(names.AttrSecurityGroupIDs, sgs); err != nil { return sdkdiag.AppendErrorf(diags, "reading OpsWorks Instance (%s): setting security_group_ids: %s", d.Id(), err) } @@ -571,7 +551,7 @@ func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta inte func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) err := resourceInstanceValidate(d) if err != nil { @@ -580,11 +560,11 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in req := &opsworks.CreateInstanceInput{ AgentVersion: aws.String(d.Get("agent_version").(string)), - Architecture: aws.String(d.Get("architecture").(string)), + Architecture: awstypes.Architecture(d.Get("architecture").(string)), EbsOptimized: aws.Bool(d.Get("ebs_optimized").(bool)), InstallUpdatesOnBoot: aws.Bool(d.Get("install_updates_on_boot").(bool)), InstanceType: aws.String(d.Get(names.AttrInstanceType).(string)), - LayerIds: flex.ExpandStringList(d.Get("layer_ids").([]interface{})), + LayerIds: flex.ExpandStringValueList(d.Get("layer_ids").([]interface{})), StackId: aws.String(d.Get("stack_id").(string)), } @@ -594,7 +574,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := d.GetOk("auto_scaling_type"); ok { - req.AutoScalingType = aws.String(v.(string)) + req.AutoScalingType = awstypes.AutoScalingType(v.(string)) } if v, ok := d.GetOk(names.AttrAvailabilityZone); ok { @@ -610,7 +590,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := d.GetOk("root_device_type"); ok { - req.RootDeviceType = aws.String(v.(string)) + req.RootDeviceType = awstypes.RootDeviceType(v.(string)) } if v, ok := d.GetOk("ssh_key_name"); ok { @@ -629,13 +609,13 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in req.VirtualizationType = aws.String(v.(string)) } - var blockDevices []*opsworks.BlockDeviceMapping + var blockDevices []awstypes.BlockDeviceMapping if v, ok := d.GetOk("ebs_block_device"); ok { vL := v.(*schema.Set).List() for _, v := range vL { bd := v.(map[string]interface{}) - ebs := &opsworks.EbsBlockDevice{ + ebs := &awstypes.EbsBlockDevice{ DeleteOnTermination: aws.Bool(bd[names.AttrDeleteOnTermination].(bool)), } @@ -644,18 +624,18 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := bd[names.AttrVolumeSize].(int); ok && v != 0 { - ebs.VolumeSize = aws.Int64(int64(v)) + ebs.VolumeSize = aws.Int32(int32(v)) } if v, ok := bd[names.AttrVolumeType].(string); ok && v != "" { - ebs.VolumeType = aws.String(v) + ebs.VolumeType = awstypes.VolumeType(v) } if v, ok := bd[names.AttrIOPS].(int); ok && v > 0 { - ebs.Iops = aws.Int64(int64(v)) + ebs.Iops = aws.Int32(int32(v)) } - blockDevices = append(blockDevices, &opsworks.BlockDeviceMapping{ + blockDevices = append(blockDevices, awstypes.BlockDeviceMapping{ DeviceName: aws.String(bd[names.AttrDeviceName].(string)), Ebs: ebs, }) @@ -666,7 +646,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in vL := v.(*schema.Set).List() for _, v := range vL { bd := v.(map[string]interface{}) - blockDevices = append(blockDevices, &opsworks.BlockDeviceMapping{ + blockDevices = append(blockDevices, awstypes.BlockDeviceMapping{ DeviceName: aws.String(bd[names.AttrDeviceName].(string)), VirtualName: aws.String(bd[names.AttrVirtualName].(string)), }) @@ -680,23 +660,23 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in } for _, v := range vL { bd := v.(map[string]interface{}) - ebs := &opsworks.EbsBlockDevice{ + ebs := &awstypes.EbsBlockDevice{ DeleteOnTermination: aws.Bool(bd[names.AttrDeleteOnTermination].(bool)), } if v, ok := bd[names.AttrVolumeSize].(int); ok && v != 0 { - ebs.VolumeSize = aws.Int64(int64(v)) + ebs.VolumeSize = aws.Int32(int32(v)) } if v, ok := bd[names.AttrVolumeType].(string); ok && v != "" { - ebs.VolumeType = aws.String(v) + ebs.VolumeType = awstypes.VolumeType(v) } if v, ok := bd[names.AttrIOPS].(int); ok && v > 0 { - ebs.Iops = aws.Int64(int64(v)) + ebs.Iops = aws.Int32(int32(v)) } - blockDevices = append(blockDevices, &opsworks.BlockDeviceMapping{ + blockDevices = append(blockDevices, awstypes.BlockDeviceMapping{ DeviceName: aws.String("ROOT_DEVICE"), Ebs: ebs, }) @@ -711,7 +691,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in var resp *opsworks.CreateInstanceOutput - resp, err = conn.CreateInstanceWithContext(ctx, req) + resp, err = conn.CreateInstance(ctx, req) if err != nil { return sdkdiag.AppendErrorf(diags, "creating OpsWorks Instance: %s", err) } @@ -720,7 +700,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in return sdkdiag.AppendErrorf(diags, "creating OpsWorks Instance: no instance returned") } - instanceId := aws.StringValue(resp.InstanceId) + instanceId := aws.ToString(resp.InstanceId) d.SetId(instanceId) if v, ok := d.GetOk(names.AttrState); ok && v.(string) == instanceStatusRunning { @@ -735,7 +715,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) err := resourceInstanceValidate(d) if err != nil { @@ -745,7 +725,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in req := &opsworks.UpdateInstanceInput{ InstanceId: aws.String(d.Id()), AgentVersion: aws.String(d.Get("agent_version").(string)), - Architecture: aws.String(d.Get("architecture").(string)), + Architecture: awstypes.Architecture(d.Get("architecture").(string)), InstallUpdatesOnBoot: aws.Bool(d.Get("install_updates_on_boot").(bool)), } @@ -755,7 +735,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := d.GetOk("auto_scaling_type"); ok { - req.AutoScalingType = aws.String(v.(string)) + req.AutoScalingType = awstypes.AutoScalingType(v.(string)) } if v, ok := d.GetOk("hostname"); ok { @@ -767,7 +747,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := d.GetOk("layer_ids"); ok { - req.LayerIds = flex.ExpandStringList(v.([]interface{})) + req.LayerIds = flex.ExpandStringValueList(v.([]interface{})) } if v, ok := d.GetOk("os"); ok { @@ -780,7 +760,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in log.Printf("[DEBUG] Updating OpsWorks instance: %s", d.Id()) - _, err = conn.UpdateInstanceWithContext(ctx, req) + _, err = conn.UpdateInstance(ctx, req) if err != nil { return sdkdiag.AppendErrorf(diags, "updating OpsWorks Instance (%s): %s", d.Id(), err) } @@ -817,7 +797,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in func resourceInstanceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) if v, ok := d.GetOk(names.AttrStatus); ok && v.(string) != instanceStatusStopped { err := stopInstance(ctx, d, meta, d.Timeout(schema.TimeoutDelete)) @@ -834,9 +814,9 @@ func resourceInstanceDelete(ctx context.Context, d *schema.ResourceData, meta in log.Printf("[DEBUG] Deleting OpsWorks instance: %s", d.Id()) - _, err := conn.DeleteInstanceWithContext(ctx, req) + _, err := conn.DeleteInstance(ctx, req) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -851,6 +831,30 @@ func resourceInstanceDelete(ctx context.Context, d *schema.ResourceData, meta in return diags } +func findInstanceByID(ctx context.Context, conn *opsworks.Client, id string) (*awstypes.Instance, error) { + input := &opsworks.DescribeInstancesInput{ + InstanceIds: []string{id}, + } + + output, err := conn.DescribeInstances(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.Instances == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return tfresource.AssertSingleValueResult(output.Instances) +} + func resourceInstanceImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { // Neither delete_eip nor delete_ebs can be fetched // from any API call, so we need to default to the values @@ -861,7 +865,7 @@ func resourceInstanceImport(ctx context.Context, d *schema.ResourceData, meta in } func startInstance(ctx context.Context, d *schema.ResourceData, meta interface{}, wait bool, timeout time.Duration) error { - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) req := &opsworks.StartInstanceInput{ InstanceId: aws.String(d.Id()), @@ -869,7 +873,7 @@ func startInstance(ctx context.Context, d *schema.ResourceData, meta interface{} log.Printf("[DEBUG] Starting OpsWorks instance: %s", d.Id()) - _, err := conn.StartInstanceWithContext(ctx, req) + _, err := conn.StartInstance(ctx, req) if err != nil { return fmt.Errorf("starting instance: %w", err) @@ -887,7 +891,7 @@ func startInstance(ctx context.Context, d *schema.ResourceData, meta interface{} } func stopInstance(ctx context.Context, d *schema.ResourceData, meta interface{}, timeout time.Duration) error { - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) req := &opsworks.StopInstanceInput{ InstanceId: aws.String(d.Id()), @@ -895,7 +899,7 @@ func stopInstance(ctx context.Context, d *schema.ResourceData, meta interface{}, log.Printf("[DEBUG] Stopping OpsWorks instance: %s", d.Id()) - _, err := conn.StopInstanceWithContext(ctx, req) + _, err := conn.StopInstance(ctx, req) if err != nil { return fmt.Errorf("stopping instance: %w", err) @@ -910,7 +914,7 @@ func stopInstance(ctx context.Context, d *schema.ResourceData, meta interface{}, return nil } -func waitInstanceDeleted(ctx context.Context, conn *opsworks.OpsWorks, instanceId string) error { +func waitInstanceDeleted(ctx context.Context, conn *opsworks.Client, instanceId string) error { stateConf := &retry.StateChangeConf{ Pending: []string{instanceStatusStopped, instanceStatusTerminating, instanceStatusTerminated}, Target: []string{}, @@ -924,7 +928,7 @@ func waitInstanceDeleted(ctx context.Context, conn *opsworks.OpsWorks, instanceI return err } -func waitInstanceStarted(ctx context.Context, conn *opsworks.OpsWorks, instanceId string, timeout time.Duration) error { +func waitInstanceStarted(ctx context.Context, conn *opsworks.Client, instanceId string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ Pending: []string{instanceStatusRequested, instanceStatusPending, instanceStatusBooting, instanceStatusRunningSetup}, Target: []string{instanceStatusOnline}, @@ -937,7 +941,7 @@ func waitInstanceStarted(ctx context.Context, conn *opsworks.OpsWorks, instanceI return err } -func waitInstanceStopped(ctx context.Context, conn *opsworks.OpsWorks, instanceId string, timeout time.Duration) error { +func waitInstanceStopped(ctx context.Context, conn *opsworks.Client, instanceId string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ Pending: []string{instanceStatusStopping, instanceStatusTerminating, instanceStatusShuttingDown, instanceStatusTerminated}, Target: []string{instanceStatusStopped}, @@ -950,13 +954,13 @@ func waitInstanceStopped(ctx context.Context, conn *opsworks.OpsWorks, instanceI return err } -func instanceStatus(ctx context.Context, conn *opsworks.OpsWorks, instanceID string) retry.StateRefreshFunc { +func instanceStatus(ctx context.Context, conn *opsworks.Client, instanceID string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - resp, err := conn.DescribeInstancesWithContext(ctx, &opsworks.DescribeInstancesInput{ - InstanceIds: []*string{aws.String(instanceID)}, + resp, err := conn.DescribeInstances(ctx, &opsworks.DescribeInstancesInput{ + InstanceIds: []string{instanceID}, }) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, "", nil } @@ -964,18 +968,18 @@ func instanceStatus(ctx context.Context, conn *opsworks.OpsWorks, instanceID str return nil, "", err } - if resp == nil || len(resp.Instances) == 0 || resp.Instances[0] == nil { + if resp == nil || len(resp.Instances) == 0 { // Sometimes AWS just has consistency issues and doesn't see // our instance yet. Return an empty state. return nil, "", nil } i := resp.Instances[0] - return i, aws.StringValue(i.Status), nil + return i, aws.ToString(i.Status), nil } } -func readBlockDevices(instance *opsworks.Instance) map[string]interface{} { +func readBlockDevices(instance *awstypes.Instance) map[string]interface{} { blockDevices := make(map[string]interface{}) blockDevices["ebs"] = make([]map[string]interface{}, 0) blockDevices["ephemeral"] = make([]map[string]interface{}, 0) @@ -988,29 +992,29 @@ func readBlockDevices(instance *opsworks.Instance) map[string]interface{} { for _, bdm := range instance.BlockDeviceMappings { bd := make(map[string]interface{}) if bdm.Ebs != nil && bdm.Ebs.DeleteOnTermination != nil { - bd[names.AttrDeleteOnTermination] = aws.BoolValue(bdm.Ebs.DeleteOnTermination) + bd[names.AttrDeleteOnTermination] = aws.ToBool(bdm.Ebs.DeleteOnTermination) } if bdm.Ebs != nil && bdm.Ebs.VolumeSize != nil { - bd[names.AttrVolumeSize] = aws.Int64Value(bdm.Ebs.VolumeSize) + bd[names.AttrVolumeSize] = aws.ToInt32(bdm.Ebs.VolumeSize) } - if bdm.Ebs != nil && bdm.Ebs.VolumeType != nil { - bd[names.AttrVolumeType] = aws.StringValue(bdm.Ebs.VolumeType) + if bdm.Ebs != nil { + bd[names.AttrVolumeType] = bdm.Ebs.VolumeType } if bdm.Ebs != nil && bdm.Ebs.Iops != nil { - bd[names.AttrIOPS] = aws.Int64Value(bdm.Ebs.Iops) + bd[names.AttrIOPS] = aws.ToInt32(bdm.Ebs.Iops) } - if aws.StringValue(bdm.DeviceName) == "ROOT_DEVICE" { + if aws.ToString(bdm.DeviceName) == "ROOT_DEVICE" { blockDevices["root"] = bd } else { if bdm.DeviceName != nil { - bd[names.AttrDeviceName] = aws.StringValue(bdm.DeviceName) + bd[names.AttrDeviceName] = aws.ToString(bdm.DeviceName) } if bdm.VirtualName != nil { - bd[names.AttrVirtualName] = aws.StringValue(bdm.VirtualName) + bd[names.AttrVirtualName] = aws.ToString(bdm.VirtualName) blockDevices["ephemeral"] = append(blockDevices["ephemeral"].([]map[string]interface{}), bd) } else { if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil { - bd[names.AttrSnapshotID] = aws.StringValue(bdm.Ebs.SnapshotId) + bd[names.AttrSnapshotID] = aws.ToString(bdm.Ebs.SnapshotId) } blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd) } diff --git a/internal/service/opsworks/instance_test.go b/internal/service/opsworks/instance_test.go index e7a551b6a91..4275d5a6186 100644 --- a/internal/service/opsworks/instance_test.go +++ b/internal/service/opsworks/instance_test.go @@ -8,26 +8,29 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfopsworks "github.com/hashicorp/terraform-provider-aws/internal/service/opsworks" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) func TestAccOpsWorksInstance_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var opsinst opsworks.Instance + var opsinst awstypes.Instance rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_instance.test" dataSourceName := "data.aws_availability_zones.available" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckInstanceDestroy(ctx), @@ -72,13 +75,15 @@ func TestAccOpsWorksInstance_basic(t *testing.T) { } func TestAccOpsWorksInstance_updateHostNameForceNew(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_instance.test" - var before, after opsworks.Instance + var before, after awstypes.Instance resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckInstanceDestroy(ctx), @@ -108,8 +113,7 @@ func TestAccOpsWorksInstance_updateHostNameForceNew(t *testing.T) { }) } -func testAccCheckInstanceRecreated(t *testing.T, - before, after *opsworks.Instance) resource.TestCheckFunc { +func testAccCheckInstanceRecreated(t *testing.T, before, after *awstypes.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { if *before.InstanceId == *after.InstanceId { t.Fatalf("Expected change of OpsWorks Instance IDs, but both were %s", *before.InstanceId) @@ -118,8 +122,31 @@ func testAccCheckInstanceRecreated(t *testing.T, } } -func testAccCheckInstanceExists(ctx context.Context, - n string, opsinst *opsworks.Instance) resource.TestCheckFunc { +func testAccCheckInstanceDestroy(ctx context.Context) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_opsworks_instance" { + continue + } + _, err := tfopsworks.FindInstanceByID(ctx, conn, rs.Primary.ID) + + if tfresource.NotFound(err) { + continue + } + + if err != nil { + return err + } + + return fmt.Errorf("OpsWorks Instance %s still exists", rs.Primary.ID) + } + + return nil + } +} + +func testAccCheckInstanceExists(ctx context.Context, n string, opsinst *awstypes.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -130,84 +157,41 @@ func testAccCheckInstanceExists(ctx context.Context, return fmt.Errorf("No Opsworks Instance is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) - params := &opsworks.DescribeInstancesInput{ - InstanceIds: []*string{&rs.Primary.ID}, - } - resp, err := conn.DescribeInstancesWithContext(ctx, params) + output, err := tfopsworks.FindInstanceByID(ctx, conn, rs.Primary.ID) if err != nil { return err } - if v := len(resp.Instances); v != 1 { - return fmt.Errorf("Expected 1 request returned, got %d", v) - } - - *opsinst = *resp.Instances[0] + *opsinst = *output return nil } } -func testAccCheckInstanceAttributes( - opsinst *opsworks.Instance) resource.TestCheckFunc { +func testAccCheckInstanceAttributes(opsinst *awstypes.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { // Depending on the timing, the state could be requested or stopped - if *opsinst.Status != "stopped" && *opsinst.Status != "requested" { + if aws.ToString(opsinst.Status) != "stopped" && aws.ToString(opsinst.Status) != "requested" { return fmt.Errorf("Unexpected request status: %s", *opsinst.Status) } - if *opsinst.Architecture != "x86_64" { - return fmt.Errorf("Unexpected architecture: %s", *opsinst.Architecture) + if opsinst.Architecture != awstypes.ArchitectureX8664 { + return fmt.Errorf("Unexpected architecture: %s", opsinst.Architecture) } if *opsinst.Tenancy != "default" { return fmt.Errorf("Unexpected tenancy: %s", *opsinst.Tenancy) } - if *opsinst.InfrastructureClass != "ec2" { - return fmt.Errorf("Unexpected infrastructure class: %s", *opsinst.InfrastructureClass) - } - if *opsinst.RootDeviceType != "ebs" { - return fmt.Errorf("Unexpected root device type: %s", *opsinst.RootDeviceType) + if aws.ToString(opsinst.InfrastructureClass) != "ec2" { + return fmt.Errorf("Unexpected infrastructure class: %s", aws.ToString(opsinst.InfrastructureClass)) } - if *opsinst.VirtualizationType != "hvm" { - return fmt.Errorf("Unexpected virtualization type: %s", *opsinst.VirtualizationType) + if opsinst.RootDeviceType != awstypes.RootDeviceTypeEbs { + return fmt.Errorf("Unexpected root device type: %s", opsinst.RootDeviceType) } - return nil - } -} - -func testAccCheckInstanceDestroy(ctx context.Context) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_opsworks_instance" { - continue - } - req := &opsworks.DescribeInstancesInput{ - InstanceIds: aws.StringSlice([]string{rs.Primary.ID}), - } - - output, err := conn.DescribeInstancesWithContext(ctx, req) - - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { - continue - } - - if err != nil { - return err - } - - if output != nil && len(output.Instances) > 0 { - for _, instance := range output.Instances { - if aws.StringValue(instance.InstanceId) != rs.Primary.ID { - continue - } - return fmt.Errorf("Expected OpsWorks instance (%s) to be gone, but was still found", rs.Primary.ID) - } - } + if opsinst.VirtualizationType != awstypes.VirtualizationTypeHvm { + return fmt.Errorf("Unexpected virtualization type: %s", opsinst.VirtualizationType) } - return nil } } diff --git a/internal/service/opsworks/java_app_layer.go b/internal/service/opsworks/java_app_layer.go index 9dc0cd7092e..abeef4db31e 100644 --- a/internal/service/opsworks/java_app_layer.go +++ b/internal/service/opsworks/java_app_layer.go @@ -4,40 +4,40 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_java_app_layer", name="Java App Layer") // @Tags(identifierAttribute="arn") -func ResourceJavaAppLayer() *schema.Resource { +func resourceJavaAppLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeJavaApp, + TypeName: awstypes.LayerTypeJavaApp, DefaultLayerName: "Java App Server", Attributes: map[string]*opsworksLayerTypeAttribute{ "app_server": { - AttrName: opsworks.LayerAttributesKeysJavaAppServer, + AttrName: awstypes.LayerAttributesKeysJavaAppServer, Type: schema.TypeString, Default: "tomcat", }, "app_server_version": { - AttrName: opsworks.LayerAttributesKeysJavaAppServerVersion, + AttrName: awstypes.LayerAttributesKeysJavaAppServerVersion, Type: schema.TypeString, Default: "7", }, "jvm_options": { - AttrName: opsworks.LayerAttributesKeysJvmOptions, + AttrName: awstypes.LayerAttributesKeysJvmOptions, Type: schema.TypeString, Default: "", }, "jvm_type": { - AttrName: opsworks.LayerAttributesKeysJvm, + AttrName: awstypes.LayerAttributesKeysJvm, Type: schema.TypeString, Default: "openjdk", }, "jvm_version": { - AttrName: opsworks.LayerAttributesKeysJvmVersion, + AttrName: awstypes.LayerAttributesKeysJvmVersion, Type: schema.TypeString, Default: "7", }, diff --git a/internal/service/opsworks/java_app_layer_test.go b/internal/service/opsworks/java_app_layer_test.go index b73f3eeeb2d..15de805d572 100644 --- a/internal/service/opsworks/java_app_layer_test.go +++ b/internal/service/opsworks/java_app_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksJavaAppLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_java_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckJavaAppLayerDestroy(ctx), diff --git a/internal/service/opsworks/layers.go b/internal/service/opsworks/layers.go index 4a6c964670b..e668370b354 100644 --- a/internal/service/opsworks/layers.go +++ b/internal/service/opsworks/layers.go @@ -9,9 +9,9 @@ import ( "log" "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "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/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -19,6 +19,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tfmaps "github.com/hashicorp/terraform-provider-aws/internal/maps" @@ -39,7 +41,7 @@ import ( // layer resource types, which have names matching aws_opsworks_*_layer . type opsworksLayerTypeAttribute struct { - AttrName string + AttrName awstypes.LayerAttributesKeys Type schema.ValueType Default interface{} ForceNew bool @@ -51,7 +53,7 @@ type opsworksLayerTypeAttribute struct { type opsworksLayerTypeAttributeMap map[string]*opsworksLayerTypeAttribute type opsworksLayerType struct { - TypeName string + TypeName awstypes.LayerType DefaultLayerName string Attributes opsworksLayerTypeAttributeMap CustomShortName bool @@ -134,10 +136,10 @@ func (lt *opsworksLayerType) resourceSchema() *schema.Resource { Optional: true, }, "encoding": { - Type: schema.TypeString, - Optional: true, - Default: opsworks.CloudWatchLogsEncodingUtf8, - ValidateFunc: validation.StringInSlice(opsworks.CloudWatchLogsEncoding_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.CloudWatchLogsEncodingUtf8, + ValidateDiagFunc: enum.Validate[awstypes.CloudWatchLogsEncoding](), }, "file": { Type: schema.TypeString, @@ -149,10 +151,10 @@ func (lt *opsworksLayerType) resourceSchema() *schema.Resource { Default: "1", }, "initial_position": { - Type: schema.TypeString, - Optional: true, - Default: opsworks.CloudWatchLogsInitialPositionStartOfFile, - ValidateFunc: validation.StringInSlice(opsworks.CloudWatchLogsInitialPosition_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: awstypes.CloudWatchLogsInitialPositionStartOfFile, + ValidateDiagFunc: enum.Validate[awstypes.CloudWatchLogsInitialPosition](), }, names.AttrLogGroupName: { Type: schema.TypeString, @@ -163,9 +165,9 @@ func (lt *opsworksLayerType) resourceSchema() *schema.Resource { Optional: true, }, "time_zone": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice(opsworks.CloudWatchLogsTimeZone_Values(), false), + Type: schema.TypeString, + Optional: true, + ValidateDiagFunc: enum.Validate[awstypes.CloudWatchLogsTimeZone](), }, }, }, @@ -472,7 +474,7 @@ func (lt *opsworksLayerType) resourceSchema() *schema.Resource { func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) attributes, err := lt.Attributes.resourceDataToAPIAttributes(d) @@ -482,19 +484,19 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, name := d.Get(names.AttrName).(string) input := &opsworks.CreateLayerInput{ - Attributes: aws.StringMap(attributes), + Attributes: attributes, AutoAssignElasticIps: aws.Bool(d.Get("auto_assign_elastic_ips").(bool)), AutoAssignPublicIps: aws.Bool(d.Get("auto_assign_public_ips").(bool)), - CustomRecipes: &opsworks.Recipes{}, + CustomRecipes: &awstypes.Recipes{}, EnableAutoHealing: aws.Bool(d.Get("auto_healing").(bool)), InstallUpdatesOnBoot: aws.Bool(d.Get("install_updates_on_boot").(bool)), - LifecycleEventConfiguration: &opsworks.LifecycleEventConfiguration{ - Shutdown: &opsworks.ShutdownEventConfiguration{ + LifecycleEventConfiguration: &awstypes.LifecycleEventConfiguration{ + Shutdown: &awstypes.ShutdownEventConfiguration{ DelayUntilElbConnectionsDrained: aws.Bool(d.Get("drain_elb_on_shutdown").(bool)), }, }, Name: aws.String(name), - Type: aws.String(lt.TypeName), + Type: lt.TypeName, StackId: aws.String(d.Get("stack_id").(string)), UseEbsOptimizedInstances: aws.Bool(d.Get("use_ebs_optimized_instances").(bool)), } @@ -504,11 +506,11 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("custom_configure_recipes"); ok && len(v.([]interface{})) > 0 { - input.CustomRecipes.Configure = flex.ExpandStringList(v.([]interface{})) + input.CustomRecipes.Configure = flex.ExpandStringValueList(v.([]interface{})) } if v, ok := d.GetOk("custom_deploy_recipes"); ok && len(v.([]interface{})) > 0 { - input.CustomRecipes.Deploy = flex.ExpandStringList(v.([]interface{})) + input.CustomRecipes.Deploy = flex.ExpandStringValueList(v.([]interface{})) } if v, ok := d.GetOk("custom_instance_profile_arn"); ok { @@ -520,19 +522,19 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("custom_security_group_ids"); ok && v.(*schema.Set).Len() > 0 { - input.CustomSecurityGroupIds = flex.ExpandStringSet(v.(*schema.Set)) + input.CustomSecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("custom_setup_recipes"); ok && len(v.([]interface{})) > 0 { - input.CustomRecipes.Setup = flex.ExpandStringList(v.([]interface{})) + input.CustomRecipes.Setup = flex.ExpandStringValueList(v.([]interface{})) } if v, ok := d.GetOk("custom_shutdown_recipes"); ok && len(v.([]interface{})) > 0 { - input.CustomRecipes.Shutdown = flex.ExpandStringList(v.([]interface{})) + input.CustomRecipes.Shutdown = flex.ExpandStringValueList(v.([]interface{})) } if v, ok := d.GetOk("custom_undeploy_recipes"); ok && len(v.([]interface{})) > 0 { - input.CustomRecipes.Undeploy = flex.ExpandStringList(v.([]interface{})) + input.CustomRecipes.Undeploy = flex.ExpandStringValueList(v.([]interface{})) } if v, ok := d.GetOk("ebs_volume"); ok && v.(*schema.Set).Len() > 0 { @@ -540,22 +542,22 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("instance_shutdown_timeout"); ok { - input.LifecycleEventConfiguration.Shutdown.ExecutionTimeout = aws.Int64(int64(v.(int))) + input.LifecycleEventConfiguration.Shutdown.ExecutionTimeout = aws.Int32(int32(v.(int))) } if lt.CustomShortName { input.Shortname = aws.String(d.Get("short_name").(string)) } else { - input.Shortname = aws.String(lt.TypeName) + input.Shortname = aws.String(string(lt.TypeName)) } if v, ok := d.GetOk("system_packages"); ok && v.(*schema.Set).Len() > 0 { - input.Packages = flex.ExpandStringSet(v.(*schema.Set)) + input.Packages = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("ecs_cluster_arn"); ok { arn := v.(string) - _, err := conn.RegisterEcsClusterWithContext(ctx, &opsworks.RegisterEcsClusterInput{ + _, err := conn.RegisterEcsCluster(ctx, &opsworks.RegisterEcsClusterInput{ EcsClusterArn: aws.String(arn), StackId: input.StackId, }) @@ -565,18 +567,18 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, } } - log.Printf("[DEBUG] Creating OpsWorks Layer: %s", input) - output, err := conn.CreateLayerWithContext(ctx, input) + log.Printf("[DEBUG] Creating OpsWorks Layer: %#v", input) + output, err := conn.CreateLayer(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating OpsWorks Layer (%s): %s", name, err) } - d.SetId(aws.StringValue(output.LayerId)) + d.SetId(aws.ToString(output.LayerId)) if v, ok := d.GetOk("elastic_load_balancer"); ok { v := v.(string) - _, err := conn.AttachElasticLoadBalancerWithContext(ctx, &opsworks.AttachElasticLoadBalancerInput{ + _, err := conn.AttachElasticLoadBalancer(ctx, &opsworks.AttachElasticLoadBalancerInput{ ElasticLoadBalancerName: aws.String(v), LayerId: aws.String(d.Id()), }) @@ -590,7 +592,7 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, input := expandSetLoadBasedAutoScalingInput(v.([]interface{})[0].(map[string]interface{})) input.LayerId = aws.String(d.Id()) - _, err := conn.SetLoadBasedAutoScalingWithContext(ctx, input) + _, err := conn.SetLoadBasedAutoScaling(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "setting OpsWorks Layer (%s) load-based auto scaling configuration: %s", d.Id(), err) @@ -598,13 +600,13 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, } if tags := KeyValueTags(ctx, getTagsIn(ctx)); len(tags) > 0 { - layer, err := FindLayerByID(ctx, conn, d.Id()) + layer, err := findLayerByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading OpsWorks Layer (%s): %s", d.Id(), err) } - arn := aws.StringValue(layer.Arn) + arn := aws.ToString(layer.Arn) if err := updateTags(ctx, conn, arn, nil, tags); err != nil { return sdkdiag.AppendErrorf(diags, "adding OpsWorks Layer (%s) tags: %s", arn, err) } @@ -615,9 +617,9 @@ func (lt *opsworksLayerType) Create(ctx context.Context, d *schema.ResourceData, func (lt *opsworksLayerType) Read(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) - layer, err := FindLayerByID(ctx, conn, d.Id()) + layer, err := findLayerByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] OpsWorks Layer %s not found, removing from state", d.Id()) @@ -629,7 +631,7 @@ func (lt *opsworksLayerType) Read(ctx context.Context, d *schema.ResourceData, m return sdkdiag.AppendErrorf(diags, "reading OpsWorks Layer (%s): %s", d.Id(), err) } - arn := aws.StringValue(layer.Arn) + arn := aws.ToString(layer.Arn) d.Set(names.AttrARN, arn) d.Set("auto_assign_elastic_ips", layer.AutoAssignElasticIps) d.Set("auto_assign_public_ips", layer.AutoAssignPublicIps) @@ -648,23 +650,23 @@ func (lt *opsworksLayerType) Read(ctx context.Context, d *schema.ResourceData, m d.Set("custom_shutdown_recipes", nil) d.Set("custom_undeploy_recipes", nil) } else { - d.Set("custom_configure_recipes", aws.StringValueSlice(layer.CustomRecipes.Configure)) - d.Set("custom_deploy_recipes", aws.StringValueSlice(layer.CustomRecipes.Deploy)) - d.Set("custom_setup_recipes", aws.StringValueSlice(layer.CustomRecipes.Setup)) - d.Set("custom_shutdown_recipes", aws.StringValueSlice(layer.CustomRecipes.Shutdown)) - d.Set("custom_undeploy_recipes", aws.StringValueSlice(layer.CustomRecipes.Undeploy)) + d.Set("custom_configure_recipes", layer.CustomRecipes.Configure) + d.Set("custom_deploy_recipes", layer.CustomRecipes.Deploy) + d.Set("custom_setup_recipes", layer.CustomRecipes.Setup) + d.Set("custom_shutdown_recipes", layer.CustomRecipes.Shutdown) + d.Set("custom_undeploy_recipes", layer.CustomRecipes.Undeploy) } d.Set("custom_instance_profile_arn", layer.CustomInstanceProfileArn) if layer.CustomJson == nil { d.Set("custom_json", "") } else { - policy, err := structure.NormalizeJsonString(aws.StringValue(layer.CustomJson)) + policy, err := structure.NormalizeJsonString(aws.ToString(layer.CustomJson)) if err != nil { return sdkdiag.AppendErrorf(diags, "policy contains an invalid JSON: %s", err) } d.Set("custom_json", policy) } - d.Set("custom_security_group_ids", aws.StringValueSlice(layer.CustomSecurityGroupIds)) + d.Set("custom_security_group_ids", layer.CustomSecurityGroupIds) if layer.LifecycleEventConfiguration == nil || layer.LifecycleEventConfiguration.Shutdown == nil { d.Set("drain_elb_on_shutdown", nil) d.Set("instance_shutdown_timeout", nil) @@ -680,11 +682,11 @@ func (lt *opsworksLayerType) Read(ctx context.Context, d *schema.ResourceData, m if lt.CustomShortName { d.Set("short_name", layer.Shortname) } - d.Set("system_packages", aws.StringValueSlice(layer.Packages)) + d.Set("system_packages", layer.Packages) d.Set("stack_id", layer.StackId) d.Set("use_ebs_optimized_instances", layer.UseEbsOptimizedInstances) - if err := lt.Attributes.apiAttributesToResourceData(aws.StringValueMap(layer.Attributes), d); err != nil { + if err := lt.Attributes.apiAttributesToResourceData(layer.Attributes, d); err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -715,7 +717,7 @@ func (lt *opsworksLayerType) Read(ctx context.Context, d *schema.ResourceData, m func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) if d.HasChangesExcept("elastic_load_balancer", "load_based_auto_scaling", names.AttrTags, names.AttrTagsAll) { input := &opsworks.UpdateLayerInput{ @@ -729,7 +731,7 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendFromErr(diags, err) } - input.Attributes = aws.StringMap(attributes) + input.Attributes = attributes } if d.HasChanges("auto_assign_elastic_ips") { @@ -751,26 +753,26 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, } if d.HasChanges("custom_configure_recipes", "custom_deploy_recipes", "custom_setup_recipes", "custom_shutdown_recipes", "custom_undeploy_recipes") { - apiObject := &opsworks.Recipes{} + apiObject := &awstypes.Recipes{} if d.HasChanges("custom_configure_recipes") { - apiObject.Configure = flex.ExpandStringList(d.Get("custom_configure_recipes").([]interface{})) + apiObject.Configure = flex.ExpandStringValueList(d.Get("custom_configure_recipes").([]interface{})) } if d.HasChanges("custom_deploy_recipes") { - apiObject.Deploy = flex.ExpandStringList(d.Get("custom_deploy_recipes").([]interface{})) + apiObject.Deploy = flex.ExpandStringValueList(d.Get("custom_deploy_recipes").([]interface{})) } if d.HasChanges("custom_setup_recipes") { - apiObject.Setup = flex.ExpandStringList(d.Get("custom_setup_recipes").([]interface{})) + apiObject.Setup = flex.ExpandStringValueList(d.Get("custom_setup_recipes").([]interface{})) } if d.HasChanges("custom_shutdown_recipes") { - apiObject.Shutdown = flex.ExpandStringList(d.Get("custom_shutdown_recipes").([]interface{})) + apiObject.Shutdown = flex.ExpandStringValueList(d.Get("custom_shutdown_recipes").([]interface{})) } if d.HasChanges("custom_undeploy_recipes") { - apiObject.Undeploy = flex.ExpandStringList(d.Get("custom_undeploy_recipes").([]interface{})) + apiObject.Undeploy = flex.ExpandStringValueList(d.Get("custom_undeploy_recipes").([]interface{})) } input.CustomRecipes = apiObject @@ -785,14 +787,14 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, } if d.HasChanges("custom_security_group_ids") { - input.CustomSecurityGroupIds = flex.ExpandStringSet(d.Get("custom_security_group_ids").(*schema.Set)) + input.CustomSecurityGroupIds = flex.ExpandStringValueSet(d.Get("custom_security_group_ids").(*schema.Set)) } if d.HasChanges("drain_elb_on_shutdown", "instance_shutdown_timeout") { - input.LifecycleEventConfiguration = &opsworks.LifecycleEventConfiguration{ - Shutdown: &opsworks.ShutdownEventConfiguration{ + input.LifecycleEventConfiguration = &awstypes.LifecycleEventConfiguration{ + Shutdown: &awstypes.ShutdownEventConfiguration{ DelayUntilElbConnectionsDrained: aws.Bool(d.Get("drain_elb_on_shutdown").(bool)), - ExecutionTimeout: aws.Int64(int64(d.Get("instance_shutdown_timeout").(int))), + ExecutionTimeout: aws.Int32(int32(d.Get("instance_shutdown_timeout").(int))), }, } } @@ -816,15 +818,15 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, } if d.HasChanges("system_packages") { - input.Packages = flex.ExpandStringSet(d.Get("system_packages").(*schema.Set)) + input.Packages = flex.ExpandStringValueSet(d.Get("system_packages").(*schema.Set)) } if d.HasChanges("use_ebs_optimized_instances") { input.UseEbsOptimizedInstances = aws.Bool(d.Get("install_updates_on_boot").(bool)) } - log.Printf("[DEBUG] Updating OpsWorks Layer: %s", input) - _, err := conn.UpdateLayerWithContext(ctx, input) + log.Printf("[DEBUG] Updating OpsWorks Layer: %#v", input) + _, err := conn.UpdateLayer(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating OpsWorks Layer (%s): %s", d.Id(), err) @@ -835,7 +837,7 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, o, n := d.GetChange("elastic_load_balancer") if v := o.(string); v != "" { - _, err := conn.DetachElasticLoadBalancerWithContext(ctx, &opsworks.DetachElasticLoadBalancerInput{ + _, err := conn.DetachElasticLoadBalancer(ctx, &opsworks.DetachElasticLoadBalancerInput{ ElasticLoadBalancerName: aws.String(v), LayerId: aws.String(d.Id()), }) @@ -846,7 +848,7 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, } if v := n.(string); v != "" { - _, err := conn.AttachElasticLoadBalancerWithContext(ctx, &opsworks.AttachElasticLoadBalancerInput{ + _, err := conn.AttachElasticLoadBalancer(ctx, &opsworks.AttachElasticLoadBalancerInput{ ElasticLoadBalancerName: aws.String(v), LayerId: aws.String(d.Id()), }) @@ -861,7 +863,7 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, input := expandSetLoadBasedAutoScalingInput(d.Get("load_based_auto_scaling").([]interface{})[0].(map[string]interface{})) input.LayerId = aws.String(d.Id()) - _, err := conn.SetLoadBasedAutoScalingWithContext(ctx, input) + _, err := conn.SetLoadBasedAutoScaling(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "setting OpsWorks Layer (%s) load-based auto scaling configuration: %s", d.Id(), err) @@ -873,14 +875,14 @@ func (lt *opsworksLayerType) Update(ctx context.Context, d *schema.ResourceData, func (lt *opsworksLayerType) Delete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) log.Printf("[DEBUG] Deleting OpsWorks Layer: %s", d.Id()) - _, err := conn.DeleteLayerWithContext(ctx, &opsworks.DeleteLayerInput{ + _, err := conn.DeleteLayer(ctx, &opsworks.DeleteLayerInput{ LayerId: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil } @@ -890,7 +892,7 @@ func (lt *opsworksLayerType) Delete(ctx context.Context, d *schema.ResourceData, if v, ok := d.GetOk("ecs_cluster_arn"); ok { arn := v.(string) - _, err := conn.DeregisterEcsClusterWithContext(ctx, &opsworks.DeregisterEcsClusterInput{ + _, err := conn.DeregisterEcsCluster(ctx, &opsworks.DeregisterEcsClusterInput{ EcsClusterArn: aws.String(arn), }) @@ -902,14 +904,14 @@ func (lt *opsworksLayerType) Delete(ctx context.Context, d *schema.ResourceData, return nil } -func FindLayerByID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*opsworks.Layer, error) { +func findLayerByID(ctx context.Context, conn *opsworks.Client, id string) (*awstypes.Layer, error) { input := &opsworks.DescribeLayersInput{ - LayerIds: aws.StringSlice([]string{id}), + LayerIds: []string{id}, } - output, err := conn.DescribeLayersWithContext(ctx, input) + output, err := conn.DescribeLayers(ctx, input) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -920,7 +922,7 @@ func FindLayerByID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*op return nil, err } - if output == nil || len(output.Layers) == 0 || output.Layers[0] == nil { + if output == nil || len(output.Layers) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -928,21 +930,21 @@ func FindLayerByID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*op return nil, tfresource.NewTooManyResultsError(count, input) } - return output.Layers[0], nil + return tfresource.AssertSingleValueResult(output.Layers) } -func findElasticLoadBalancerByLayerID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*opsworks.ElasticLoadBalancer, error) { +func findElasticLoadBalancerByLayerID(ctx context.Context, conn *opsworks.Client, id string) (*awstypes.ElasticLoadBalancer, error) { input := &opsworks.DescribeElasticLoadBalancersInput{ - LayerIds: aws.StringSlice([]string{id}), + LayerIds: []string{id}, } - output, err := conn.DescribeElasticLoadBalancersWithContext(ctx, input) + output, err := conn.DescribeElasticLoadBalancers(ctx, input) if err != nil { return nil, err } - if output == nil || len(output.ElasticLoadBalancers) == 0 || output.ElasticLoadBalancers[0] == nil { + if output == nil || len(output.ElasticLoadBalancers) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -950,21 +952,21 @@ func findElasticLoadBalancerByLayerID(ctx context.Context, conn *opsworks.OpsWor return nil, tfresource.NewTooManyResultsError(count, input) } - return output.ElasticLoadBalancers[0], nil + return tfresource.AssertSingleValueResult(output.ElasticLoadBalancers) } -func findLoadBasedAutoScalingConfigurationByLayerID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*opsworks.LoadBasedAutoScalingConfiguration, error) { +func findLoadBasedAutoScalingConfigurationByLayerID(ctx context.Context, conn *opsworks.Client, id string) (*awstypes.LoadBasedAutoScalingConfiguration, error) { input := &opsworks.DescribeLoadBasedAutoScalingInput{ - LayerIds: aws.StringSlice([]string{id}), + LayerIds: []string{id}, } - output, err := conn.DescribeLoadBasedAutoScalingWithContext(ctx, input) + output, err := conn.DescribeLoadBasedAutoScaling(ctx, input) if err != nil { return nil, err } - if output == nil || len(output.LoadBasedAutoScalingConfigurations) == 0 || output.LoadBasedAutoScalingConfigurations[0] == nil { + if output == nil || len(output.LoadBasedAutoScalingConfigurations) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -972,7 +974,7 @@ func findLoadBasedAutoScalingConfigurationByLayerID(ctx context.Context, conn *o return nil, tfresource.NewTooManyResultsError(count, input) } - return output.LoadBasedAutoScalingConfigurations[0], nil + return tfresource.AssertSingleValueResult(output.LoadBasedAutoScalingConfigurations) } func (m opsworksLayerTypeAttributeMap) apiAttributesToResourceData(apiAttributes map[string]string, d *schema.ResourceData) error { @@ -983,7 +985,7 @@ func (m opsworksLayerTypeAttributeMap) apiAttributesToResourceData(apiAttributes continue } - if v, ok := apiAttributes[attr.AttrName]; ok { + if v, ok := apiAttributes[string(attr.AttrName)]; ok { switch typ := attr.Type; typ { case schema.TypeString: d.Set(k, v) @@ -1014,11 +1016,11 @@ func (m opsworksLayerTypeAttributeMap) resourceDataToAPIAttributes(d *schema.Res switch typ := attr.Type; typ { case schema.TypeString: - apiAttributes[attr.AttrName] = v.(string) + apiAttributes[string(attr.AttrName)] = v.(string) case schema.TypeInt: - apiAttributes[attr.AttrName] = strconv.Itoa(v.(int)) + apiAttributes[string(attr.AttrName)] = strconv.Itoa(v.(int)) case schema.TypeBool: - apiAttributes[attr.AttrName] = strconv.FormatBool(v.(bool)) + apiAttributes[string(attr.AttrName)] = strconv.FormatBool(v.(bool)) default: return nil, fmt.Errorf("unsupported OpsWorks Layer (%s) attribute (%s) type: %s", d.Id(), k, typ) } @@ -1027,12 +1029,12 @@ func (m opsworksLayerTypeAttributeMap) resourceDataToAPIAttributes(d *schema.Res return apiAttributes, nil } -func expandCloudWatchLogsConfiguration(tfMap map[string]interface{}) *opsworks.CloudWatchLogsConfiguration { +func expandCloudWatchLogsConfiguration(tfMap map[string]interface{}) *awstypes.CloudWatchLogsConfiguration { if tfMap == nil { return nil } - apiObject := &opsworks.CloudWatchLogsConfiguration{} + apiObject := &awstypes.CloudWatchLogsConfiguration{} if v, ok := tfMap[names.AttrEnabled].(bool); ok { apiObject.Enabled = aws.Bool(v) @@ -1045,23 +1047,19 @@ func expandCloudWatchLogsConfiguration(tfMap map[string]interface{}) *opsworks.C return apiObject } -func expandCloudWatchLogsLogStream(tfMap map[string]interface{}) *opsworks.CloudWatchLogsLogStream { - if tfMap == nil { - return nil - } - - apiObject := &opsworks.CloudWatchLogsLogStream{} +func expandCloudWatchLogsLogStream(tfMap map[string]interface{}) awstypes.CloudWatchLogsLogStream { + apiObject := awstypes.CloudWatchLogsLogStream{} if v, ok := tfMap["batch_count"].(int); ok && v != 0 { - apiObject.BatchCount = aws.Int64(int64(v)) + apiObject.BatchCount = aws.Int32(int32(v)) } if v, ok := tfMap["batch_size"].(int); ok && v != 0 { - apiObject.BatchSize = aws.Int64(int64(v)) + apiObject.BatchSize = aws.Int32(int32(v)) } if v, ok := tfMap["buffer_duration"].(int); ok && v != 0 { - apiObject.BufferDuration = aws.Int64(int64(v)) + apiObject.BufferDuration = aws.Int32(int32(v)) } if v, ok := tfMap["datetime_format"].(string); ok && v != "" { @@ -1069,7 +1067,7 @@ func expandCloudWatchLogsLogStream(tfMap map[string]interface{}) *opsworks.Cloud } if v, ok := tfMap["encoding"].(string); ok && v != "" { - apiObject.Encoding = aws.String(v) + apiObject.Encoding = awstypes.CloudWatchLogsEncoding(v) } if v, ok := tfMap["file"].(string); ok && v != "" { @@ -1081,7 +1079,7 @@ func expandCloudWatchLogsLogStream(tfMap map[string]interface{}) *opsworks.Cloud } if v, ok := tfMap["initial_position"].(string); ok && v != "" { - apiObject.InitialPosition = aws.String(v) + apiObject.InitialPosition = awstypes.CloudWatchLogsInitialPosition(v) } if v, ok := tfMap[names.AttrLogGroupName].(string); ok && v != "" { @@ -1093,18 +1091,18 @@ func expandCloudWatchLogsLogStream(tfMap map[string]interface{}) *opsworks.Cloud } if v, ok := tfMap["time_zone"].(string); ok && v != "" { - apiObject.TimeZone = aws.String(v) + apiObject.TimeZone = awstypes.CloudWatchLogsTimeZone(v) } return apiObject } -func expandCloudWatchLogsLogStreams(tfList []interface{}) []*opsworks.CloudWatchLogsLogStream { +func expandCloudWatchLogsLogStreams(tfList []interface{}) []awstypes.CloudWatchLogsLogStream { if len(tfList) == 0 { return nil } - var apiObjects []*opsworks.CloudWatchLogsLogStream + var apiObjects []awstypes.CloudWatchLogsLogStream for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -1113,19 +1111,13 @@ func expandCloudWatchLogsLogStreams(tfList []interface{}) []*opsworks.CloudWatch continue } - apiObject := expandCloudWatchLogsLogStream(tfMap) - - if apiObject == nil { - continue - } - - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, expandCloudWatchLogsLogStream(tfMap)) } return apiObjects } -func flattenCloudWatchLogsConfiguration(apiObject *opsworks.CloudWatchLogsConfiguration) map[string]interface{} { +func flattenCloudWatchLogsConfiguration(apiObject *awstypes.CloudWatchLogsConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -1133,7 +1125,7 @@ func flattenCloudWatchLogsConfiguration(apiObject *opsworks.CloudWatchLogsConfig tfMap := map[string]interface{}{} if v := apiObject.Enabled; v != nil { - tfMap[names.AttrEnabled] = aws.BoolValue(v) + tfMap[names.AttrEnabled] = aws.ToBool(v) } if v := apiObject.LogStreams; v != nil { @@ -1143,61 +1135,51 @@ func flattenCloudWatchLogsConfiguration(apiObject *opsworks.CloudWatchLogsConfig return tfMap } -func flattenCloudWatchLogsLogStream(apiObject *opsworks.CloudWatchLogsLogStream) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenCloudWatchLogsLogStream(apiObject awstypes.CloudWatchLogsLogStream) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.BatchCount; v != nil { - tfMap["batch_count"] = aws.Int64Value(v) + tfMap["batch_count"] = aws.ToInt32(v) } if v := apiObject.BatchSize; v != nil { - tfMap["batch_size"] = aws.Int64Value(v) + tfMap["batch_size"] = aws.ToInt32(v) } if v := apiObject.BufferDuration; v != nil { - tfMap["buffer_duration"] = aws.Int64Value(v) + tfMap["buffer_duration"] = aws.ToInt32(v) } if v := apiObject.DatetimeFormat; v != nil { - tfMap["datetime_format"] = aws.StringValue(v) + tfMap["datetime_format"] = aws.ToString(v) } - if v := apiObject.Encoding; v != nil { - tfMap["encoding"] = aws.StringValue(v) - } + tfMap["encoding"] = apiObject.Encoding if v := apiObject.File; v != nil { - tfMap["file"] = aws.StringValue(v) + tfMap["file"] = aws.ToString(v) } if v := apiObject.FileFingerprintLines; v != nil { - tfMap["file_fingerprint_lines"] = aws.StringValue(v) + tfMap["file_fingerprint_lines"] = aws.ToString(v) } - if v := apiObject.InitialPosition; v != nil { - tfMap["initial_position"] = aws.StringValue(v) - } + tfMap["initial_position"] = apiObject.InitialPosition if v := apiObject.LogGroupName; v != nil { - tfMap[names.AttrLogGroupName] = aws.StringValue(v) + tfMap[names.AttrLogGroupName] = aws.ToString(v) } if v := apiObject.MultiLineStartPattern; v != nil { - tfMap["multiline_start_pattern"] = aws.StringValue(v) + tfMap["multiline_start_pattern"] = aws.ToString(v) } - if v := apiObject.TimeZone; v != nil { - tfMap["time_zone"] = aws.StringValue(v) - } + tfMap["time_zone"] = apiObject.TimeZone return tfMap } -func flattenCloudWatchLogsLogStreams(apiObjects []*opsworks.CloudWatchLogsLogStream) []interface{} { +func flattenCloudWatchLogsLogStreams(apiObjects []awstypes.CloudWatchLogsLogStream) []interface{} { if len(apiObjects) == 0 { return nil } @@ -1205,29 +1187,21 @@ func flattenCloudWatchLogsLogStreams(apiObjects []*opsworks.CloudWatchLogsLogStr var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenCloudWatchLogsLogStream(apiObject)) } return tfList } -func expandVolumeConfiguration(tfMap map[string]interface{}) *opsworks.VolumeConfiguration { - if tfMap == nil { - return nil - } - - apiObject := &opsworks.VolumeConfiguration{} +func expandVolumeConfiguration(tfMap map[string]interface{}) awstypes.VolumeConfiguration { + apiObject := awstypes.VolumeConfiguration{} if v, ok := tfMap[names.AttrEncrypted].(bool); ok { apiObject.Encrypted = aws.Bool(v) } if v, ok := tfMap[names.AttrIOPS].(int); ok && v != 0 { - apiObject.Iops = aws.Int64(int64(v)) + apiObject.Iops = aws.Int32(int32(v)) } if v, ok := tfMap["mount_point"].(string); ok && v != "" { @@ -1235,17 +1209,17 @@ func expandVolumeConfiguration(tfMap map[string]interface{}) *opsworks.VolumeCon } if v, ok := tfMap["number_of_disks"].(int); ok && v != 0 { - apiObject.NumberOfDisks = aws.Int64(int64(v)) + apiObject.NumberOfDisks = aws.Int32(int32(v)) } if v, ok := tfMap["raid_level"].(string); ok && v != "" { if v, err := strconv.Atoi(v); err == nil { - apiObject.RaidLevel = aws.Int64(int64(v)) + apiObject.RaidLevel = aws.Int32(int32(v)) } } if v, ok := tfMap[names.AttrSize].(int); ok && v != 0 { - apiObject.Size = aws.Int64(int64(v)) + apiObject.Size = aws.Int32(int32(v)) } if v, ok := tfMap[names.AttrType].(string); ok && v != "" { @@ -1255,12 +1229,12 @@ func expandVolumeConfiguration(tfMap map[string]interface{}) *opsworks.VolumeCon return apiObject } -func expandVolumeConfigurations(tfList []interface{}) []*opsworks.VolumeConfiguration { +func expandVolumeConfigurations(tfList []interface{}) []awstypes.VolumeConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*opsworks.VolumeConfiguration + var apiObjects []awstypes.VolumeConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -1269,57 +1243,47 @@ func expandVolumeConfigurations(tfList []interface{}) []*opsworks.VolumeConfigur continue } - apiObject := expandVolumeConfiguration(tfMap) - - if apiObject == nil { - continue - } - - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, expandVolumeConfiguration(tfMap)) } return apiObjects } -func flattenVolumeConfiguration(apiObject *opsworks.VolumeConfiguration) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenVolumeConfiguration(apiObject awstypes.VolumeConfiguration) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.Encrypted; v != nil { - tfMap[names.AttrEncrypted] = aws.BoolValue(v) + tfMap[names.AttrEncrypted] = aws.ToBool(v) } if v := apiObject.Iops; v != nil { - tfMap[names.AttrIOPS] = aws.Int64Value(v) + tfMap[names.AttrIOPS] = aws.ToInt32(v) } if v := apiObject.MountPoint; v != nil { - tfMap["mount_point"] = aws.StringValue(v) + tfMap["mount_point"] = aws.ToString(v) } if v := apiObject.NumberOfDisks; v != nil { - tfMap["number_of_disks"] = aws.Int64Value(v) + tfMap["number_of_disks"] = aws.ToInt32(v) } if v := apiObject.RaidLevel; v != nil { - tfMap["raid_level"] = strconv.Itoa(int(aws.Int64Value(v))) + tfMap["raid_level"] = strconv.Itoa(int(aws.ToInt32(v))) } if v := apiObject.Size; v != nil { - tfMap[names.AttrSize] = aws.Int64Value(v) + tfMap[names.AttrSize] = aws.ToInt32(v) } if v := apiObject.VolumeType; v != nil { - tfMap[names.AttrType] = aws.StringValue(v) + tfMap[names.AttrType] = aws.ToString(v) } return tfMap } -func flattenVolumeConfigurations(apiObjects []*opsworks.VolumeConfiguration) []interface{} { +func flattenVolumeConfigurations(apiObjects []awstypes.VolumeConfiguration) []interface{} { if len(apiObjects) == 0 { return nil } @@ -1327,10 +1291,6 @@ func flattenVolumeConfigurations(apiObjects []*opsworks.VolumeConfiguration) []i var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenVolumeConfiguration(apiObject)) } @@ -1359,15 +1319,15 @@ func expandSetLoadBasedAutoScalingInput(tfMap map[string]interface{}) *opsworks. return apiObject } -func expandAutoScalingThresholds(tfMap map[string]interface{}) *opsworks.AutoScalingThresholds { +func expandAutoScalingThresholds(tfMap map[string]interface{}) *awstypes.AutoScalingThresholds { if tfMap == nil { return nil } - apiObject := &opsworks.AutoScalingThresholds{} + apiObject := &awstypes.AutoScalingThresholds{} if v, ok := tfMap["alarms"].([]interface{}); ok && len(v) > 0 { - apiObject.Alarms = flex.ExpandStringList(v) + apiObject.Alarms = flex.ExpandStringValueList(v) } if v, ok := tfMap["cpu_threshold"].(float64); ok && v != 0.0 { @@ -1375,11 +1335,11 @@ func expandAutoScalingThresholds(tfMap map[string]interface{}) *opsworks.AutoSca } if v, ok := tfMap["ignore_metrics_time"].(int); ok && v != 0 { - apiObject.IgnoreMetricsTime = aws.Int64(int64(v)) + apiObject.IgnoreMetricsTime = aws.Int32(int32(v)) } if v, ok := tfMap[names.AttrInstanceCount].(int); ok && v != 0 { - apiObject.InstanceCount = aws.Int64(int64(v)) + apiObject.InstanceCount = aws.Int32(int32(v)) } if v, ok := tfMap["load_threshold"].(float64); ok && v != 0.0 { @@ -1391,13 +1351,13 @@ func expandAutoScalingThresholds(tfMap map[string]interface{}) *opsworks.AutoSca } if v, ok := tfMap["thresholds_wait_time"].(int); ok && v != 0 { - apiObject.ThresholdsWaitTime = aws.Int64(int64(v)) + apiObject.ThresholdsWaitTime = aws.Int32(int32(v)) } return apiObject } -func flattenLoadBasedAutoScalingConfiguration(apiObject *opsworks.LoadBasedAutoScalingConfiguration) map[string]interface{} { +func flattenLoadBasedAutoScalingConfiguration(apiObject *awstypes.LoadBasedAutoScalingConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -1409,7 +1369,7 @@ func flattenLoadBasedAutoScalingConfiguration(apiObject *opsworks.LoadBasedAutoS } if v := apiObject.Enable; v != nil { - tfMap["enable"] = aws.BoolValue(v) + tfMap["enable"] = aws.ToBool(v) } if v := apiObject.UpScaling; v != nil { @@ -1419,7 +1379,7 @@ func flattenLoadBasedAutoScalingConfiguration(apiObject *opsworks.LoadBasedAutoS return tfMap } -func flattenAutoScalingThresholds(apiObject *opsworks.AutoScalingThresholds) map[string]interface{} { +func flattenAutoScalingThresholds(apiObject *awstypes.AutoScalingThresholds) map[string]interface{} { if apiObject == nil { return nil } @@ -1427,31 +1387,31 @@ func flattenAutoScalingThresholds(apiObject *opsworks.AutoScalingThresholds) map tfMap := map[string]interface{}{} if v := apiObject.Alarms; v != nil { - tfMap["alarms"] = aws.StringValueSlice(v) + tfMap["alarms"] = v } if v := apiObject.CpuThreshold; v != nil { - tfMap["cpu_threshold"] = aws.Float64Value(v) + tfMap["cpu_threshold"] = aws.ToFloat64(v) } if v := apiObject.IgnoreMetricsTime; v != nil { - tfMap["ignore_metrics_time"] = aws.Int64Value(v) + tfMap["ignore_metrics_time"] = aws.ToInt32(v) } if v := apiObject.InstanceCount; v != nil { - tfMap[names.AttrInstanceCount] = aws.Int64Value(v) + tfMap[names.AttrInstanceCount] = aws.ToInt32(v) } if v := apiObject.LoadThreshold; v != nil { - tfMap["load_threshold"] = aws.Float64Value(v) + tfMap["load_threshold"] = aws.ToFloat64(v) } if v := apiObject.MemoryThreshold; v != nil { - tfMap["memory_threshold"] = aws.Float64Value(v) + tfMap["memory_threshold"] = aws.ToFloat64(v) } if v := apiObject.ThresholdsWaitTime; v != nil { - tfMap["thresholds_wait_time"] = aws.Int64Value(v) + tfMap["thresholds_wait_time"] = aws.ToInt32(v) } return tfMap diff --git a/internal/service/opsworks/layers_test.go b/internal/service/opsworks/layers_test.go index c6762afc4a3..aacc8bca4fc 100644 --- a/internal/service/opsworks/layers_test.go +++ b/internal/service/opsworks/layers_test.go @@ -7,7 +7,7 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -16,7 +16,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -func testAccCheckLayerExists(ctx context.Context, n string, v *opsworks.Layer) resource.TestCheckFunc { +func testAccCheckLayerExists(ctx context.Context, n string, v *awstypes.Layer) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -27,7 +27,7 @@ func testAccCheckLayerExists(ctx context.Context, n string, v *opsworks.Layer) r return fmt.Errorf("No OpsWorks Layer ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) output, err := tfopsworks.FindLayerByID(ctx, conn, rs.Primary.ID) @@ -42,7 +42,7 @@ func testAccCheckLayerExists(ctx context.Context, n string, v *opsworks.Layer) r } func testAccCheckLayerDestroy(ctx context.Context, resourceType string, s *terraform.State) error { // nosemgrep:ci.semgrep.acctest.naming.destroy-check-signature - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != resourceType { diff --git a/internal/service/opsworks/memcached_layer.go b/internal/service/opsworks/memcached_layer.go index 293b82933b1..2a86332a310 100644 --- a/internal/service/opsworks/memcached_layer.go +++ b/internal/service/opsworks/memcached_layer.go @@ -4,20 +4,20 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_memcached_layer", name="Memcached Layer") // @Tags(identifierAttribute="arn") -func ResourceMemcachedLayer() *schema.Resource { +func resourceMemcachedLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeMemcached, + TypeName: awstypes.LayerTypeMemcached, DefaultLayerName: "Memcached", Attributes: map[string]*opsworksLayerTypeAttribute{ "allocated_memory": { - AttrName: opsworks.LayerAttributesKeysMemcachedMemory, + AttrName: awstypes.LayerAttributesKeysMemcachedMemory, Type: schema.TypeInt, Default: 512, }, diff --git a/internal/service/opsworks/memcached_layer_test.go b/internal/service/opsworks/memcached_layer_test.go index f0bae8c588a..4285632a342 100644 --- a/internal/service/opsworks/memcached_layer_test.go +++ b/internal/service/opsworks/memcached_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksMemcachedLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_memcached_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckMemcachedLayerDestroy(ctx), diff --git a/internal/service/opsworks/mysql_layer.go b/internal/service/opsworks/mysql_layer.go index 79f9eca0dee..0cf7c038110 100644 --- a/internal/service/opsworks/mysql_layer.go +++ b/internal/service/opsworks/mysql_layer.go @@ -4,25 +4,25 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_mysql_layer", name="MySQL Layer") // @Tags(identifierAttribute="arn") -func ResourceMySQLLayer() *schema.Resource { +func resourceMySQLLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeDbMaster, + TypeName: awstypes.LayerTypeDbMaster, DefaultLayerName: "MySQL", Attributes: map[string]*opsworksLayerTypeAttribute{ "root_password": { - AttrName: opsworks.LayerAttributesKeysMysqlRootPassword, + AttrName: awstypes.LayerAttributesKeysMysqlRootPassword, Type: schema.TypeString, WriteOnly: true, }, "root_password_on_all_instances": { - AttrName: opsworks.LayerAttributesKeysMysqlRootPasswordUbiquitous, + AttrName: awstypes.LayerAttributesKeysMysqlRootPasswordUbiquitous, Type: schema.TypeBool, Default: true, }, diff --git a/internal/service/opsworks/mysql_layer_test.go b/internal/service/opsworks/mysql_layer_test.go index 1fd4031ac90..7813f40bf3f 100644 --- a/internal/service/opsworks/mysql_layer_test.go +++ b/internal/service/opsworks/mysql_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksMySQLLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_mysql_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckMySQLLayerDestroy(ctx), diff --git a/internal/service/opsworks/nodejs_app_layer.go b/internal/service/opsworks/nodejs_app_layer.go index 469ceca5b24..a437d7e5769 100644 --- a/internal/service/opsworks/nodejs_app_layer.go +++ b/internal/service/opsworks/nodejs_app_layer.go @@ -4,20 +4,20 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_nodejs_app_layer", name="NodeJS App Layer") // @Tags(identifierAttribute="arn") -func ResourceNodejsAppLayer() *schema.Resource { +func resourceNodejsAppLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeNodejsApp, + TypeName: awstypes.LayerTypeNodejsApp, DefaultLayerName: "Node.js App Server", Attributes: map[string]*opsworksLayerTypeAttribute{ "nodejs_version": { - AttrName: opsworks.LayerAttributesKeysNodejsVersion, + AttrName: awstypes.LayerAttributesKeysNodejsVersion, Type: schema.TypeString, Default: "0.10.38", }, diff --git a/internal/service/opsworks/nodejs_app_layer_test.go b/internal/service/opsworks/nodejs_app_layer_test.go index d357f7b3560..df5661867ad 100644 --- a/internal/service/opsworks/nodejs_app_layer_test.go +++ b/internal/service/opsworks/nodejs_app_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksNodejsAppLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_nodejs_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckNodejsAppLayerDestroy(ctx), diff --git a/internal/service/opsworks/permission.go b/internal/service/opsworks/permission.go index ee94f1ae78c..33469b40b4f 100644 --- a/internal/service/opsworks/permission.go +++ b/internal/service/opsworks/permission.go @@ -7,20 +7,21 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "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/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// @SDKResource("aws_opsworks_permission") -func ResourcePermission() *schema.Resource { +// @SDKResource("aws_opsworks_permission", name="Permission") +func resourcePermission() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceSetPermission, ReadWithoutTimeout: resourcePermissionRead, @@ -66,7 +67,7 @@ func ResourcePermission() *schema.Resource { func resourceSetPermission(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) iamUserARN := d.Get("user_arn").(string) stackID := d.Get("stack_id").(string) @@ -86,9 +87,9 @@ func resourceSetPermission(ctx context.Context, d *schema.ResourceData, meta int input.Level = aws.String(d.Get("level").(string)) } - _, err := tfresource.RetryWhenAWSErrMessageContains(ctx, propagationTimeout, func() (interface{}, error) { - return conn.SetPermissionWithContext(ctx, input) - }, opsworks.ErrCodeResourceNotFoundException, "Unable to find user with ARN") + _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.ResourceNotFoundException](ctx, propagationTimeout, func() (interface{}, error) { + return conn.SetPermission(ctx, input) + }, "Unable to find user with ARN") if err != nil { return sdkdiag.AppendErrorf(diags, "setting OpsWorks Permission (%s): %s", id, err) @@ -103,9 +104,9 @@ func resourceSetPermission(ctx context.Context, d *schema.ResourceData, meta int func resourcePermissionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) - permission, err := FindPermissionByTwoPartKey(ctx, conn, d.Get("user_arn").(string), d.Get("stack_id").(string)) + permission, err := findPermissionByTwoPartKey(ctx, conn, d.Get("user_arn").(string), d.Get("stack_id").(string)) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] OpsWorks Permission %s not found, removing from state", d.Id()) @@ -126,15 +127,15 @@ func resourcePermissionRead(ctx context.Context, d *schema.ResourceData, meta in return diags } -func FindPermissionByTwoPartKey(ctx context.Context, conn *opsworks.OpsWorks, iamUserARN, stackID string) (*opsworks.Permission, error) { +func findPermissionByTwoPartKey(ctx context.Context, conn *opsworks.Client, iamUserARN, stackID string) (*awstypes.Permission, error) { input := &opsworks.DescribePermissionsInput{ IamUserArn: aws.String(iamUserARN), StackId: aws.String(stackID), } - output, err := conn.DescribePermissionsWithContext(ctx, input) + output, err := conn.DescribePermissions(ctx, input) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -145,7 +146,7 @@ func FindPermissionByTwoPartKey(ctx context.Context, conn *opsworks.OpsWorks, ia return nil, err } - if output == nil || len(output.Permissions) == 0 || output.Permissions[0] == nil { + if output == nil || len(output.Permissions) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -153,5 +154,5 @@ func FindPermissionByTwoPartKey(ctx context.Context, conn *opsworks.OpsWorks, ia return nil, tfresource.NewTooManyResultsError(count, input) } - return output.Permissions[0], nil + return tfresource.AssertSingleValueResult(output.Permissions) } diff --git a/internal/service/opsworks/permission_test.go b/internal/service/opsworks/permission_test.go index 1deb1b918eb..72968759873 100644 --- a/internal/service/opsworks/permission_test.go +++ b/internal/service/opsworks/permission_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -19,13 +19,15 @@ import ( ) func TestAccOpsWorksPermission_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_permission.test" - var opsperm opsworks.Permission + var opsperm awstypes.Permission resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: acctest.CheckDestroyNoop, @@ -72,13 +74,15 @@ func TestAccOpsWorksPermission_basic(t *testing.T) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/4804 func TestAccOpsWorksPermission_self(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var opsperm opsworks.Permission + var opsperm awstypes.Permission rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_permission.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: acctest.CheckDestroyNoop, @@ -103,7 +107,7 @@ func TestAccOpsWorksPermission_self(t *testing.T) { }) } -func testAccCheckPermissionExists(ctx context.Context, n string, v *opsworks.Permission) resource.TestCheckFunc { +func testAccCheckPermissionExists(ctx context.Context, n string, v *awstypes.Permission) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -114,7 +118,7 @@ func testAccCheckPermissionExists(ctx context.Context, n string, v *opsworks.Per return fmt.Errorf("No OpsWorks Layer ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) output, err := tfopsworks.FindPermissionByTwoPartKey(ctx, conn, rs.Primary.Attributes["user_arn"], rs.Primary.Attributes["stack_id"]) diff --git a/internal/service/opsworks/php_app_layer.go b/internal/service/opsworks/php_app_layer.go index e8f8a652716..e299d9ca35e 100644 --- a/internal/service/opsworks/php_app_layer.go +++ b/internal/service/opsworks/php_app_layer.go @@ -4,15 +4,15 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_php_app_layer", name="PHP App Layer") // @Tags(identifierAttribute="arn") -func ResourcePHPAppLayer() *schema.Resource { +func resourcePHPAppLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypePhpApp, + TypeName: awstypes.LayerTypePhpApp, DefaultLayerName: "PHP App Server", Attributes: map[string]*opsworksLayerTypeAttribute{}, diff --git a/internal/service/opsworks/php_app_layer_test.go b/internal/service/opsworks/php_app_layer_test.go index ea1993046f8..27d5f3b3c5c 100644 --- a/internal/service/opsworks/php_app_layer_test.go +++ b/internal/service/opsworks/php_app_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksPHPAppLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_php_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckPHPAppLayerDestroy(ctx), diff --git a/internal/service/opsworks/rails_app_layer.go b/internal/service/opsworks/rails_app_layer.go index 0b0ee1e1485..03155197c68 100644 --- a/internal/service/opsworks/rails_app_layer.go +++ b/internal/service/opsworks/rails_app_layer.go @@ -4,45 +4,45 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_rails_app_layer", name="Rails App Layer") // @Tags(identifierAttribute="arn") -func ResourceRailsAppLayer() *schema.Resource { +func resourceRailsAppLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeRailsApp, + TypeName: awstypes.LayerTypeRailsApp, DefaultLayerName: "Rails App Server", Attributes: map[string]*opsworksLayerTypeAttribute{ "app_server": { - AttrName: opsworks.LayerAttributesKeysRailsStack, + AttrName: awstypes.LayerAttributesKeysRailsStack, Type: schema.TypeString, Default: "apache_passenger", }, "bundler_version": { - AttrName: opsworks.LayerAttributesKeysBundlerVersion, + AttrName: awstypes.LayerAttributesKeysBundlerVersion, Type: schema.TypeString, Default: "1.5.3", }, "manage_bundler": { - AttrName: opsworks.LayerAttributesKeysManageBundler, + AttrName: awstypes.LayerAttributesKeysManageBundler, Type: schema.TypeBool, Default: true, }, "passenger_version": { - AttrName: opsworks.LayerAttributesKeysPassengerVersion, + AttrName: awstypes.LayerAttributesKeysPassengerVersion, Type: schema.TypeString, Default: "4.0.46", }, "ruby_version": { - AttrName: opsworks.LayerAttributesKeysRubyVersion, + AttrName: awstypes.LayerAttributesKeysRubyVersion, Type: schema.TypeString, Default: "2.0.0", }, "rubygems_version": { - AttrName: opsworks.LayerAttributesKeysRubygemsVersion, + AttrName: awstypes.LayerAttributesKeysRubygemsVersion, Type: schema.TypeString, Default: "2.2.2", }, diff --git a/internal/service/opsworks/rails_app_layer_test.go b/internal/service/opsworks/rails_app_layer_test.go index a260c6a636a..21a35949698 100644 --- a/internal/service/opsworks/rails_app_layer_test.go +++ b/internal/service/opsworks/rails_app_layer_test.go @@ -9,8 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -20,13 +19,15 @@ import ( ) func TestAccOpsWorksRailsAppLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_rails_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRailsAppLayerDestroy(ctx), @@ -76,13 +77,15 @@ func TestAccOpsWorksRailsAppLayer_basic(t *testing.T) { } func TestAccOpsWorksRailsAppLayer_disappears(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_rails_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRailsAppLayerDestroy(ctx), @@ -100,13 +103,15 @@ func TestAccOpsWorksRailsAppLayer_disappears(t *testing.T) { } func TestAccOpsWorksRailsAppLayer_tags(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_rails_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRailsAppLayerDestroy(ctx), @@ -141,20 +146,22 @@ func TestAccOpsWorksRailsAppLayer_tags(t *testing.T) { } func TestAccOpsWorksRailsAppLayer_tagsAlternateRegion(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_rails_app_layer.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) // This test requires a very particular AWS Region configuration // in order to exercise the OpsWorks classic endpoint functionality. acctest.PreCheckMultipleRegion(t, 2) - acctest.PreCheckRegion(t, endpoints.UsEast1RegionID) - acctest.PreCheckAlternateRegionIs(t, endpoints.UsWest1RegionID) + acctest.PreCheckRegion(t, names.USEast1RegionID) + acctest.PreCheckAlternateRegionIs(t, names.USWest1RegionID) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5FactoriesMultipleRegions(ctx, t, 2), @@ -190,13 +197,15 @@ func TestAccOpsWorksRailsAppLayer_tagsAlternateRegion(t *testing.T) { } func TestAccOpsWorksRailsAppLayer_update(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_rails_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRailsAppLayerDestroy(ctx), @@ -237,13 +246,15 @@ func TestAccOpsWorksRailsAppLayer_update(t *testing.T) { } func TestAccOpsWorksRailsAppLayer_elb(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_rails_app_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRailsAppLayerDestroy(ctx), diff --git a/internal/service/opsworks/rds_db_instance.go b/internal/service/opsworks/rds_db_instance.go index b55ec8491d4..374589950ef 100644 --- a/internal/service/opsworks/rds_db_instance.go +++ b/internal/service/opsworks/rds_db_instance.go @@ -7,19 +7,20 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "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/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// @SDKResource("aws_opsworks_rds_db_instance") -func ResourceRDSDBInstance() *schema.Resource { +// @SDKResource("aws_opsworks_rds_db_instance", name="RDS DB Instance") +func resourceRDSDBInstance() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceRDSDBInstanceCreate, UpdateWithoutTimeout: resourceRDSDBInstanceUpdate, @@ -52,7 +53,7 @@ func ResourceRDSDBInstance() *schema.Resource { func resourceRDSDBInstanceCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - client := meta.(*conns.AWSClient).OpsWorksConn(ctx) + client := meta.(*conns.AWSClient).OpsWorksClient(ctx) dbInstanceARN := d.Get("rds_db_instance_arn").(string) stackID := d.Get("stack_id").(string) @@ -64,7 +65,7 @@ func resourceRDSDBInstanceCreate(ctx context.Context, d *schema.ResourceData, me StackId: aws.String(stackID), } - _, err := client.RegisterRdsDbInstanceWithContext(ctx, input) + _, err := client.RegisterRdsDbInstance(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "registering OpsWorks RDS DB Instance (%s): %s", id, err) @@ -77,9 +78,9 @@ func resourceRDSDBInstanceCreate(ctx context.Context, d *schema.ResourceData, me func resourceRDSDBInstanceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) - dbInstance, err := FindRDSDBInstanceByTwoPartKey(ctx, conn, d.Get("rds_db_instance_arn").(string), d.Get("stack_id").(string)) + dbInstance, err := findRDSDBInstanceByTwoPartKey(ctx, conn, d.Get("rds_db_instance_arn").(string), d.Get("stack_id").(string)) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] OpsWorks RDS DB Instance %s not found, removing from state", d.Id()) @@ -100,7 +101,7 @@ func resourceRDSDBInstanceRead(ctx context.Context, d *schema.ResourceData, meta func resourceRDSDBInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - client := meta.(*conns.AWSClient).OpsWorksConn(ctx) + client := meta.(*conns.AWSClient).OpsWorksClient(ctx) input := &opsworks.UpdateRdsDbInstanceInput{ RdsDbInstanceArn: aws.String(d.Get("rds_db_instance_arn").(string)), @@ -114,7 +115,7 @@ func resourceRDSDBInstanceUpdate(ctx context.Context, d *schema.ResourceData, me input.DbUser = aws.String(d.Get("db_user").(string)) } - _, err := client.UpdateRdsDbInstanceWithContext(ctx, input) + _, err := client.UpdateRdsDbInstance(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating OpsWorks RDS DB Instance (%s): %s", d.Id(), err) @@ -125,14 +126,14 @@ func resourceRDSDBInstanceUpdate(ctx context.Context, d *schema.ResourceData, me func resourceRDSDBInstanceDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - client := meta.(*conns.AWSClient).OpsWorksConn(ctx) + client := meta.(*conns.AWSClient).OpsWorksClient(ctx) log.Printf("[DEBUG] Deregistering OpsWorks RDS DB Instance: %s", d.Id()) - _, err := client.DeregisterRdsDbInstanceWithContext(ctx, &opsworks.DeregisterRdsDbInstanceInput{ + _, err := client.DeregisterRdsDbInstance(ctx, &opsworks.DeregisterRdsDbInstanceInput{ RdsDbInstanceArn: aws.String(d.Get("rds_db_instance_arn").(string)), }) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -143,14 +144,14 @@ func resourceRDSDBInstanceDelete(ctx context.Context, d *schema.ResourceData, me return diags } -func FindRDSDBInstanceByTwoPartKey(ctx context.Context, conn *opsworks.OpsWorks, dbInstanceARN, stackID string) (*opsworks.RdsDbInstance, error) { +func findRDSDBInstanceByTwoPartKey(ctx context.Context, conn *opsworks.Client, dbInstanceARN, stackID string) (*awstypes.RdsDbInstance, error) { input := &opsworks.DescribeRdsDbInstancesInput{ StackId: aws.String(stackID), } - output, err := conn.DescribeRdsDbInstancesWithContext(ctx, input) + output, err := conn.DescribeRdsDbInstances(ctx, input) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -166,8 +167,8 @@ func FindRDSDBInstanceByTwoPartKey(ctx context.Context, conn *opsworks.OpsWorks, } for _, v := range output.RdsDbInstances { - if aws.StringValue(v.RdsDbInstanceArn) == dbInstanceARN { - return v, nil + if aws.ToString(v.RdsDbInstanceArn) == dbInstanceARN { + return &v, nil } } diff --git a/internal/service/opsworks/rds_db_instance_test.go b/internal/service/opsworks/rds_db_instance_test.go index eec0e2f113d..0580028b504 100644 --- a/internal/service/opsworks/rds_db_instance_test.go +++ b/internal/service/opsworks/rds_db_instance_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -20,17 +20,19 @@ import ( ) func TestAccOpsWorksRDSDBInstance_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) if testing.Short() { t.Skip("skipping long-running test in short mode") } - var v opsworks.RdsDbInstance + var v awstypes.RdsDbInstance resourceName := "aws_opsworks_rds_db_instance.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRDSDBInstanceDestroy(ctx), @@ -64,17 +66,19 @@ func TestAccOpsWorksRDSDBInstance_basic(t *testing.T) { } func TestAccOpsWorksRDSDBInstance_disappears(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) if testing.Short() { t.Skip("skipping long-running test in short mode") } - var v opsworks.RdsDbInstance + var v awstypes.RdsDbInstance resourceName := "aws_opsworks_rds_db_instance.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckRDSDBInstanceDestroy(ctx), @@ -91,7 +95,7 @@ func TestAccOpsWorksRDSDBInstance_disappears(t *testing.T) { }) } -func testAccCheckRDSDBInstanceExists(ctx context.Context, n string, v *opsworks.RdsDbInstance) resource.TestCheckFunc { +func testAccCheckRDSDBInstanceExists(ctx context.Context, n string, v *awstypes.RdsDbInstance) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -102,7 +106,7 @@ func testAccCheckRDSDBInstanceExists(ctx context.Context, n string, v *opsworks. return fmt.Errorf("No OpsWorks RDS DB Instance ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) output, err := tfopsworks.FindRDSDBInstanceByTwoPartKey(ctx, conn, rs.Primary.Attributes["rds_db_instance_arn"], rs.Primary.Attributes["stack_id"]) @@ -118,7 +122,7 @@ func testAccCheckRDSDBInstanceExists(ctx context.Context, n string, v *opsworks. func testAccCheckRDSDBInstanceDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_opsworks_rds_db_instance" { diff --git a/internal/service/opsworks/service_endpoint_resolver_gen.go b/internal/service/opsworks/service_endpoint_resolver_gen.go index 6f09d847eec..8067dbf5d88 100644 --- a/internal/service/opsworks/service_endpoint_resolver_gen.go +++ b/internal/service/opsworks/service_endpoint_resolver_gen.go @@ -6,65 +6,63 @@ import ( "context" "fmt" "net" - "net/url" - endpoints_sdkv1 "github.com/aws/aws-sdk-go/aws/endpoints" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + opsworks_sdkv2 "github.com/aws/aws-sdk-go-v2/service/opsworks" + smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) -var _ endpoints_sdkv1.Resolver = resolverSDKv1{} +var _ opsworks_sdkv2.EndpointResolverV2 = resolverSDKv2{} -type resolverSDKv1 struct { - ctx context.Context +type resolverSDKv2 struct { + defaultResolver opsworks_sdkv2.EndpointResolverV2 } -func newEndpointResolverSDKv1(ctx context.Context) resolverSDKv1 { - return resolverSDKv1{ - ctx: ctx, +func newEndpointResolverSDKv2() resolverSDKv2 { + return resolverSDKv2{ + defaultResolver: opsworks_sdkv2.NewDefaultEndpointResolverV2(), } } -func (r resolverSDKv1) EndpointFor(service, region string, opts ...func(*endpoints_sdkv1.Options)) (endpoint endpoints_sdkv1.ResolvedEndpoint, err error) { - ctx := r.ctx +func (r resolverSDKv2) ResolveEndpoint(ctx context.Context, params opsworks_sdkv2.EndpointParameters) (endpoint smithyendpoints.Endpoint, err error) { + params = params.WithDefaults() + useFIPS := aws_sdkv2.ToBool(params.UseFIPS) - var opt endpoints_sdkv1.Options - opt.Set(opts...) - - useFIPS := opt.UseFIPSEndpoint == endpoints_sdkv1.FIPSEndpointStateEnabled + if eps := params.Endpoint; aws_sdkv2.ToString(eps) != "" { + tflog.Debug(ctx, "setting endpoint", map[string]any{ + "tf_aws.endpoint": endpoint, + }) - defaultResolver := endpoints_sdkv1.DefaultResolver() + if useFIPS { + tflog.Debug(ctx, "endpoint set, ignoring UseFIPSEndpoint setting") + params.UseFIPS = aws_sdkv2.Bool(false) + } - if useFIPS { + return r.defaultResolver.ResolveEndpoint(ctx, params) + } else if useFIPS { ctx = tflog.SetField(ctx, "tf_aws.use_fips", useFIPS) - endpoint, err = defaultResolver.EndpointFor(service, region, opts...) + endpoint, err = r.defaultResolver.ResolveEndpoint(ctx, params) if err != nil { return endpoint, err } tflog.Debug(ctx, "endpoint resolved", map[string]any{ - "tf_aws.endpoint": endpoint.URL, + "tf_aws.endpoint": endpoint.URI.String(), }) - var endpointURL *url.URL - endpointURL, err = url.Parse(endpoint.URL) - if err != nil { - return endpoint, err - } - - hostname := endpointURL.Hostname() + hostname := endpoint.URI.Hostname() _, err = net.LookupHost(hostname) if err != nil { if dnsErr, ok := errs.As[*net.DNSError](err); ok && dnsErr.IsNotFound { tflog.Debug(ctx, "default endpoint host not found, disabling FIPS", map[string]any{ "tf_aws.hostname": hostname, }) - opts = append(opts, func(o *endpoints_sdkv1.Options) { - o.UseFIPSEndpoint = endpoints_sdkv1.FIPSEndpointStateDisabled - }) + params.UseFIPS = aws_sdkv2.Bool(false) } else { - err = fmt.Errorf("looking up accessanalyzer endpoint %q: %s", hostname, err) + err = fmt.Errorf("looking up opsworks endpoint %q: %s", hostname, err) return } } else { @@ -72,5 +70,13 @@ func (r resolverSDKv1) EndpointFor(service, region string, opts ...func(*endpoin } } - return defaultResolver.EndpointFor(service, region, opts...) + return r.defaultResolver.ResolveEndpoint(ctx, params) +} + +func withBaseEndpoint(endpoint string) func(*opsworks_sdkv2.Options) { + return func(o *opsworks_sdkv2.Options) { + if endpoint != "" { + o.BaseEndpoint = aws_sdkv2.String(endpoint) + } + } } diff --git a/internal/service/opsworks/service_endpoints_gen_test.go b/internal/service/opsworks/service_endpoints_gen_test.go index 09f8ed6291a..1544e193c0a 100644 --- a/internal/service/opsworks/service_endpoints_gen_test.go +++ b/internal/service/opsworks/service_endpoints_gen_test.go @@ -4,18 +4,22 @@ package opsworks_test import ( "context" + "errors" "fmt" "maps" "net" "net/url" "os" "path/filepath" + "reflect" "strings" "testing" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" - opsworks_sdkv1 "github.com/aws/aws-sdk-go/service/opsworks" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + opsworks_sdkv2 "github.com/aws/aws-sdk-go-v2/service/opsworks" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/google/go-cmp/cmp" "github.com/hashicorp/aws-sdk-go-base/v2/servicemocks" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -240,54 +244,63 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S } func defaultEndpoint(region string) (url.URL, error) { - r := endpoints.DefaultResolver() + r := opsworks_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(opsworks_sdkv1.EndpointsID, region) + ep, err := r.ResolveEndpoint(context.Background(), opsworks_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + }) if err != nil { return url.URL{}, err } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return *url, nil + return ep.URI, nil } func defaultFIPSEndpoint(region string) (url.URL, error) { - r := endpoints.DefaultResolver() + r := opsworks_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(opsworks_sdkv1.EndpointsID, region, func(opt *endpoints.Options) { - opt.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled + ep, err := r.ResolveEndpoint(context.Background(), opsworks_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), + UseFIPS: aws_sdkv2.Bool(true), }) if err != nil { return url.URL{}, err } - url, _ := url.Parse(ep.URL) - - if url.Path == "" { - url.Path = "/" + if ep.URI.Path == "" { + ep.URI.Path = "/" } - return *url, nil + return ep.URI, nil } func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { t.Helper() - client := meta.OpsWorksConn(ctx) + client := meta.OpsWorksClient(ctx) - req, _ := client.DescribeAppsRequest(&opsworks_sdkv1.DescribeAppsInput{}) + var result apiCallParams - req.HTTPRequest.URL.Path = "/" - - return apiCallParams{ - endpoint: req.HTTPRequest.URL.String(), - region: aws_sdkv1.StringValue(client.Config.Region), + _, err := client.DescribeApps(ctx, &opsworks_sdkv2.DescribeAppsInput{}, + func(opts *opsworks_sdkv2.Options) { + opts.APIOptions = append(opts.APIOptions, + addRetrieveEndpointURLMiddleware(t, &result.endpoint), + addRetrieveRegionMiddleware(&result.region), + addCancelRequestMiddleware(), + ) + }, + ) + if err == nil { + t.Fatal("Expected an error, got none") + } else if !errors.Is(err, errCancelOperation) { + t.Fatalf("Unexpected error: %s", err) } + + return result } func withNoConfig(_ *caseSetup) { @@ -466,6 +479,89 @@ func testEndpointCase(t *testing.T, region string, testcase endpointTestCase, ca } } +func addRetrieveEndpointURLMiddleware(t *testing.T, endpoint *string) func(*middleware.Stack) error { + return func(stack *middleware.Stack) error { + return stack.Finalize.Add( + retrieveEndpointURLMiddleware(t, endpoint), + middleware.After, + ) + } +} + +func retrieveEndpointURLMiddleware(t *testing.T, endpoint *string) middleware.FinalizeMiddleware { + return middleware.FinalizeMiddlewareFunc( + "Test: Retrieve Endpoint", + func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { + t.Helper() + + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + t.Fatalf("Expected *github.com/aws/smithy-go/transport/http.Request, got %s", fullTypeName(in.Request)) + } + + url := request.URL + url.RawQuery = "" + url.Path = "/" + + *endpoint = url.String() + + return next.HandleFinalize(ctx, in) + }) +} + +func addRetrieveRegionMiddleware(region *string) func(*middleware.Stack) error { + return func(stack *middleware.Stack) error { + return stack.Serialize.Add( + retrieveRegionMiddleware(region), + middleware.After, + ) + } +} + +func retrieveRegionMiddleware(region *string) middleware.SerializeMiddleware { + return middleware.SerializeMiddlewareFunc( + "Test: Retrieve Region", + func(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (middleware.SerializeOutput, middleware.Metadata, error) { + *region = awsmiddleware.GetRegion(ctx) + + return next.HandleSerialize(ctx, in) + }, + ) +} + +var errCancelOperation = fmt.Errorf("Test: Canceling request") + +func addCancelRequestMiddleware() func(*middleware.Stack) error { + return func(stack *middleware.Stack) error { + return stack.Finalize.Add( + cancelRequestMiddleware(), + middleware.After, + ) + } +} + +// cancelRequestMiddleware creates a Smithy middleware that intercepts the request before sending and cancels it +func cancelRequestMiddleware() middleware.FinalizeMiddleware { + return middleware.FinalizeMiddlewareFunc( + "Test: Cancel Requests", + func(_ context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { + return middleware.FinalizeOutput{}, middleware.Metadata{}, errCancelOperation + }) +} + +func fullTypeName(i interface{}) string { + return fullValueTypeName(reflect.ValueOf(i)) +} + +func fullValueTypeName(v reflect.Value) string { + if v.Kind() == reflect.Ptr { + return "*" + fullValueTypeName(reflect.Indirect(v)) + } + + requestType := v.Type() + return fmt.Sprintf("%s.%s", requestType.PkgPath(), requestType.Name()) +} + func generateSharedConfigFile(config configFile) string { var buf strings.Builder diff --git a/internal/service/opsworks/service_package_gen.go b/internal/service/opsworks/service_package_gen.go index e218ee36fc1..f9e32a543f1 100644 --- a/internal/service/opsworks/service_package_gen.go +++ b/internal/service/opsworks/service_package_gen.go @@ -5,10 +5,8 @@ package opsworks import ( "context" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - opsworks_sdkv1 "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-log/tflog" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + opsworks_sdkv2 "github.com/aws/aws-sdk-go-v2/service/opsworks" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" "github.com/hashicorp/terraform-provider-aws/names" @@ -31,11 +29,12 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePackageSDKResource { return []*types.ServicePackageSDKResource{ { - Factory: ResourceApplication, + Factory: resourceApplication, TypeName: "aws_opsworks_application", + Name: "Application", }, { - Factory: ResourceCustomLayer, + Factory: resourceCustomLayer, TypeName: "aws_opsworks_custom_layer", Name: "Custom Layer", Tags: &types.ServicePackageResourceTags{ @@ -43,7 +42,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceECSClusterLayer, + Factory: resourceECSClusterLayer, TypeName: "aws_opsworks_ecs_cluster_layer", Name: "ECS Cluster Layer", Tags: &types.ServicePackageResourceTags{ @@ -51,7 +50,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceGangliaLayer, + Factory: resourceGangliaLayer, TypeName: "aws_opsworks_ganglia_layer", Name: "Ganglia Layer", Tags: &types.ServicePackageResourceTags{ @@ -59,7 +58,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceHAProxyLayer, + Factory: resourceHAProxyLayer, TypeName: "aws_opsworks_haproxy_layer", Name: "HAProxy Layer", Tags: &types.ServicePackageResourceTags{ @@ -67,11 +66,12 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceInstance, + Factory: resourceInstance, TypeName: "aws_opsworks_instance", + Name: "Instance", }, { - Factory: ResourceJavaAppLayer, + Factory: resourceJavaAppLayer, TypeName: "aws_opsworks_java_app_layer", Name: "Java App Layer", Tags: &types.ServicePackageResourceTags{ @@ -79,7 +79,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceMemcachedLayer, + Factory: resourceMemcachedLayer, TypeName: "aws_opsworks_memcached_layer", Name: "Memcached Layer", Tags: &types.ServicePackageResourceTags{ @@ -87,7 +87,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceMySQLLayer, + Factory: resourceMySQLLayer, TypeName: "aws_opsworks_mysql_layer", Name: "MySQL Layer", Tags: &types.ServicePackageResourceTags{ @@ -95,7 +95,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceNodejsAppLayer, + Factory: resourceNodejsAppLayer, TypeName: "aws_opsworks_nodejs_app_layer", Name: "NodeJS App Layer", Tags: &types.ServicePackageResourceTags{ @@ -103,11 +103,12 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourcePermission, + Factory: resourcePermission, TypeName: "aws_opsworks_permission", + Name: "Permission", }, { - Factory: ResourcePHPAppLayer, + Factory: resourcePHPAppLayer, TypeName: "aws_opsworks_php_app_layer", Name: "PHP App Layer", Tags: &types.ServicePackageResourceTags{ @@ -115,7 +116,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceRailsAppLayer, + Factory: resourceRailsAppLayer, TypeName: "aws_opsworks_rails_app_layer", Name: "Rails App Layer", Tags: &types.ServicePackageResourceTags{ @@ -123,17 +124,18 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceRDSDBInstance, + Factory: resourceRDSDBInstance, TypeName: "aws_opsworks_rds_db_instance", + Name: "RDS DB Instance", }, { - Factory: ResourceStack, + Factory: resourceStack, TypeName: "aws_opsworks_stack", Name: "Stack", Tags: &types.ServicePackageResourceTags{}, }, { - Factory: ResourceStaticWebLayer, + Factory: resourceStaticWebLayer, TypeName: "aws_opsworks_static_web_layer", Name: "Static Web Layer", Tags: &types.ServicePackageResourceTags{ @@ -141,8 +143,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceUserProfile, + Factory: resourceUserProfile, TypeName: "aws_opsworks_user_profile", + Name: "Profile", }, } } @@ -151,22 +154,14 @@ func (p *servicePackage) ServicePackageName() string { return names.OpsWorks } -// 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) (*opsworks_sdkv1.OpsWorks, 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) (*opsworks_sdkv2.Client, error) { + cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) - cfg := aws_sdkv1.Config{} - - if endpoint := config[names.AttrEndpoint].(string); endpoint != "" { - tflog.Debug(ctx, "setting endpoint", map[string]any{ - "tf_aws.endpoint": endpoint, - }) - cfg.Endpoint = aws_sdkv1.String(endpoint) - } else { - cfg.EndpointResolver = newEndpointResolverSDKv1(ctx) - } - - return opsworks_sdkv1.New(sess.Copy(&cfg)), nil + return opsworks_sdkv2.NewFromConfig(cfg, + opsworks_sdkv2.WithEndpointResolverV2(newEndpointResolverSDKv2()), + withBaseEndpoint(config[names.AttrEndpoint].(string)), + ), nil } func ServicePackage(ctx context.Context) conns.ServicePackage { diff --git a/internal/service/opsworks/stack.go b/internal/service/opsworks/stack.go index a758336f19e..18de0e8ebb0 100644 --- a/internal/service/opsworks/stack.go +++ b/internal/service/opsworks/stack.go @@ -9,15 +9,16 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -32,7 +33,7 @@ const ( // @SDKResource("aws_opsworks_stack", name="Stack") // @Tags -func ResourceStack() *schema.Resource { +func resourceStack() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceStackCreate, ReadWithoutTimeout: resourceStackRead, @@ -98,9 +99,9 @@ func ResourceStack() *schema.Resource { Sensitive: true, }, names.AttrType: { - Type: schema.TypeString, - Required: true, - ValidateFunc: validation.StringInSlice(opsworks.SourceType_Values(), false), + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: enum.Validate[awstypes.SourceType](), }, names.AttrURL: { Type: schema.TypeString, @@ -203,15 +204,15 @@ func ResourceStack() *schema.Resource { func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) name := d.Get(names.AttrName).(string) region := d.Get(names.AttrRegion).(string) input := &opsworks.CreateStackInput{ - ChefConfiguration: &opsworks.ChefConfiguration{ + ChefConfiguration: &awstypes.ChefConfiguration{ ManageBerkshelf: aws.Bool(d.Get("manage_berkshelf").(bool)), }, - ConfigurationManager: &opsworks.StackConfigurationManager{ + ConfigurationManager: &awstypes.StackConfigurationManager{ Name: aws.String(d.Get("configuration_manager_name").(string)), Version: aws.String(d.Get("configuration_manager_version").(string)), }, @@ -230,9 +231,9 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter } if v, ok := d.GetOk("color"); ok { - input.Attributes = aws.StringMap(map[string]string{ - opsworks.StackAttributesKeysColor: v.(string), - }) + input.Attributes = map[string]string{ + string(awstypes.StackAttributesKeysColor): v.(string), + } } if v, ok := d.GetOk("custom_cookbooks_source"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { @@ -248,7 +249,7 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter } if v, ok := d.GetOk("default_root_device_type"); ok { - input.DefaultRootDeviceType = aws.String(v.(string)) + input.DefaultRootDeviceType = awstypes.RootDeviceType(v.(string)) } if v, ok := d.GetOk("default_ssh_key_name"); ok { @@ -269,7 +270,7 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter outputRaw, err := tfresource.RetryWhen(ctx, d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { - return conn.CreateStackWithContext(ctx, input) + return conn.CreateStack(ctx, input) }, func(err error) (bool, error) { // If Terraform is also managing the service IAM role, it may have just been created and not yet be @@ -277,9 +278,9 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter // to do fragile message matching. // The full error we're looking for looks something like the following: // Service Role Arn: [...] is not yet propagated, please try again in a couple of minutes - if tfawserr.ErrMessageContains(err, opsworks.ErrCodeValidationException, "not yet propagated") || - tfawserr.ErrMessageContains(err, opsworks.ErrCodeValidationException, "not the necessary trust relationship") || - tfawserr.ErrMessageContains(err, opsworks.ErrCodeValidationException, "validate IAM role permission") { + if errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "not yet propagated") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "not the necessary trust relationship") || + errs.IsAErrorMessageContains[*awstypes.ValidationException](err, "validate IAM role permission") { return true, err } @@ -291,11 +292,11 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "creating OpsWorks Stack (%s): %s", name, err) } - d.SetId(aws.StringValue(outputRaw.(*opsworks.CreateStackOutput).StackId)) + d.SetId(aws.ToString(outputRaw.(*opsworks.CreateStackOutput).StackId)) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: opsworks.ServiceName, + Service: names.OpsWorks, Region: region, AccountID: meta.(*conns.AWSClient).AccountID, Resource: fmt.Sprintf("stack/%s/", d.Id()), @@ -305,7 +306,7 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "setting OpsWorks Stack (%s) tags: %s", arn, err) } - if aws.StringValue(input.VpcId) != "" && aws.BoolValue(input.UseOpsworksSecurityGroups) { + if aws.ToString(input.VpcId) != "" && aws.ToBool(input.UseOpsworksSecurityGroups) { // For VPC-based stacks, OpsWorks asynchronously creates some default // security groups which must exist before layers can be created. // Unfortunately it doesn't tell us what the ids of these are, so @@ -321,21 +322,24 @@ func resourceStackCreate(ctx context.Context, d *schema.ResourceData, meta inter func resourceStackRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics var err error - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) + region := conn.Options().Region if v, ok := d.GetOk("stack_endpoint"); ok { - conn = meta.(*conns.AWSClient).OpsWorksConnForRegion(ctx, v.(string)) + region = v.(string) } - stack, err := FindStackByID(ctx, conn, d.Id()) + stack, err := findStackByID(ctx, conn, d.Id()) if tfresource.NotFound(err) { // nosemgrep:ci.semgrep.errors.notfound-without-err-checks // If it's not found in the default region we're in, we check us-east-1 // in the event this stack was created with Terraform before version 0.9. // See https://github.com/hashicorp/terraform/issues/12842. - conn = meta.(*conns.AWSClient).OpsWorksConnForRegion(ctx, names.USEast1RegionID) + region = names.USEast1RegionID - stack, err = FindStackByID(ctx, conn, d.Id()) + stack, err = findStackByID(ctx, conn, d.Id(), func(o *opsworks.Options) { + o.Region = region + }) } if !d.IsNewResource() && tfresource.NotFound(err) { @@ -349,22 +353,22 @@ func resourceStackRead(ctx context.Context, d *schema.ResourceData, meta interfa } // If the stack was found, set the stack_endpoint. - if v := aws.StringValue(conn.Config.Region); v != "" { + if v := conn.Options().Region; v != "" { d.Set("stack_endpoint", v) } d.Set("agent_version", stack.AgentVersion) - arn := aws.StringValue(stack.Arn) + arn := aws.ToString(stack.Arn) d.Set(names.AttrARN, arn) if stack.ChefConfiguration != nil { - if v := aws.StringValue(stack.ChefConfiguration.BerkshelfVersion); v != "" { + if v := aws.ToString(stack.ChefConfiguration.BerkshelfVersion); v != "" { d.Set("berkshelf_version", v) } else { d.Set("berkshelf_version", defaultBerkshelfVersion) } d.Set("manage_berkshelf", stack.ChefConfiguration.ManageBerkshelf) } - if color, ok := stack.Attributes[opsworks.StackAttributesKeysColor]; ok { + if color, ok := stack.Attributes[string(awstypes.StackAttributesKeysColor)]; ok { d.Set("color", color) } if stack.ConfigurationManager != nil { @@ -418,10 +422,11 @@ func resourceStackRead(ctx context.Context, d *schema.ResourceData, meta interfa func resourceStackUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics var err error - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) + region := conn.Options().Region if v, ok := d.GetOk("stack_endpoint"); ok { - conn = meta.(*conns.AWSClient).OpsWorksConnForRegion(ctx, v.(string)) + region = v.(string) } if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) { @@ -434,7 +439,7 @@ func resourceStackUpdate(ctx context.Context, d *schema.ResourceData, meta inter } if d.HasChanges("berkshelf_version", "manage_berkshelf") { - input.ChefConfiguration = &opsworks.ChefConfiguration{ + input.ChefConfiguration = &awstypes.ChefConfiguration{ ManageBerkshelf: aws.Bool(d.Get("manage_berkshelf").(bool)), } @@ -444,13 +449,13 @@ func resourceStackUpdate(ctx context.Context, d *schema.ResourceData, meta inter } if d.HasChange("color") { - input.Attributes = aws.StringMap(map[string]string{ - opsworks.StackAttributesKeysColor: d.Get("color").(string), - }) + input.Attributes = map[string]string{ + string(awstypes.StackAttributesKeysColor): d.Get("color").(string), + } } if d.HasChanges("configuration_manager_name", "configuration_manager_version") { - input.ConfigurationManager = &opsworks.StackConfigurationManager{ + input.ConfigurationManager = &awstypes.StackConfigurationManager{ Name: aws.String(d.Get("configuration_manager_name").(string)), Version: aws.String(d.Get("configuration_manager_version").(string)), } @@ -479,7 +484,7 @@ func resourceStackUpdate(ctx context.Context, d *schema.ResourceData, meta inter } if d.HasChange("default_root_device_type") { - input.DefaultRootDeviceType = aws.String(d.Get("default_root_device_type").(string)) + input.DefaultRootDeviceType = awstypes.RootDeviceType(d.Get("default_root_device_type").(string)) } if d.HasChange("default_ssh_key_name") { @@ -510,7 +515,9 @@ func resourceStackUpdate(ctx context.Context, d *schema.ResourceData, meta inter input.UseOpsworksSecurityGroups = aws.Bool(d.Get("use_opsworks_security_groups").(bool)) } - _, err = conn.UpdateStackWithContext(ctx, input) + _, err = conn.UpdateStack(ctx, input, func(o *opsworks.Options) { + o.Region = region + }) if err != nil { return sdkdiag.AppendErrorf(diags, "updating OpsWorks Stack (%s): %s", d.Id(), err) @@ -531,18 +538,24 @@ func resourceStackUpdate(ctx context.Context, d *schema.ResourceData, meta inter func resourceStackDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics var err error - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) + + region := conn.Options().Region if v, ok := d.GetOk("stack_endpoint"); ok { - conn = meta.(*conns.AWSClient).OpsWorksConnForRegion(ctx, v.(string)) + region = v.(string) } - log.Printf("[DEBUG] Deleting OpsWorks Stack: %s", d.Id()) - _, err = conn.DeleteStackWithContext(ctx, &opsworks.DeleteStackInput{ + input := &opsworks.DeleteStackInput{ StackId: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting OpsWorks Stack: %s", d.Id()) + _, err = conn.DeleteStack(ctx, input, func(o *opsworks.Options) { + o.Region = region }) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -569,14 +582,14 @@ func resourceStackDelete(ctx context.Context, d *schema.ResourceData, meta inter return diags } -func FindStackByID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*opsworks.Stack, error) { +func findStackByID(ctx context.Context, conn *opsworks.Client, id string, optFns ...func(*opsworks.Options)) (*awstypes.Stack, error) { input := &opsworks.DescribeStacksInput{ - StackIds: aws.StringSlice([]string{id}), + StackIds: []string{id}, } - output, err := conn.DescribeStacksWithContext(ctx, input) + output, err := conn.DescribeStacks(ctx, input, optFns...) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -587,7 +600,7 @@ func FindStackByID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*op return nil, err } - if output == nil || len(output.Stacks) == 0 || output.Stacks[0] == nil { + if output == nil || len(output.Stacks) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -595,15 +608,15 @@ func FindStackByID(ctx context.Context, conn *opsworks.OpsWorks, id string) (*op return nil, tfresource.NewTooManyResultsError(count, input) } - return output.Stacks[0], nil + return tfresource.AssertSingleValueResult(output.Stacks) } -func expandSource(tfMap map[string]interface{}) *opsworks.Source { +func expandSource(tfMap map[string]interface{}) *awstypes.Source { if tfMap == nil { return nil } - apiObject := &opsworks.Source{} + apiObject := &awstypes.Source{} if v, ok := tfMap[names.AttrPassword].(string); ok && v != "" { apiObject.Password = aws.String(v) @@ -618,7 +631,7 @@ func expandSource(tfMap map[string]interface{}) *opsworks.Source { } if v, ok := tfMap[names.AttrType].(string); ok && v != "" { - apiObject.Type = aws.String(v) + apiObject.Type = awstypes.SourceType(v) } if v, ok := tfMap[names.AttrURL].(string); ok && v != "" { @@ -632,7 +645,7 @@ func expandSource(tfMap map[string]interface{}) *opsworks.Source { return apiObject } -func flattenSource(apiObject *opsworks.Source) map[string]interface{} { +func flattenSource(apiObject *awstypes.Source) map[string]interface{} { if apiObject == nil { return nil } @@ -640,27 +653,25 @@ func flattenSource(apiObject *opsworks.Source) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.Password; v != nil { - tfMap[names.AttrPassword] = aws.StringValue(v) + tfMap[names.AttrPassword] = aws.ToString(v) } if v := apiObject.Revision; v != nil { - tfMap["revision"] = aws.StringValue(v) + tfMap["revision"] = aws.ToString(v) } if v := apiObject.SshKey; v != nil { - tfMap["ssh_key"] = aws.StringValue(v) + tfMap["ssh_key"] = aws.ToString(v) } - if v := apiObject.Type; v != nil { - tfMap[names.AttrType] = aws.StringValue(v) - } + tfMap[names.AttrType] = apiObject.Type if v := apiObject.Url; v != nil { - tfMap[names.AttrURL] = aws.StringValue(v) + tfMap[names.AttrURL] = aws.ToString(v) } if v := apiObject.Username; v != nil { - tfMap[names.AttrUsername] = aws.StringValue(v) + tfMap[names.AttrUsername] = aws.ToString(v) } return tfMap diff --git a/internal/service/opsworks/stack_test.go b/internal/service/opsworks/stack_test.go index 89dc4fbbdd2..7183f5ae551 100644 --- a/internal/service/opsworks/stack_test.go +++ b/internal/service/opsworks/stack_test.go @@ -9,9 +9,9 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/opsworks" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -23,15 +23,17 @@ import ( ) func TestAccOpsWorksStack_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -78,15 +80,17 @@ func TestAccOpsWorksStack_basic(t *testing.T) { } func TestAccOpsWorksStack_disappears(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -106,15 +110,17 @@ func TestAccOpsWorksStack_disappears(t *testing.T) { } func TestAccOpsWorksStack_noVPC_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -148,15 +154,17 @@ func TestAccOpsWorksStack_noVPC_basic(t *testing.T) { } func TestAccOpsWorksStack_noVPC_defaultAZ(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -182,15 +190,17 @@ func TestAccOpsWorksStack_noVPC_defaultAZ(t *testing.T) { } func TestAccOpsWorksStack_tags(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -232,21 +242,23 @@ func TestAccOpsWorksStack_tags(t *testing.T) { } func TestAccOpsWorksStack_tagsAlternateRegion(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) // This test requires a very particular AWS Region configuration // in order to exercise the OpsWorks classic endpoint functionality. acctest.PreCheckMultipleRegion(t, 2) - acctest.PreCheckRegion(t, endpoints.UsEast1RegionID) - acctest.PreCheckAlternateRegionIs(t, endpoints.UsWest1RegionID) + acctest.PreCheckRegion(t, names.USEast1RegionID) + acctest.PreCheckAlternateRegionIs(t, names.USWest1RegionID) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5FactoriesMultipleRegions(ctx, t, 2), @@ -259,7 +271,7 @@ func TestAccOpsWorksStack_tagsAlternateRegion(t *testing.T) { resource.TestCheckResourceAttrWith(resourceName, names.AttrARN, func(value string) error { if !regexache.MustCompile(arn.ARN{ Partition: acctest.Partition(), - Service: opsworks.ServiceName, + Service: names.OpsWorks, Region: acctest.AlternateRegion(), AccountID: acctest.AccountID(), Resource: `stack/.+/`, @@ -271,7 +283,7 @@ func TestAccOpsWorksStack_tagsAlternateRegion(t *testing.T) { }), resource.TestCheckResourceAttr(resourceName, names.AttrRegion, acctest.AlternateRegion()), // "In this case, the actual API endpoint of the stack is in us-east-1." - resource.TestCheckResourceAttr(resourceName, "stack_endpoint", endpoints.UsEast1RegionID), + resource.TestCheckResourceAttr(resourceName, "stack_endpoint", names.USEast1RegionID), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct1), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey1, acctest.CtValue1), ), @@ -303,15 +315,17 @@ func TestAccOpsWorksStack_tagsAlternateRegion(t *testing.T) { } func TestAccOpsWorksStack_allAttributes(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -439,15 +453,17 @@ func TestAccOpsWorksStack_allAttributes(t *testing.T) { } func TestAccOpsWorksStack_windows(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_stack.test" - var v opsworks.Stack + var v awstypes.Stack resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) + acctest.PreCheckPartitionHasService(t, names.OpsWorks) testAccPreCheckStacks(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), @@ -484,11 +500,11 @@ func TestAccOpsWorksStack_windows(t *testing.T) { } func testAccPreCheckStacks(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) input := &opsworks.DescribeStacksInput{} - _, err := conn.DescribeStacksWithContext(ctx, input) + _, err := conn.DescribeStacks(ctx, input) if acctest.PreCheckSkipError(err) { t.Skipf("skipping acceptance testing: %s", err) @@ -499,14 +515,14 @@ func testAccPreCheckStacks(ctx context.Context, t *testing.T) { } } -func testAccCheckStackExists(ctx context.Context, n string, v *opsworks.Stack) resource.TestCheckFunc { +func testAccCheckStackExists(ctx context.Context, n string, v *awstypes.Stack) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) output, err := tfopsworks.FindStackByID(ctx, conn, rs.Primary.ID) @@ -522,7 +538,7 @@ func testAccCheckStackExists(ctx context.Context, n string, v *opsworks.Stack) r func testAccCheckStackDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_opsworks_stack" { diff --git a/internal/service/opsworks/static_web_layer.go b/internal/service/opsworks/static_web_layer.go index 399d01495ab..9268bb3ae89 100644 --- a/internal/service/opsworks/static_web_layer.go +++ b/internal/service/opsworks/static_web_layer.go @@ -4,15 +4,15 @@ package opsworks import ( - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // @SDKResource("aws_opsworks_static_web_layer", name="Static Web Layer") // @Tags(identifierAttribute="arn") -func ResourceStaticWebLayer() *schema.Resource { +func resourceStaticWebLayer() *schema.Resource { layerType := &opsworksLayerType{ - TypeName: opsworks.LayerTypeWeb, + TypeName: awstypes.LayerTypeWeb, DefaultLayerName: "Static Web Server", Attributes: map[string]*opsworksLayerTypeAttribute{}, diff --git a/internal/service/opsworks/static_web_layer_test.go b/internal/service/opsworks/static_web_layer_test.go index dbf45620135..4e374981ebf 100644 --- a/internal/service/opsworks/static_web_layer_test.go +++ b/internal/service/opsworks/static_web_layer_test.go @@ -7,7 +7,7 @@ import ( "context" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/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" @@ -16,13 +16,15 @@ import ( ) func TestAccOpsWorksStaticWebLayer_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) - var v opsworks.Layer + var v awstypes.Layer rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_static_web_layer.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckStaticWebLayerDestroy(ctx), diff --git a/internal/service/opsworks/sweep.go b/internal/service/opsworks/sweep.go index 01e99c49446..8e00bb67548 100644 --- a/internal/service/opsworks/sweep.go +++ b/internal/service/opsworks/sweep.go @@ -10,8 +10,9 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -76,10 +77,10 @@ func sweepApplication(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.OpsWorksConn(ctx) + conn := client.OpsWorksClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - output, err := conn.DescribeStacksWithContext(ctx, &opsworks.DescribeStacksInput{}) + output, err := conn.DescribeStacks(ctx, &opsworks.DescribeStacksInput{}) if err != nil { if awsv1.SkipSweepError(err) { @@ -96,23 +97,19 @@ func sweepApplication(region string) error { StackId: stack.StackId, } - appOutput, err := conn.DescribeAppsWithContext(ctx, input) + appOutput, err := conn.DescribeApps(ctx, input) if err != nil { - sweeperErr := fmt.Errorf("describing OpsWorks Applications for Stack (%s): %w", aws.StringValue(stack.StackId), err) + sweeperErr := fmt.Errorf("describing OpsWorks Applications for Stack (%s): %w", aws.ToString(stack.StackId), err) log.Printf("[ERROR] %s", sweeperErr) sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) continue } for _, app := range appOutput.Apps { - if app == nil { - continue - } - - r := ResourceApplication() + r := resourceApplication() d := r.Data(nil) - d.SetId(aws.StringValue(app.AppId)) + d.SetId(aws.ToString(app.AppId)) sweepResources = append(sweepResources, sdk.NewSweepResource(r, d, client)) } @@ -128,10 +125,10 @@ func sweepInstance(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.OpsWorksConn(ctx) + conn := client.OpsWorksClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - output, err := conn.DescribeStacksWithContext(ctx, &opsworks.DescribeStacksInput{}) + output, err := conn.DescribeStacks(ctx, &opsworks.DescribeStacksInput{}) if err != nil { if awsv1.SkipSweepError(err) { @@ -148,23 +145,19 @@ func sweepInstance(region string) error { StackId: stack.StackId, } - instanceOutput, err := conn.DescribeInstancesWithContext(ctx, input) + instanceOutput, err := conn.DescribeInstances(ctx, input) if err != nil { - sweeperErr := fmt.Errorf("describing OpsWorks Instances for Stack (%s): %w", aws.StringValue(stack.StackId), err) + sweeperErr := fmt.Errorf("describing OpsWorks Instances for Stack (%s): %w", aws.ToString(stack.StackId), err) log.Printf("[ERROR] %s", sweeperErr) sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) continue } for _, instance := range instanceOutput.Instances { - if instance == nil { - continue - } - - r := ResourceInstance() + r := resourceInstance() d := r.Data(nil) - d.SetId(aws.StringValue(instance.InstanceId)) + d.SetId(aws.ToString(instance.InstanceId)) d.Set(names.AttrStatus, instance.Status) sweepResources = append(sweepResources, sdk.NewSweepResource(r, d, client)) @@ -181,10 +174,10 @@ func sweepRDSDBInstance(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.OpsWorksConn(ctx) + conn := client.OpsWorksClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - output, err := conn.DescribeStacksWithContext(ctx, &opsworks.DescribeStacksInput{}) + output, err := conn.DescribeStacks(ctx, &opsworks.DescribeStacksInput{}) if err != nil { if awsv1.SkipSweepError(err) { @@ -201,23 +194,19 @@ func sweepRDSDBInstance(region string) error { StackId: stack.StackId, } - dbInstOutput, err := conn.DescribeRdsDbInstancesWithContext(ctx, input) + dbInstOutput, err := conn.DescribeRdsDbInstances(ctx, input) if err != nil { - sweeperErr := fmt.Errorf("describing OpsWorks RDS DB Instances for Stack (%s): %w", aws.StringValue(stack.StackId), err) + sweeperErr := fmt.Errorf("describing OpsWorks RDS DB Instances for Stack (%s): %w", aws.ToString(stack.StackId), err) log.Printf("[ERROR] %s", sweeperErr) sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) continue } for _, dbInstance := range dbInstOutput.RdsDbInstances { - if dbInstance == nil { - continue - } - - r := ResourceRDSDBInstance() + r := resourceRDSDBInstance() d := r.Data(nil) - d.SetId(aws.StringValue(dbInstance.DbInstanceIdentifier)) + d.SetId(aws.ToString(dbInstance.DbInstanceIdentifier)) d.Set("rds_db_instance_arn", dbInstance.RdsDbInstanceArn) sweepResources = append(sweepResources, sdk.NewSweepResource(r, d, client)) @@ -234,10 +223,10 @@ func sweepStacks(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.OpsWorksConn(ctx) + conn := client.OpsWorksClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - output, err := conn.DescribeStacksWithContext(ctx, &opsworks.DescribeStacksInput{}) + output, err := conn.DescribeStacks(ctx, &opsworks.DescribeStacksInput{}) if err != nil { if awsv1.SkipSweepError(err) { @@ -248,19 +237,15 @@ func sweepStacks(region string) error { } for _, stack := range output.Stacks { - if stack == nil { - continue - } - - r := ResourceStack() + r := resourceStack() d := r.Data(nil) - d.SetId(aws.StringValue(stack.StackId)) + d.SetId(aws.ToString(stack.StackId)) - if aws.StringValue(stack.VpcId) != "" { + if aws.ToString(stack.VpcId) != "" { d.Set(names.AttrVPCID, stack.VpcId) } - if aws.BoolValue(stack.UseOpsworksSecurityGroups) { + if aws.ToBool(stack.UseOpsworksSecurityGroups) { d.Set("use_opsworks_security_groups", true) } @@ -277,10 +262,10 @@ func sweepLayers(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.OpsWorksConn(ctx) + conn := client.OpsWorksClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - output, err := conn.DescribeStacksWithContext(ctx, &opsworks.DescribeStacksInput{}) + output, err := conn.DescribeStacks(ctx, &opsworks.DescribeStacksInput{}) if err != nil { if awsv1.SkipSweepError(err) { @@ -297,30 +282,26 @@ func sweepLayers(region string) error { StackId: stack.StackId, } - layerOutput, err := conn.DescribeLayersWithContext(ctx, input) + layerOutput, err := conn.DescribeLayers(ctx, input) if err != nil { - sweeperErr := fmt.Errorf("describing OpsWorks Layers for Stack (%s): %w", aws.StringValue(stack.StackId), err) + sweeperErr := fmt.Errorf("describing OpsWorks Layers for Stack (%s): %w", aws.ToString(stack.StackId), err) log.Printf("[ERROR] %s", sweeperErr) sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) continue } for _, layer := range layerOutput.Layers { - if layer == nil { - continue - } - l := &opsworksLayerType{} r := l.resourceSchema() d := r.Data(nil) - d.SetId(aws.StringValue(layer.LayerId)) + d.SetId(aws.ToString(layer.LayerId)) if layer.Attributes != nil { - if v, ok := layer.Attributes[opsworks.LayerAttributesKeysEcsClusterArn]; ok && aws.StringValue(v) != "" { - r = ResourceECSClusterLayer() + if v, ok := layer.Attributes[string(awstypes.LayerAttributesKeysEcsClusterArn)]; ok && v != "" { + r = resourceECSClusterLayer() d = r.Data(nil) - d.SetId(aws.StringValue(layer.LayerId)) + d.SetId(aws.ToString(layer.LayerId)) d.Set("ecs_cluster_arn", v) } } @@ -339,10 +320,10 @@ func sweepUserProfiles(region string) error { return fmt.Errorf("error getting client: %s", err) } - conn := client.OpsWorksConn(ctx) + conn := client.OpsWorksClient(ctx) sweepResources := make([]sweep.Sweepable, 0) - output, err := conn.DescribeUserProfilesWithContext(ctx, &opsworks.DescribeUserProfilesInput{}) + output, err := conn.DescribeUserProfiles(ctx, &opsworks.DescribeUserProfilesInput{}) if err != nil { if awsv1.SkipSweepError(err) { @@ -353,9 +334,9 @@ func sweepUserProfiles(region string) error { } for _, profile := range output.UserProfiles { - r := ResourceUserProfile() + r := resourceUserProfile() d := r.Data(nil) - d.SetId(aws.StringValue(profile.IamUserArn)) + d.SetId(aws.ToString(profile.IamUserArn)) sweepResources = append(sweepResources, newUserProfileSweeper(r, d, client)) } diff --git a/internal/service/opsworks/tags_gen.go b/internal/service/opsworks/tags_gen.go index 1e17d009ffb..0bfc739d1f8 100644 --- a/internal/service/opsworks/tags_gen.go +++ b/internal/service/opsworks/tags_gen.go @@ -5,9 +5,8 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/aws/aws-sdk-go/service/opsworks/opsworksiface" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/opsworks" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" @@ -19,12 +18,12 @@ import ( // listTags lists opsworks 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 opsworksiface.OpsWorksAPI, identifier string) (tftags.KeyValueTags, error) { +func listTags(ctx context.Context, conn *opsworks.Client, identifier string, optFns ...func(*opsworks.Options)) (tftags.KeyValueTags, error) { input := &opsworks.ListTagsInput{ ResourceArn: aws.String(identifier), } - output, err := conn.ListTagsWithContext(ctx, input) + output, err := conn.ListTags(ctx, input, optFns...) if err != nil { return tftags.New(ctx, nil), err @@ -36,7 +35,7 @@ func listTags(ctx context.Context, conn opsworksiface.OpsWorksAPI, identifier st // ListTags lists opsworks 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).OpsWorksConn(ctx), identifier) + tags, err := listTags(ctx, meta.(*conns.AWSClient).OpsWorksClient(ctx), identifier) if err != nil { return err @@ -49,21 +48,21 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri return nil } -// map[string]*string handling +// map[string]string handling // Tags returns opsworks service tags. -func Tags(tags tftags.KeyValueTags) map[string]*string { - return aws.StringMap(tags.Map()) +func Tags(tags tftags.KeyValueTags) map[string]string { + return tags.Map() } // KeyValueTags creates tftags.KeyValueTags from opsworks service tags. -func KeyValueTags(ctx context.Context, tags map[string]*string) tftags.KeyValueTags { +func KeyValueTags(ctx context.Context, tags map[string]string) tftags.KeyValueTags { return tftags.New(ctx, tags) } // getTagsIn returns opsworks service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) map[string]*string { +func getTagsIn(ctx context.Context) map[string]string { if inContext, ok := tftags.FromContext(ctx); ok { if tags := Tags(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { return tags @@ -74,25 +73,25 @@ func getTagsIn(ctx context.Context) map[string]*string { } // setTagsOut sets opsworks service tags in Context. -func setTagsOut(ctx context.Context, tags map[string]*string) { +func setTagsOut(ctx context.Context, tags map[string]string) { if inContext, ok := tftags.FromContext(ctx); ok { inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) } } // createTags creates opsworks service tags for new resources. -func createTags(ctx context.Context, conn opsworksiface.OpsWorksAPI, identifier string, tags map[string]*string) error { +func createTags(ctx context.Context, conn *opsworks.Client, identifier string, tags map[string]string, optFns ...func(*opsworks.Options)) error { if len(tags) == 0 { return nil } - return updateTags(ctx, conn, identifier, nil, tags) + return updateTags(ctx, conn, identifier, nil, tags, optFns...) } // updateTags updates opsworks 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 opsworksiface.OpsWorksAPI, identifier string, oldTagsMap, newTagsMap any) error { +func updateTags(ctx context.Context, conn *opsworks.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*opsworks.Options)) error { oldTags := tftags.New(ctx, oldTagsMap) newTags := tftags.New(ctx, newTagsMap) @@ -103,10 +102,10 @@ func updateTags(ctx context.Context, conn opsworksiface.OpsWorksAPI, identifier if len(removedTags) > 0 { input := &opsworks.UntagResourceInput{ ResourceArn: aws.String(identifier), - TagKeys: aws.StringSlice(removedTags.Keys()), + TagKeys: removedTags.Keys(), } - _, err := conn.UntagResourceWithContext(ctx, input) + _, err := conn.UntagResource(ctx, input, optFns...) if err != nil { return fmt.Errorf("untagging resource (%s): %w", identifier, err) @@ -121,7 +120,7 @@ func updateTags(ctx context.Context, conn opsworksiface.OpsWorksAPI, identifier Tags: Tags(updatedTags), } - _, err := conn.TagResourceWithContext(ctx, input) + _, err := conn.TagResource(ctx, input, optFns...) if err != nil { return fmt.Errorf("tagging resource (%s): %w", identifier, err) @@ -134,5 +133,5 @@ func updateTags(ctx context.Context, conn opsworksiface.OpsWorksAPI, identifier // UpdateTags updates opsworks 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).OpsWorksConn(ctx), identifier, oldTags, newTags) + return updateTags(ctx, meta.(*conns.AWSClient).OpsWorksClient(ctx), identifier, oldTags, newTags) } diff --git a/internal/service/opsworks/user_profile.go b/internal/service/opsworks/user_profile.go index 3f9c851dc63..b97e4a510c2 100644 --- a/internal/service/opsworks/user_profile.go +++ b/internal/service/opsworks/user_profile.go @@ -7,19 +7,20 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/opsworks" - "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/opsworks" + awstypes "github.com/aws/aws-sdk-go-v2/service/opsworks/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// @SDKResource("aws_opsworks_user_profile") -func ResourceUserProfile() *schema.Resource { +// @SDKResource("aws_opsworks_user_profile", name="Profile") +func resourceUserProfile() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceUserProfileCreate, ReadWithoutTimeout: resourceUserProfileRead, @@ -51,7 +52,7 @@ func ResourceUserProfile() *schema.Resource { func resourceUserProfileCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) iamUserARN := d.Get("user_arn").(string) input := &opsworks.CreateUserProfileInput{ @@ -64,7 +65,7 @@ func resourceUserProfileCreate(ctx context.Context, d *schema.ResourceData, meta input.SshPublicKey = aws.String(v.(string)) } - _, err := conn.CreateUserProfileWithContext(ctx, input) + _, err := conn.CreateUserProfile(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating OpsWorks User Profile (%s): %s", iamUserARN, err) @@ -77,9 +78,9 @@ func resourceUserProfileCreate(ctx context.Context, d *schema.ResourceData, meta func resourceUserProfileRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) - profile, err := FindUserProfileByARN(ctx, conn, d.Id()) + profile, err := findUserProfileByARN(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] OpsWorks User Profile %s not found, removing from state", d.Id()) @@ -101,7 +102,7 @@ func resourceUserProfileRead(ctx context.Context, d *schema.ResourceData, meta i func resourceUserProfileUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) input := &opsworks.UpdateUserProfileInput{ AllowSelfManagement: aws.Bool(d.Get("allow_self_management").(bool)), @@ -110,7 +111,7 @@ func resourceUserProfileUpdate(ctx context.Context, d *schema.ResourceData, meta SshUsername: aws.String(d.Get("ssh_username").(string)), } - _, err := conn.UpdateUserProfileWithContext(ctx, input) + _, err := conn.UpdateUserProfile(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating OpsWorks User Profile (%s): %s", d.Id(), err) @@ -121,14 +122,14 @@ func resourceUserProfileUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceUserProfileDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).OpsWorksConn(ctx) + conn := meta.(*conns.AWSClient).OpsWorksClient(ctx) log.Printf("[DEBUG] Deleting OpsWorks User Profile: %s", d.Id()) - _, err := conn.DeleteUserProfileWithContext(ctx, &opsworks.DeleteUserProfileInput{ + _, err := conn.DeleteUserProfile(ctx, &opsworks.DeleteUserProfileInput{ IamUserArn: aws.String(d.Id()), }) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -139,14 +140,14 @@ func resourceUserProfileDelete(ctx context.Context, d *schema.ResourceData, meta return diags } -func FindUserProfileByARN(ctx context.Context, conn *opsworks.OpsWorks, arn string) (*opsworks.UserProfile, error) { +func findUserProfileByARN(ctx context.Context, conn *opsworks.Client, arn string) (*awstypes.UserProfile, error) { input := &opsworks.DescribeUserProfilesInput{ - IamUserArns: aws.StringSlice([]string{arn}), + IamUserArns: []string{arn}, } - output, err := conn.DescribeUserProfilesWithContext(ctx, input) + output, err := conn.DescribeUserProfiles(ctx, input) - if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, @@ -157,7 +158,7 @@ func FindUserProfileByARN(ctx context.Context, conn *opsworks.OpsWorks, arn stri return nil, err } - if output == nil || len(output.UserProfiles) == 0 || output.UserProfiles[0] == nil { + if output == nil || len(output.UserProfiles) == 0 { return nil, tfresource.NewEmptyResultError(input) } @@ -165,5 +166,5 @@ func FindUserProfileByARN(ctx context.Context, conn *opsworks.OpsWorks, arn stri return nil, tfresource.NewTooManyResultsError(count, input) } - return output.UserProfiles[0], nil + return tfresource.AssertSingleValueResult(output.UserProfiles) } diff --git a/internal/service/opsworks/user_profile_test.go b/internal/service/opsworks/user_profile_test.go index 8fbda56641f..bd53fd2a264 100644 --- a/internal/service/opsworks/user_profile_test.go +++ b/internal/service/opsworks/user_profile_test.go @@ -8,7 +8,6 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/opsworks" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -20,13 +19,15 @@ import ( ) func TestAccOpsWorksUserProfile_basic(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName1 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) rName2 := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_user_profile.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckUserProfileDestroy(ctx), @@ -54,12 +55,14 @@ func TestAccOpsWorksUserProfile_basic(t *testing.T) { } func TestAccOpsWorksUserProfile_disappears(t *testing.T) { + acctest.Skip(t, "skipping test; Amazon OpsWorks has been deprecated and will be removed in the next major release") + ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_opsworks_user_profile.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, opsworks.EndpointsID) }, + PreCheck: func() { acctest.PreCheck(ctx, t); acctest.PreCheckPartitionHasService(t, names.OpsWorks) }, ErrorCheck: acctest.ErrorCheck(t, names.OpsWorksServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckUserProfileDestroy(ctx), @@ -87,7 +90,7 @@ func testAccCheckUserProfileExists(ctx context.Context, n string) resource.TestC return fmt.Errorf("No OpsWorks User Profile ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) _, err := tfopsworks.FindUserProfileByARN(ctx, conn, rs.Primary.ID) @@ -97,7 +100,7 @@ func testAccCheckUserProfileExists(ctx context.Context, n string) resource.TestC func testAccCheckUserProfileDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).OpsWorksClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_opsworks_user_profile" { diff --git a/names/data/names_data.hcl b/names/data/names_data.hcl index e4d1f4e266c..4c4c37a1825 100644 --- a/names/data/names_data.hcl +++ b/names/data/names_data.hcl @@ -6644,7 +6644,7 @@ service "opsworks" { sdk { id = "OpsWorks" - client_version = [1] + client_version = [2] } names { diff --git a/tools/tfsdk2fw/go.mod b/tools/tfsdk2fw/go.mod index a5736cc0944..1dace3cb91b 100644 --- a/tools/tfsdk2fw/go.mod +++ b/tools/tfsdk2fw/go.mod @@ -190,6 +190,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/oam v1.13.5 // indirect github.com/aws/aws-sdk-go-v2/service/opensearch v1.39.3 // indirect github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.13.4 // indirect + github.com/aws/aws-sdk-go-v2/service/opsworks v1.24.4 // indirect github.com/aws/aws-sdk-go-v2/service/organizations v1.30.3 // indirect github.com/aws/aws-sdk-go-v2/service/osis v1.12.4 // indirect github.com/aws/aws-sdk-go-v2/service/outposts v1.42.1 // indirect diff --git a/tools/tfsdk2fw/go.sum b/tools/tfsdk2fw/go.sum index 0c0bacff384..396f4f74a77 100644 --- a/tools/tfsdk2fw/go.sum +++ b/tools/tfsdk2fw/go.sum @@ -366,6 +366,8 @@ github.com/aws/aws-sdk-go-v2/service/opensearch v1.39.3 h1:EoXdh45m+CNUmP1tRFz+S github.com/aws/aws-sdk-go-v2/service/opensearch v1.39.3/go.mod h1:dt1En8oUmuPUz5AZjWi+fBeekG3O8WejKi1wgoafwNk= github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.13.4 h1:3Y4N61NHpii/6m38masM+VYJgnHhGtktEyJVZcTv0nc= github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.13.4/go.mod h1:pQOhum5PBwXCSspA6bT4EZLhpawWF2aHTToUu/5vIBg= +github.com/aws/aws-sdk-go-v2/service/opsworks v1.24.4 h1:2bzNoZZWJ8+lRIBfY/FSOdcRIfMYAae9DFwcYxIwD5w= +github.com/aws/aws-sdk-go-v2/service/opsworks v1.24.4/go.mod h1:yjoW6GYtJ1dRtOth68jEL3gYgSXVJicc2Ljcjxt3s/4= github.com/aws/aws-sdk-go-v2/service/organizations v1.30.3 h1:gYS53GRIaSesL04BlZA9MEBzDlENidWR/JDBXhZonFs= github.com/aws/aws-sdk-go-v2/service/organizations v1.30.3/go.mod h1:qdJX3WZbuAan5dXCoinnJjuY1QERCpv3glXeI3+wbeA= github.com/aws/aws-sdk-go-v2/service/osis v1.12.4 h1:D1+hSpaeBVydbHUc86o1Yv3EhOcM0CRazxOokfpC33g=