From 5aa37d94aa83020cb7925ce1a8fbacabb567a6c1 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 6 Feb 2024 23:30:13 +0100 Subject: [PATCH 001/112] feat (WIP): add imagebuilder lifecycle policy --- internal/conns/awsclient_gen.go | 5 + .../service/imagebuilder/lifecycle_policy.go | 443 ++++++++++++++++++ .../service_endpoints_gen_test.go | 66 ++- .../imagebuilder/service_package_gen.go | 13 + names/data/names_data.csv | 2 +- 5 files changed, 513 insertions(+), 16 deletions(-) create mode 100644 internal/service/imagebuilder/lifecycle_policy.go diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index ee560f6faa1..73b6ac4c800 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -66,6 +66,7 @@ import ( groundstation_sdkv2 "github.com/aws/aws-sdk-go-v2/service/groundstation" healthlake_sdkv2 "github.com/aws/aws-sdk-go-v2/service/healthlake" identitystore_sdkv2 "github.com/aws/aws-sdk-go-v2/service/identitystore" + imagebuilder_sdkv2 "github.com/aws/aws-sdk-go-v2/service/imagebuilder" inspector2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/inspector2" internetmonitor_sdkv2 "github.com/aws/aws-sdk-go-v2/service/internetmonitor" ivschat_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ivschat" @@ -739,6 +740,10 @@ func (c *AWSClient) ImageBuilderConn(ctx context.Context) *imagebuilder_sdkv1.Im return errs.Must(conn[*imagebuilder_sdkv1.Imagebuilder](ctx, c, names.ImageBuilder, make(map[string]any))) } +func (c *AWSClient) ImageBuilderClient(ctx context.Context) *imagebuilder_sdkv2.Client { + return errs.Must(client[*imagebuilder_sdkv2.Client](ctx, c, names.ImageBuilder, make(map[string]any))) +} + func (c *AWSClient) InspectorConn(ctx context.Context) *inspector_sdkv1.Inspector { return errs.Must(conn[*inspector_sdkv1.Inspector](ctx, c, names.Inspector, make(map[string]any))) } diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go new file mode 100644 index 00000000000..1fc6cb26c61 --- /dev/null +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -0,0 +1,443 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package imagebuilder + +import ( + "context" + "errors" + "fmt" + + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go/service/opensearchserverless" + "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/framework" + "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" + tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/names" +) + +// @FrameworkResource +func newResourceLifecyclePolicy(_ context.Context) (resource.ResourceWithConfigure, error) { + return &resourceLifecyclePolicy{}, nil +} + +type resourceLifecyclePolicyData struct { + ID types.String `tfsdk:"id"` + Arn types.String `tfsdk:"arn"` + Description types.String `tfsdk:"description"` + Name types.String `tfsdk:"name"` + ExecutionRole types.String `tfsdk:"execution_role"` + ResourceType types.String `tfsdk:"resource_type"` + Status types.String `tfsdk:"status"` + PolicyDetails resourcePolicyDetailsData `tfsdk:"policy_details"` + ResourceSelection resourceResourceSelectionData `tfsdk:"resource_selection"` +} + +type resourcePolicyDetailsData struct { + Action resourceActionData `tfsdk:"action"` + Filter resourceFilterData `tfsdk:"filter"` + ExclusionRules resourceExclusionRulesData `tfsdk:"exclusion_rules"` +} + +type resourceResourceSelectionData struct { + TagMap types.String `tfsdk:"tag_map"` + Recipes resourceRecipesData `tfsdk:"recipes"` +} + +type resourceRecipesData struct { + Name types.String `tfsdk:"name"` + SemanticVersion types.String `tfsdk:"semantic_version"` +} + +type resourceActionData struct { + Type types.String `tfsdk:"type"` + IncludeResources resourceIncludeResourcesData `tfsdk:"include_resources"` +} + +type resourceIncludeResourcesData struct { + Amis types.String `tfsdk:"amis"` + Containers types.String `tfsdk:"containers"` + Snapshots types.String `tfsdk:"snapshots"` +} + +type resourceFilterData struct { + Type types.String `tfsdk:"type"` + Value types.String `tfsdk:"value"` + RetainAtLeast types.String `tfsdk:"retain_at_least"` + Unit types.String `tfsdk:"unit"` +} + +type resourceExclusionRulesData struct { + AMIs resourceAMIsData `tfsdk:"ami"` + TagMap types.String `tfsdk:"tag_map"` +} + +type resourceAMIsData struct { + IsPublic types.String `tfsdk:"is_public"` + Regions types.String `tfsdk:"regions"` + SharedAccounts types.String `tfsdk:"shared_accounts"` + TagMap types.String `tfsdk:"tag_map"` + LastLaunched resourceLastLaunchedData `tfsdk:"last_launched"` +} + +type resourceLastLaunchedData struct { + Unit types.String `tfsdk:"unit"` + Value types.String `tfsdk:"value"` +} + +const ( + ResNameLifecyclePolicy = "Lifecycle Policy" +) + +type resourceLifecyclePolicy struct { + framework.ResourceWithConfigure +} + +func (r *resourceLifecyclePolicy) Metadata(_ context.Context, request resource.MetadataRequest, response *resource.MetadataResponse) { + response.TypeName = "aws_imagebuilder_lifecycle_policy" +} + +func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + Attributes: map[string]schema.Attribute{ + + "id": framework.IDAttribute(), + "name": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(3, 32), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "arn": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(3, 32), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "description": schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(1, 1000), + }, + }, + "execution_role": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(3, 32), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "resource_type": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(3, 32), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "status": schema.StringAttribute{ + Required: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(3, 32), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + names.AttrTags: tftags.TagsAttribute(), + names.AttrTagsAll: tftags.TagsAttributeComputedOnly(), + }, + Blocks: map[string]schema.Block{ + "policy_details": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Blocks: map[string]schema.Block{ + "action": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "type": schema.StringAttribute{ + Required: true, + }, + }, + Blocks: map[string]schema.Block{ + "include_resources": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "amis": schema.StringAttribute{ + Required: true, + }, + "containers": schema.StringAttribute{ + Required: true, + }, + "snapshots": schema.StringAttribute{ + Required: true, + }, + }, + }, + }, + }, + }, + }, + "filter": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "type": schema.StringAttribute{ + Required: true, + }, + "value": schema.StringAttribute{ + Required: true, + }, + "retain_at_least": schema.StringAttribute{ + Required: true, + }, + "unit": schema.StringAttribute{ + Required: true, + }, + }, + }, + }, + "exclusion_rules": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "tag_map": schema.StringAttribute{ + Required: true, + }, + }, + Blocks: map[string]schema.Block{ + "amis": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "is_public": schema.StringAttribute{ + Required: true, + }, + "regions": schema.StringAttribute{ + Required: true, + }, + "shared_accounts": schema.StringAttribute{ + Required: true, + }, + "tag_map": schema.StringAttribute{ + Required: true, + }, + }, + Blocks: map[string]schema.Block{ + "last_launched": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "unit": schema.StringAttribute{ + Required: true, + }, + "value": schema.StringAttribute{ + Required: true, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + "resource_selection": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "tag_map": schema.StringAttribute{ + Required: true, + }, + }, + Blocks: map[string]schema.Block{ + "recipes": schema.ListNestedBlock{ + Validators: []validator.List{ + listvalidator.SizeAtMost(1), + listvalidator.IsRequired(), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "name": schema.StringAttribute{ + Required: true, + }, + "semantic_version": schema.StringAttribute{ + Required: true, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var plan resourceLifecyclePolicyData + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + + if resp.Diagnostics.HasError() { + return + } + + conn := r.Meta().ImageBuilderClient(ctx) + + in := &imagebuilder.CreateLifecyclePolicyInput{ + ClientToken: aws.String(id.UniqueId()), + Name: aws.String(plan.Name.ValueString()), + } + + if !plan.Description.IsNull() { + in.Description = aws.String(plan.Description.ValueString()) + } + + out, err := conn.CreateLifecyclePolicy(ctx, in) + if err != nil { + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), nil), + err.Error(), + ) + return + } + + state := plan + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + conn := r.Meta().ImageBuilderClient(ctx) + + var state resourceLifecyclePolicyData + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + out, err := conn.GetLifecyclePolicy(ctx, &imagebuilder.GetLifecyclePolicyInput{ + LifecyclePolicyArn: aws.String(state.ID.ValueString()), + }) + if err != nil { + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionReading, ResNameLifecyclePolicy, state.Name.String(), nil), + err.Error(), + ) + return + } + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + conn := r.Meta().ImageBuilderClient(ctx) + + var plan, state resourceLifecyclePolicyData + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + if !plan.Description.Equal(state.Description) || + !plan.Policy.Equal(state.Policy) { + input := &opensearchserverless.UpdateAccessPolicyInput{ + ClientToken: aws.String(id.UniqueId()), + Name: flex.StringFromFramework(ctx, plan.Name), + PolicyVersion: flex.StringFromFramework(ctx, state.PolicyVersion), + Type: awstypes.AccessPolicyType(plan.Type.ValueString()), + } + + if !plan.Description.Equal(state.Description) { + input.Description = aws.String(plan.Description.ValueString()) + } + + if !plan.Policy.Equal(state.Policy) { + input.Policy = aws.String(plan.Policy.ValueString()) + } + + out, err := conn.UpdateAccessPolicy(ctx, input) + + if err != nil { + resp.Diagnostics.AddError(fmt.Sprintf("updating Security Policy (%s)", plan.Name.ValueString()), err.Error()) + return + } + } + + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) +} + +func (r *resourceLifecyclePolicy) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + conn := r.Meta().ImageBuilderClient(ctx) + + var state resourceLifecyclePolicyData + resp.Diagnostics.Append(req.State.Get(ctx, &state)...) + if resp.Diagnostics.HasError() { + return + } + + _, err := conn.DeleteLifecyclePolicy(ctx, &imagebuilder.DeleteLifecyclePolicyInput{ + LifecyclePolicyArn: aws.String(state.ID.ValueString()), + }) + if err != nil { + var nfe *awstypes.ResourceNotFoundException + if errors.As(err, &nfe) { + return + } + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionDeleting, ResNameLifecyclePolicy, state.Name.String(), nil), + err.Error(), + ) + } +} diff --git a/internal/service/imagebuilder/service_endpoints_gen_test.go b/internal/service/imagebuilder/service_endpoints_gen_test.go index 26797384e42..86c01451a2e 100644 --- a/internal/service/imagebuilder/service_endpoints_gen_test.go +++ b/internal/service/imagebuilder/service_endpoints_gen_test.go @@ -4,6 +4,7 @@ package imagebuilder_test import ( "context" + "errors" "fmt" "maps" "net/url" @@ -13,7 +14,8 @@ import ( "strings" "testing" - "github.com/aws/aws-sdk-go/aws/endpoints" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + imagebuilder_sdkv2 "github.com/aws/aws-sdk-go-v2/service/imagebuilder" imagebuilder_sdkv1 "github.com/aws/aws-sdk-go/service/imagebuilder" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" @@ -202,35 +204,69 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S }, } - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase + t.Run("v1", func(t *testing.T) { + for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv + testcase := testcase - t.Run(name, func(t *testing.T) { - testEndpointCase(t, region, testcase, callService) - }) - } + t.Run(name, func(t *testing.T) { + testEndpointCase(t, region, testcase, callServiceV1) + }) + } + }) + + t.Run("v2", func(t *testing.T) { + for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv + testcase := testcase + + t.Run(name, func(t *testing.T) { + testEndpointCase(t, region, testcase, callServiceV2) + }) + } + }) } func defaultEndpoint(region string) string { - r := endpoints.DefaultResolver() + r := imagebuilder_sdkv2.NewDefaultEndpointResolverV2() - ep, err := r.EndpointFor(imagebuilder_sdkv1.EndpointsID, region, func(opt *endpoints.Options) { - opt.ResolveUnknownService = true + ep, err := r.ResolveEndpoint(context.Background(), imagebuilder_sdkv2.EndpointParameters{ + Region: aws_sdkv2.String(region), }) if err != nil { return err.Error() } - url, _ := url.Parse(ep.URL) + if ep.URI.Path == "" { + ep.URI.Path = "/" + } + + return ep.URI.String() +} + +func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { + t.Helper() + + var endpoint string - if url.Path == "" { - url.Path = "/" + client := meta.ImageBuilderClient(ctx) + + _, err := client.ListImages(ctx, &imagebuilder_sdkv2.ListImagesInput{}, + func(opts *imagebuilder_sdkv2.Options) { + opts.APIOptions = append(opts.APIOptions, + addRetrieveEndpointURLMiddleware(t, &endpoint), + addCancelRequestMiddleware(), + ) + }, + ) + if err == nil { + t.Fatal("Expected an error, got none") + } else if !errors.Is(err, errCancelOperation) { + t.Fatalf("Unexpected error: %s", err) } - return url.String() + return endpoint } -func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { +func callServiceV1(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { t.Helper() client := meta.ImageBuilderConn(ctx) diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 625590f7756..03d2d54d760 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -5,6 +5,8 @@ package imagebuilder import ( "context" + aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + imagebuilder_sdkv2 "github.com/aws/aws-sdk-go-v2/service/imagebuilder" aws_sdkv1 "github.com/aws/aws-sdk-go/aws" session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" imagebuilder_sdkv1 "github.com/aws/aws-sdk-go/service/imagebuilder" @@ -163,6 +165,17 @@ func (p *servicePackage) NewConn(ctx context.Context, config map[string]any) (*i return imagebuilder_sdkv1.New(sess.Copy(&aws_sdkv1.Config{Endpoint: aws_sdkv1.String(config["endpoint"].(string))})), nil } +// NewClient returns a new AWS SDK for Go v2 client for this service package's AWS API. +func (p *servicePackage) NewClient(ctx context.Context, config map[string]any) (*imagebuilder_sdkv2.Client, error) { + cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) + + return imagebuilder_sdkv2.NewFromConfig(cfg, func(o *imagebuilder_sdkv2.Options) { + if endpoint := config["endpoint"].(string); endpoint != "" { + o.BaseEndpoint = aws_sdkv2.String(endpoint) + } + }), nil +} + func ServicePackage(ctx context.Context) conns.ServicePackage { return &servicePackage{} } diff --git a/names/data/names_data.csv b/names/data/names_data.csv index 5cdab0b6574..d883f09300d 100644 --- a/names/data/names_data.csv +++ b/names/data/names_data.csv @@ -130,7 +130,7 @@ dynamodbstreams,dynamodbstreams,dynamodbstreams,dynamodbstreams,,dynamodbstreams ,,,,,ec2ebs,ec2,,EC2EBS,,,,,aws_(ebs_|volume_attach|snapshot_create),aws_ec2ebs_,ebs_,ebs_;volume_attachment;snapshot_,EBS (EC2),Amazon,x,,,x,,,,,,Part of EC2 ebs,ebs,ebs,ebs,,ebs,,,EBS,EBS,,1,,,aws_ebs_,,changewhenimplemented,EBS (Elastic Block Store),Amazon,,x,,,,,EBS,,, ec2,ec2,ec2,ec2,,ec2,ec2,,EC2,EC2,,1,2,aws_(ami|availability_zone|ec2_(availability|capacity|fleet|host|instance|public_ipv4_pool|serial|spot|tag)|eip|instance|key_pair|launch_template|placement_group|spot),aws_ec2_,ec2_,ami;availability_zone;ec2_availability_;ec2_capacity_;ec2_fleet;ec2_host;ec2_image_;ec2_instance_;ec2_public_ipv4_pool;ec2_serial_;ec2_spot_;ec2_tag;eip;instance;key_pair;launch_template;placement_group;spot_,EC2 (Elastic Compute Cloud),Amazon,,,,,,,EC2,DescribeVpcs,, -imagebuilder,imagebuilder,imagebuilder,imagebuilder,,imagebuilder,,,ImageBuilder,Imagebuilder,,1,,,aws_imagebuilder_,,imagebuilder_,EC2 Image Builder,Amazon,,,,,,,imagebuilder,ListImages,, +imagebuilder,imagebuilder,imagebuilder,imagebuilder,,imagebuilder,,,ImageBuilder,Imagebuilder,,1,2,,aws_imagebuilder_,,imagebuilder_,EC2 Image Builder,Amazon,,,,,,,imagebuilder,ListImages,, ec2-instance-connect,ec2instanceconnect,ec2instanceconnect,ec2instanceconnect,,ec2instanceconnect,,,EC2InstanceConnect,EC2InstanceConnect,,1,,,aws_ec2instanceconnect_,,ec2instanceconnect_,EC2 Instance Connect,AWS,,x,,,,,EC2 Instance Connect,,, ecr,ecr,ecr,ecr,,ecr,,,ECR,ECR,,1,2,,aws_ecr_,,ecr_,ECR (Elastic Container Registry),Amazon,,,,,,,ECR,DescribeRepositories,, ecr-public,ecrpublic,ecrpublic,ecrpublic,,ecrpublic,,,ECRPublic,ECRPublic,,1,,,aws_ecrpublic_,,ecrpublic_,ECR Public,Amazon,,,,,,,ECR PUBLIC,DescribeRepositories,, From 0cf9f006de715632cdf33a03a4ea4680dde5da9b Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Fri, 16 Feb 2024 22:13:54 +0100 Subject: [PATCH 002/112] chore: fix root schema --- .../service/imagebuilder/lifecycle_policy.go | 54 ++++++++----------- 1 file changed, 23 insertions(+), 31 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 1fc6cb26c61..d94ba830deb 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/service/imagebuilder" "github.com/aws/aws-sdk-go/service/opensearchserverless" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" - "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" @@ -22,6 +21,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/framework" "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -112,57 +112,51 @@ func (r *resourceLifecyclePolicy) Metadata(_ context.Context, request resource.M func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ - "id": framework.IDAttribute(), "name": schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - stringvalidator.LengthBetween(3, 32), - }, + Optional: true, + Computed: true, PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), + stringplanmodifier.UseStateForUnknown(), }, }, "arn": schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - stringvalidator.LengthBetween(3, 32), - }, + Computed: true, PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), + stringplanmodifier.UseStateForUnknown(), }, }, "description": schema.StringAttribute{ Optional: true, - Validators: []validator.String{ - stringvalidator.LengthBetween(1, 1000), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), }, }, "execution_role": schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - stringvalidator.LengthBetween(3, 32), - }, + Optional: true, + Computed: true, PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), + stringplanmodifier.UseStateForUnknown(), }, }, "resource_type": schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - stringvalidator.LengthBetween(3, 32), - }, + Optional: true, + Computed: true, PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), + stringplanmodifier.UseStateForUnknown(), }, - }, - "status": schema.StringAttribute{ - Required: true, Validators: []validator.String{ - stringvalidator.LengthBetween(3, 32), + enum.FrameworkValidate[awstypes.LifecyclePolicyResourceType](), }, + }, + "status": schema.StringAttribute{ + Optional: true, + Computed: true, PlanModifiers: []planmodifier.String{ - stringplanmodifier.RequiresReplace(), + stringplanmodifier.UseStateForUnknown(), + }, + Validators: []validator.String{ + enum.FrameworkValidate[awstypes.LifecyclePolicyStatus](), }, }, names.AttrTags: tftags.TagsAttribute(), @@ -172,7 +166,6 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem "policy_details": schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Blocks: map[string]schema.Block{ @@ -293,7 +286,6 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem "resource_selection": schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ From d9f4ef0db46c6db74600e4b2b53e02e27f40e86d Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Fri, 16 Feb 2024 22:25:15 +0100 Subject: [PATCH 003/112] chore: fix nested schema attributes --- .../service/imagebuilder/lifecycle_policy.go | 71 +++++++++++-------- 1 file changed, 42 insertions(+), 29 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index d94ba830deb..fff6be8bc6c 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -178,24 +178,26 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem Attributes: map[string]schema.Attribute{ "type": schema.StringAttribute{ Required: true, + Validators: []validator.String{ + enum.FrameworkValidate[awstypes.LifecyclePolicyDetailActionType](), + }, }, }, Blocks: map[string]schema.Block{ "include_resources": schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "amis": schema.StringAttribute{ - Required: true, + "amis": schema.BoolAttribute{ + Optional: true, }, - "containers": schema.StringAttribute{ - Required: true, + "containers": schema.BoolAttribute{ + Optional: true, }, - "snapshots": schema.StringAttribute{ - Required: true, + "snapshots": schema.BoolAttribute{ + Optional: true, }, }, }, @@ -212,15 +214,21 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem Attributes: map[string]schema.Attribute{ "type": schema.StringAttribute{ Required: true, + Validators: []validator.String{ + enum.FrameworkValidate[awstypes.LifecyclePolicyDetailFilterType](), + }, }, - "value": schema.StringAttribute{ + "value": schema.Int64Attribute{ Required: true, }, - "retain_at_least": schema.StringAttribute{ - Required: true, + "retain_at_least": schema.Int64Attribute{ + Optional: true, }, "unit": schema.StringAttribute{ - Required: true, + Optional: true, + Validators: []validator.String{ + enum.FrameworkValidate[awstypes.LifecyclePolicyTimeUnit](), + }, }, }, }, @@ -228,47 +236,51 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem "exclusion_rules": schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "tag_map": schema.StringAttribute{ - Required: true, + "tag_map": schema.MapAttribute{ + ElementType: types.StringType, + Optional: true, }, }, Blocks: map[string]schema.Block{ "amis": schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "is_public": schema.StringAttribute{ - Required: true, + "is_public": schema.BoolAttribute{ + Optional: true, }, - "regions": schema.StringAttribute{ - Required: true, + "regions": schema.ListAttribute{ + ElementType: types.StringType, + Optional: true, }, - "shared_accounts": schema.StringAttribute{ - Required: true, + "shared_accounts": schema.ListAttribute{ + ElementType: types.StringType, + Optional: true, }, - "tag_map": schema.StringAttribute{ - Required: true, + "tag_map": schema.MapAttribute{ + ElementType: types.StringType, + Optional: true, }, }, Blocks: map[string]schema.Block{ "last_launched": schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ "unit": schema.StringAttribute{ Required: true, + Validators: []validator.String{ + enum.FrameworkValidate[awstypes.LifecyclePolicyTimeUnit](), + }, }, - "value": schema.StringAttribute{ + "value": schema.Int64Attribute{ Required: true, }, }, @@ -289,15 +301,16 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "tag_map": schema.StringAttribute{ - Required: true, + "tag_map": schema.MapAttribute{ + ElementType: types.StringType, + Optional: true, }, }, Blocks: map[string]schema.Block{ "recipes": schema.ListNestedBlock{ Validators: []validator.List{ - listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), + listvalidator.SizeAtLeast(1), + listvalidator.SizeAtMost(50), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ From 7bb7cd251e9468a7d6a38afe617bc644fcec2bc7 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 17 Feb 2024 15:16:39 +0100 Subject: [PATCH 004/112] feat: added read/update handlers --- .../service/imagebuilder/lifecycle_policy.go | 580 ++++++++++++++---- .../imagebuilder/service_package_gen.go | 7 +- 2 files changed, 474 insertions(+), 113 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index fff6be8bc6c..a1311be8e02 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -6,13 +6,14 @@ package imagebuilder import ( "context" "errors" - "fmt" "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "github.com/aws/aws-sdk-go/service/opensearchserverless" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" + "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" @@ -24,79 +25,16 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/framework" "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" + fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/names" ) -// @FrameworkResource +// @FrameworkResource(name="Lifecycle Policy") func newResourceLifecyclePolicy(_ context.Context) (resource.ResourceWithConfigure, error) { return &resourceLifecyclePolicy{}, nil } -type resourceLifecyclePolicyData struct { - ID types.String `tfsdk:"id"` - Arn types.String `tfsdk:"arn"` - Description types.String `tfsdk:"description"` - Name types.String `tfsdk:"name"` - ExecutionRole types.String `tfsdk:"execution_role"` - ResourceType types.String `tfsdk:"resource_type"` - Status types.String `tfsdk:"status"` - PolicyDetails resourcePolicyDetailsData `tfsdk:"policy_details"` - ResourceSelection resourceResourceSelectionData `tfsdk:"resource_selection"` -} - -type resourcePolicyDetailsData struct { - Action resourceActionData `tfsdk:"action"` - Filter resourceFilterData `tfsdk:"filter"` - ExclusionRules resourceExclusionRulesData `tfsdk:"exclusion_rules"` -} - -type resourceResourceSelectionData struct { - TagMap types.String `tfsdk:"tag_map"` - Recipes resourceRecipesData `tfsdk:"recipes"` -} - -type resourceRecipesData struct { - Name types.String `tfsdk:"name"` - SemanticVersion types.String `tfsdk:"semantic_version"` -} - -type resourceActionData struct { - Type types.String `tfsdk:"type"` - IncludeResources resourceIncludeResourcesData `tfsdk:"include_resources"` -} - -type resourceIncludeResourcesData struct { - Amis types.String `tfsdk:"amis"` - Containers types.String `tfsdk:"containers"` - Snapshots types.String `tfsdk:"snapshots"` -} - -type resourceFilterData struct { - Type types.String `tfsdk:"type"` - Value types.String `tfsdk:"value"` - RetainAtLeast types.String `tfsdk:"retain_at_least"` - Unit types.String `tfsdk:"unit"` -} - -type resourceExclusionRulesData struct { - AMIs resourceAMIsData `tfsdk:"ami"` - TagMap types.String `tfsdk:"tag_map"` -} - -type resourceAMIsData struct { - IsPublic types.String `tfsdk:"is_public"` - Regions types.String `tfsdk:"regions"` - SharedAccounts types.String `tfsdk:"shared_accounts"` - TagMap types.String `tfsdk:"tag_map"` - LastLaunched resourceLastLaunchedData `tfsdk:"last_launched"` -} - -type resourceLastLaunchedData struct { - Unit types.String `tfsdk:"unit"` - Value types.String `tfsdk:"value"` -} - const ( ResNameLifecyclePolicy = "Lifecycle Policy" ) @@ -112,20 +50,7 @@ func (r *resourceLifecyclePolicy) Metadata(_ context.Context, request resource.M func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ - "id": framework.IDAttribute(), - "name": schema.StringAttribute{ - Optional: true, - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), - }, - }, - "arn": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), - }, - }, + "arn": framework.ARNAttributeComputedOnly(), "description": schema.StringAttribute{ Optional: true, PlanModifiers: []planmodifier.String{ @@ -133,11 +58,11 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, }, "execution_role": schema.StringAttribute{ - Optional: true, - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), - }, + Required: true, + }, + "id": framework.IDAttribute(), + "name": schema.StringAttribute{ + Required: true, }, "resource_type": schema.StringAttribute{ Optional: true, @@ -163,9 +88,10 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem names.AttrTagsAll: tftags.TagsAttributeComputedOnly(), }, Blocks: map[string]schema.Block{ - "policy_details": schema.ListNestedBlock{ - Validators: []validator.List{ - listvalidator.SizeAtMost(1), + "policy_details": schema.SetNestedBlock{ + Validators: []validator.Set{ + setvalidator.SizeAtLeast(1), + setvalidator.SizeAtMost(3), }, NestedObject: schema.NestedBlockObject{ Blocks: map[string]schema.Block{ @@ -307,10 +233,10 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, }, Blocks: map[string]schema.Block{ - "recipes": schema.ListNestedBlock{ - Validators: []validator.List{ - listvalidator.SizeAtLeast(1), - listvalidator.SizeAtMost(50), + "recipes": schema.SetNestedBlock{ + Validators: []validator.Set{ + setvalidator.SizeAtLeast(1), + setvalidator.SizeAtMost(50), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ @@ -334,7 +260,6 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat var plan resourceLifecyclePolicyData resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { return } @@ -342,25 +267,68 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat conn := r.Meta().ImageBuilderClient(ctx) in := &imagebuilder.CreateLifecyclePolicyInput{ - ClientToken: aws.String(id.UniqueId()), - Name: aws.String(plan.Name.ValueString()), + ClientToken: aws.String(id.UniqueId()), + ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), + Name: aws.String(plan.Name.ValueString()), + ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), + Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), + //Tags: getTagsIn(ctx), } if !plan.Description.IsNull() { in.Description = aws.String(plan.Description.ValueString()) } + if !plan.PolicyDetails.IsNull() { + var tfList []resourcePolicyDetailsData + resp.Diagnostics.Append(plan.PolicyDetails.ElementsAs(ctx, &tfList, false)...) + if resp.Diagnostics.HasError() { + return + } + + policyDetails, d := expandPolicyDetails(ctx, tfList) + resp.Diagnostics.Append(d...) + if resp.Diagnostics.HasError() { + return + } + in.PolicyDetails = policyDetails + } + + if !plan.ResourceSelection.IsNull() { + var tfList []resourceResourceSelectionData + resp.Diagnostics.Append(plan.ResourceSelection.ElementsAs(ctx, &tfList, false)...) + if resp.Diagnostics.HasError() { + return + } + + resourceSelection, d := expandResourceSelection(ctx, tfList) + resp.Diagnostics.Append(d...) + if resp.Diagnostics.HasError() { + return + } + in.ResourceSelection = resourceSelection + } + out, err := conn.CreateLifecyclePolicy(ctx, in) if err != nil { resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), nil), + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), err), err.Error(), ) return } + if out == nil { + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), nil), + errors.New("empty output").Error(), + ) + return + } - state := plan - resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) + plan.ID = flex.StringToFramework(ctx, out.LifecyclePolicyArn) + plan.ARN = flex.StringToFrameworkARN(ctx, out.LifecyclePolicyArn) + + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) } func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { @@ -396,31 +364,70 @@ func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.Updat } if !plan.Description.Equal(state.Description) || - !plan.Policy.Equal(state.Policy) { - input := &opensearchserverless.UpdateAccessPolicyInput{ - ClientToken: aws.String(id.UniqueId()), - Name: flex.StringFromFramework(ctx, plan.Name), - PolicyVersion: flex.StringFromFramework(ctx, state.PolicyVersion), - Type: awstypes.AccessPolicyType(plan.Type.ValueString()), + !plan.ExecutionRole.Equal(state.ExecutionRole) || + !plan.PolicyDetails.Equal(state.PolicyDetails) || + !plan.ResourceSelection.Equal(state.ResourceSelection) || + !plan.ResourceType.Equal(state.ResourceType) || + !plan.Status.Equal(state.Status) { + + in := &imagebuilder.UpdateLifecyclePolicyInput{ + ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), + ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), + Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), } if !plan.Description.Equal(state.Description) { - input.Description = aws.String(plan.Description.ValueString()) + in.Description = aws.String(plan.Description.ValueString()) } - if !plan.Policy.Equal(state.Policy) { - input.Policy = aws.String(plan.Policy.ValueString()) + if !plan.PolicyDetails.Equal(state.PolicyDetails) { + var tfList []resourcePolicyDetailsData + resp.Diagnostics.Append(plan.PolicyDetails.ElementsAs(ctx, &tfList, false)...) + if resp.Diagnostics.HasError() { + return + } + + policyDetails, d := expandPolicyDetails(ctx, tfList) + resp.Diagnostics.Append(d...) + if resp.Diagnostics.HasError() { + return + } + in.PolicyDetails = policyDetails } - out, err := conn.UpdateAccessPolicy(ctx, input) + if !plan.ResourceSelection.Equal(state.ResourceSelection) { + var tfList []resourceResourceSelectionData + resp.Diagnostics.Append(plan.ResourceSelection.ElementsAs(ctx, &tfList, false)...) + if resp.Diagnostics.HasError() { + return + } + + resourceSelection, d := expandResourceSelection(ctx, tfList) + resp.Diagnostics.Append(d...) + if resp.Diagnostics.HasError() { + return + } + in.ResourceSelection = resourceSelection + } + out, err := conn.UpdateLifecyclePolicy(ctx, in) if err != nil { - resp.Diagnostics.AddError(fmt.Sprintf("updating Security Policy (%s)", plan.Name.ValueString()), err.Error()) + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionUpdating, ResNameLifecyclePolicy, plan.ID.String(), err), + err.Error(), + ) + return + } + if out == nil { + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionUpdating, ResNameLifecyclePolicy, plan.ID.String(), nil), + errors.New("empty output").Error(), + ) return } } - resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) + resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) } func (r *resourceLifecyclePolicy) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { @@ -446,3 +453,352 @@ func (r *resourceLifecyclePolicy) Delete(ctx context.Context, req resource.Delet ) } } + +func (r *resourceLifecyclePolicy) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) +} + +func (r *resourceLifecyclePolicy) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { + r.SetTagsAll(ctx, req, resp) +} + +func expandPolicyDetails(ctx context.Context, tfList []resourcePolicyDetailsData) ([]awstypes.LifecyclePolicyDetail, diag.Diagnostics) { + var diags diag.Diagnostics + + if len(tfList) == 0 { + return nil, diags + } + + apiResult := []awstypes.LifecyclePolicyDetail{} + + for _, policyDetail := range tfList { + apiObject := awstypes.LifecyclePolicyDetail{} + + if !policyDetail.Action.IsNull() { + var tfList []resourceActionData + diags.Append(policyDetail.Action.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + action, d := expandPolicyDetailAction(ctx, tfList) + diags.Append(d...) + if diags.HasError() { + return nil, diags + } + apiObject.Action = action + } + + if !policyDetail.Filter.IsNull() { + var tfList []resourceFilterData + diags.Append(policyDetail.Filter.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + filter, d := expandPolicyDetailFilter(ctx, tfList) + diags.Append(d...) + if diags.HasError() { + return nil, diags + } + apiObject.Filter = filter + } + + if !policyDetail.ExclusionRules.IsNull() { + var tfList []resourceExclusionRulesData + diags.Append(policyDetail.ExclusionRules.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + exclusionRules, d := expandPolicyDetailExclusionRules(ctx, tfList) + diags.Append(d...) + if diags.HasError() { + return nil, diags + } + apiObject.ExclusionRules = exclusionRules + } + + apiResult = append(apiResult, apiObject) + } + + return apiResult, diags +} + +func expandPolicyDetailAction(ctx context.Context, tfList []resourceActionData) (*awstypes.LifecyclePolicyDetailAction, diag.Diagnostics) { + var diags diag.Diagnostics + + if len(tfList) == 0 { + return nil, diags + } + + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyDetailAction{} + + if !tfObj.IncludeResources.IsNull() { + var tfList []resourceIncludeResourcesData + diags.Append(tfObj.IncludeResources.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + apiObject.IncludeResources = expandPolicyDetailActionIncludeResources(tfList) + } + + if !tfObj.Type.IsNull() { + apiObject.Type = awstypes.LifecyclePolicyDetailActionType(tfObj.Type.ValueString()) + } + + return &apiObject, diags +} + +func expandPolicyDetailActionIncludeResources(tfList []resourceIncludeResourcesData) *awstypes.LifecyclePolicyDetailActionIncludeResources { + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyDetailActionIncludeResources{} + + if !tfObj.Amis.IsNull() { + apiObject.Amis = aws.ToBool(tfObj.Amis.ValueBoolPointer()) + } + + if !tfObj.Containers.IsNull() { + apiObject.Containers = aws.ToBool(tfObj.Containers.ValueBoolPointer()) + } + + if !tfObj.Snapshots.IsNull() { + apiObject.Snapshots = aws.ToBool(tfObj.Snapshots.ValueBoolPointer()) + } + + return &apiObject +} + +func expandPolicyDetailFilter(ctx context.Context, tfList []resourceFilterData) (*awstypes.LifecyclePolicyDetailFilter, diag.Diagnostics) { + var diags diag.Diagnostics + + if len(tfList) == 0 { + return nil, diags + } + + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyDetailFilter{} + + if !tfObj.Type.IsNull() { + apiObject.Type = awstypes.LifecyclePolicyDetailFilterType(tfObj.Type.ValueString()) + } + + if !tfObj.Value.IsNull() { + apiObject.Value = aws.Int32(int32(tfObj.Value.ValueInt64())) + } + + if !tfObj.RetainAtLeast.IsNull() { + apiObject.RetainAtLeast = aws.Int32(int32(tfObj.RetainAtLeast.ValueInt64())) + } + + if !tfObj.Unit.IsNull() { + apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Type.ValueString()) + } + + return &apiObject, diags +} + +func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExclusionRulesData) (*awstypes.LifecyclePolicyDetailExclusionRules, diag.Diagnostics) { + var diags diag.Diagnostics + + if len(tfList) == 0 { + return nil, diags + } + + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyDetailExclusionRules{} + + if !tfObj.AMIs.IsNull() { + var tfList []resourceAMIsData + diags.Append(tfObj.AMIs.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + Amis, d := expandPolicyDetailExclusionRulesAmis(ctx, tfList) + diags.Append(d...) + if diags.HasError() { + return nil, diags + } + apiObject.Amis = Amis + } + + if !tfObj.TagMap.IsNull() { + apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + } + + return &apiObject, diags +} + +func expandPolicyDetailExclusionRulesAmis(ctx context.Context, tfList []resourceAMIsData) (*awstypes.LifecyclePolicyDetailExclusionRulesAmis, diag.Diagnostics) { + var diags diag.Diagnostics + + if len(tfList) == 0 { + return nil, diags + } + + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyDetailExclusionRulesAmis{} + + if !tfObj.IsPublic.IsNull() { + apiObject.IsPublic = aws.ToBool(tfObj.IsPublic.ValueBoolPointer()) + } + + if !tfObj.LastLaunched.IsNull() { + var tfList []resourceLastLaunchedData + diags.Append(tfObj.LastLaunched.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + apiObject.LastLaunched = expandPolicyDetailExclusionRulesAmisLastLaunched(tfList) + } + + if !tfObj.Regions.IsNull() { + apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.LastLaunched) + } + + if !tfObj.SharedAccounts.IsNull() { + apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.SharedAccounts) + } + + if !tfObj.TagMap.IsNull() { + apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + } + + return &apiObject, diags +} + +func expandPolicyDetailExclusionRulesAmisLastLaunched(tfList []resourceLastLaunchedData) *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched { + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched{} + + if !tfObj.Unit.IsNull() { + apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Unit.ValueString()) + } + + if !tfObj.Value.IsNull() { + apiObject.Value = aws.Int32(int32(tfObj.Value.ValueInt64())) + } + + return &apiObject +} + +func expandResourceSelection(ctx context.Context, tfList []resourceResourceSelectionData) (*awstypes.LifecyclePolicyResourceSelection, diag.Diagnostics) { + var diags diag.Diagnostics + + if len(tfList) == 0 { + return nil, diags + } + + tfObj := tfList[0] + + apiObject := awstypes.LifecyclePolicyResourceSelection{} + + if !tfObj.Recipes.IsNull() { + var tfList []resourceRecipesData + diags.Append(tfObj.Recipes.ElementsAs(ctx, &tfList, false)...) + if diags.HasError() { + return nil, diags + } + + apiObject.Recipes = expandResourceSelectionRecipes(tfList) + } + + if !tfObj.TagMap.IsNull() { + apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + } + + return &apiObject, diags +} + +func expandResourceSelectionRecipes(tfList []resourceRecipesData) []awstypes.LifecyclePolicyResourceSelectionRecipe { + apiResult := []awstypes.LifecyclePolicyResourceSelectionRecipe{} + + for _, tfObj := range tfList { + apiObject := awstypes.LifecyclePolicyResourceSelectionRecipe{} + + if !tfObj.Name.IsNull() { + apiObject.SemanticVersion = aws.String(tfObj.Name.ValueString()) + } + if !tfObj.SemanticVersion.IsNull() { + apiObject.SemanticVersion = aws.String(tfObj.SemanticVersion.ValueString()) + } + + apiResult = append(apiResult, apiObject) + + } + return apiResult +} + +type resourceLifecyclePolicyData struct { + ID types.String `tfsdk:"id"` + ARN fwtypes.ARN `tfsdk:"arn"` + Description types.String `tfsdk:"description"` + Name types.String `tfsdk:"name"` + ExecutionRole types.String `tfsdk:"execution_role"` + ResourceType types.String `tfsdk:"resource_type"` + Status types.String `tfsdk:"status"` + PolicyDetails types.Set `tfsdk:"policy_details"` + ResourceSelection types.List `tfsdk:"resource_selection"` +} + +type resourcePolicyDetailsData struct { + Action types.List `tfsdk:"action"` + Filter types.List `tfsdk:"filter"` + ExclusionRules types.List `tfsdk:"exclusion_rules"` +} + +type resourceResourceSelectionData struct { + TagMap types.Map `tfsdk:"tag_map"` + Recipes types.Set `tfsdk:"recipes"` +} + +type resourceRecipesData struct { + Name types.String `tfsdk:"name"` + SemanticVersion types.String `tfsdk:"semantic_version"` +} + +type resourceActionData struct { + Type types.String `tfsdk:"type"` + IncludeResources types.List `tfsdk:"include_resources"` +} + +type resourceIncludeResourcesData struct { + Amis types.Bool `tfsdk:"amis"` + Containers types.Bool `tfsdk:"containers"` + Snapshots types.Bool `tfsdk:"snapshots"` +} + +type resourceFilterData struct { + Type types.String `tfsdk:"type"` + Value types.Int64 `tfsdk:"value"` + RetainAtLeast types.Int64 `tfsdk:"retain_at_least"` + Unit types.String `tfsdk:"unit"` +} + +type resourceExclusionRulesData struct { + AMIs types.List `tfsdk:"ami"` + TagMap types.Map `tfsdk:"tag_map"` +} + +type resourceAMIsData struct { + IsPublic types.Bool `tfsdk:"is_public"` + LastLaunched types.List `tfsdk:"last_launched"` + Regions types.List `tfsdk:"regions"` + SharedAccounts types.List `tfsdk:"shared_accounts"` + TagMap types.Map `tfsdk:"tag_map"` +} + +type resourceLastLaunchedData struct { + Unit types.String `tfsdk:"unit"` + Value types.Int64 `tfsdk:"value"` +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 03d2d54d760..1287110ff43 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -22,7 +22,12 @@ func (p *servicePackage) FrameworkDataSources(ctx context.Context) []*types.Serv } func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.ServicePackageFrameworkResource { - return []*types.ServicePackageFrameworkResource{} + return []*types.ServicePackageFrameworkResource{ + { + Factory: newResourceLifecyclePolicy, + Name: "Lifecycle Policy", + }, + } } func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePackageSDKDataSource { From d3ce450b46ceb7eaab6e3fd82bfba76e7125f27e Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 17 Feb 2024 15:20:37 +0100 Subject: [PATCH 005/112] feat: added recreate on name update --- internal/service/imagebuilder/lifecycle_policy.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index a1311be8e02..c2bf368655f 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -63,6 +63,9 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem "id": framework.IDAttribute(), "name": schema.StringAttribute{ Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, }, "resource_type": schema.StringAttribute{ Optional: true, From 854fa6c0231d3e43c585a609ae1d9bf5afe403cd Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 17 Feb 2024 21:19:36 +0100 Subject: [PATCH 006/112] feat: added resource attribute tyoes --- .../service/imagebuilder/lifecycle_policy.go | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index c2bf368655f..f37d21eae95 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -12,6 +12,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" + "github.com/hashicorp/terraform-plugin-framework/attr" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" @@ -805,3 +806,55 @@ type resourceLastLaunchedData struct { Unit types.String `tfsdk:"unit"` Value types.Int64 `tfsdk:"value"` } + +var resourcePolicyDetailAttrTypes = map[string]attr.Type{ + "action": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceActionAttrTypes}}, + "filter": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceFilterAttrTypes}}, + "exclusion_rules": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceExclusionRulesAttrTypes}}, +} + +var resourceActionAttrTypes = map[string]attr.Type{ + "type": types.StringType, + "include_resources": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceIncludeResourcesAttrTypes}}, +} + +var resourceIncludeResourcesAttrTypes = map[string]attr.Type{ + "amis": types.BoolType, + "containers": types.BoolType, + "snapshots": types.BoolType, +} + +var resourceFilterAttrTypes = map[string]attr.Type{ + "type": types.StringType, + "value": types.Int64Type, + "retain_at_least": types.Int64Type, + "unit": types.StringType, +} + +var resourceExclusionRulesAttrTypes = map[string]attr.Type{ + "amis": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceAmisAttrTypes}}, + "tag_map": types.MapType{ElemType: types.StringType}, +} + +var resourceAmisAttrTypes = map[string]attr.Type{ + "is_public": types.BoolType, + "last_launched": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceLastLaunchedAttrTypes}}, + "regions": types.ListType{ElemType: types.StringType}, + "shared_accounts": types.ListType{ElemType: types.StringType}, + "tag_map": types.MapType{ElemType: types.StringType}, +} + +var resourceLastLaunchedAttrTypes = map[string]attr.Type{ + "unit": types.StringType, + "value": types.Int64Type, +} + +var resourceResourceSelectionAttrTypes = map[string]attr.Type{ + "recipes": types.SetType{ElemType: types.ObjectType{AttrTypes: resourceRecipeAttrTypes}}, + "tag_map": types.MapType{ElemType: types.StringType}, +} + +var resourceRecipeAttrTypes = map[string]attr.Type{ + "name": types.StringType, + "semantic_version": types.StringType, +} From 182b7eab8d5aaaf4f9c836537ab4dad3c1e83a67 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 17 Feb 2024 21:32:55 +0100 Subject: [PATCH 007/112] feat: added get func and basic read handler --- .../service/imagebuilder/lifecycle_policy.go | 45 +++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index f37d21eae95..55ba21dbde1 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -22,12 +22,15 @@ import ( "github.com/hashicorp/terraform-plugin-framework/schema/validator" "github.com/hashicorp/terraform-plugin-framework/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "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/framework" "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -344,9 +347,11 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq return } - out, err := conn.GetLifecyclePolicy(ctx, &imagebuilder.GetLifecyclePolicyInput{ - LifecyclePolicyArn: aws.String(state.ID.ValueString()), - }) + out, err := findLifecyclePolicyByARN(ctx, conn, state.ID.String()) + + if tfresource.NotFound(err) { + resp.State.RemoveResource(ctx) + } if err != nil { resp.Diagnostics.AddError( create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionReading, ResNameLifecyclePolicy, state.Name.String(), nil), @@ -354,6 +359,17 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq ) return } + + state.ARN = flex.StringToFrameworkARN(ctx, out.Arn) + state.ID = flex.StringToFramework(ctx, out.Arn) + state.Description = flex.StringToFramework(ctx, out.Description) + state.ExecutionRole = flex.StringToFramework(ctx, out.ExecutionRole) + state.Name = flex.StringToFramework(ctx, out.Name) + //PolicyDetails + flatteners + //resourceSelection + flatteners + state.ResourceType = flex.StringValueToFramework(ctx, out.ResourceType) + state.Status = flex.StringValueToFramework(ctx, out.Status) + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } @@ -466,6 +482,29 @@ func (r *resourceLifecyclePolicy) ModifyPlan(ctx context.Context, req resource.M r.SetTagsAll(ctx, req, resp) } +func findLifecyclePolicyByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.LifecyclePolicy, error) { + in := &imagebuilder.GetLifecyclePolicyInput{ + LifecyclePolicyArn: aws.String(arn), + } + + out, err := conn.GetLifecyclePolicy(ctx, in) + if err != nil { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: in, + } + } + return nil, err + } + + if out == nil { + return nil, tfresource.NewEmptyResultError(in) + } + + return out.LifecyclePolicy, nil +} + func expandPolicyDetails(ctx context.Context, tfList []resourcePolicyDetailsData) ([]awstypes.LifecyclePolicyDetail, diag.Diagnostics) { var diags diag.Diagnostics From 4177badcbabb9835c9070d92ff3dbbbacc8708f6 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 17 Feb 2024 22:08:10 +0100 Subject: [PATCH 008/112] feat: added flatteners --- .../service/imagebuilder/lifecycle_policy.go | 283 +++++++++++++++++- 1 file changed, 281 insertions(+), 2 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 55ba21dbde1..82d3705436c 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -365,8 +365,15 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq state.Description = flex.StringToFramework(ctx, out.Description) state.ExecutionRole = flex.StringToFramework(ctx, out.ExecutionRole) state.Name = flex.StringToFramework(ctx, out.Name) - //PolicyDetails + flatteners - //resourceSelection + flatteners + + policyDetails, d := flattenPolicyDetails(ctx, out.PolicyDetails) + resp.Diagnostics.Append(d...) + state.PolicyDetails = policyDetails + + resourceSelection, d := flattenResourceSelection(ctx, out.ResourceSelection) + resp.Diagnostics.Append(d...) + state.ResourceSelection = resourceSelection + state.ResourceType = flex.StringValueToFramework(ctx, out.ResourceType) state.Status = flex.StringValueToFramework(ctx, out.Status) @@ -782,6 +789,278 @@ func expandResourceSelectionRecipes(tfList []resourceRecipesData) []awstypes.Lif return apiResult } +func flattenPolicyDetails(ctx context.Context, apiObject []awstypes.LifecyclePolicyDetail) (types.Set, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceActionAttrTypes} + + if apiObject == nil { + return types.SetNull(elemType), diags + } + + result := []attr.Value{} + + for _, policyDetail := range apiObject { + action, d := flattenDetailAction(ctx, policyDetail.Action) + diags.Append(d...) + + filter, d := flattenDetailFilter(ctx, policyDetail.Filter) + diags.Append(d...) + + exclusionRules, d := flattenDetailExclusionRules(ctx, policyDetail.ExclusionRules) + diags.Append(d...) + + obj := map[string]attr.Value{ + "action": action, + "filter": filter, + "exclusion_rules": exclusionRules, + } + + objVal, d := types.ObjectValue(resourcePolicyDetailAttrTypes, obj) + diags.Append(d...) + + result = append(result, objVal) + } + + setVal, d := types.SetValue(elemType, result) + diags.Append(d...) + + return setVal, diags +} + +func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailAction) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceActionAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{ + "type": flex.StringValueToFramework(ctx, apiObject.Type), + } + + if apiObject.IncludeResources != nil { + includeResources, d := flattenIncludeResources(ctx, apiObject.IncludeResources) + diags.Append(d...) + + obj["include_resources"] = includeResources + } + + objVal, d := types.ObjectValue(resourceActionAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenIncludeResources(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailActionIncludeResources) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceIncludeResourcesAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{ + "amis": flex.BoolToFramework(ctx, &apiObject.Amis), + "containers": flex.BoolToFramework(ctx, &apiObject.Containers), + "snapshots": flex.BoolToFramework(ctx, &apiObject.Snapshots), + } + + objVal, d := types.ObjectValue(resourceIncludeResourcesAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailFilter) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceFilterAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{ + "type": flex.StringValueToFramework(ctx, apiObject.Type), + "value": flex.Int32ToFramework(ctx, apiObject.Value), + "retain_at_least": flex.Int32ToFramework(ctx, apiObject.RetainAtLeast), + "unit": flex.StringValueToFramework(ctx, apiObject.Unit), + } + + objVal, d := types.ObjectValue(resourceFilterAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRules) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceExclusionRulesAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{} + + if apiObject.Amis != nil { + amis, d := flattenExclusionRulesAmis(ctx, apiObject.Amis) + diags.Append(d...) + + obj["amis"] = amis + } + + if apiObject.TagMap != nil { + obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + } + + objVal, d := types.ObjectValue(resourceExclusionRulesAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmis) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceAmisAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{ + "is_public": flex.BoolToFramework(ctx, &apiObject.IsPublic), + } + + if apiObject.LastLaunched != nil { + lastLaunched, d := flattenExclusionRulesAmisLastLaunched(ctx, apiObject.LastLaunched) + diags.Append(d...) + + obj["last_launched"] = lastLaunched + } + + if apiObject.Regions != nil { + obj["regions"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions) + } + + if apiObject.SharedAccounts != nil { + obj["shared_accounts"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts) + } + + if apiObject.TagMap != nil { + obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + } + + objVal, d := types.ObjectValue(resourceAmisAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenExclusionRulesAmisLastLaunched(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceLastLaunchedAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{ + "unit": flex.StringValueToFramework(ctx, apiObject.Unit), + "value": flex.Int32ToFramework(ctx, apiObject.Value), + } + + objVal, d := types.ObjectValue(resourceLastLaunchedAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenResourceSelection(ctx context.Context, apiObject *awstypes.LifecyclePolicyResourceSelection) (types.List, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceResourceSelectionAttrTypes} + + if apiObject == nil { + return types.ListNull(elemType), diags + } + + obj := map[string]attr.Value{} + + if apiObject.Recipes != nil { + recipes, d := flattenResourceSelectionRecipes(ctx, apiObject.Recipes) + diags.Append(d...) + + obj["recipes"] = recipes + } + + if apiObject.TagMap != nil { + obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + } + + objVal, d := types.ObjectValue(resourceResourceSelectionAttrTypes, obj) + diags.Append(d...) + + listVal, d := types.ListValue(elemType, []attr.Value{objVal}) + diags.Append(d...) + + return listVal, diags + +} + +func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.LifecyclePolicyResourceSelectionRecipe) (types.Set, diag.Diagnostics) { + var diags diag.Diagnostics + elemType := types.ObjectType{AttrTypes: resourceRecipeAttrTypes} + + if apiObject == nil { + return types.SetNull(elemType), diags + } + + result := []attr.Value{} + + for _, recipe := range apiObject { + + obj := map[string]attr.Value{ + "name": flex.StringToFramework(ctx, recipe.Name), + "semantic_version": flex.StringToFramework(ctx, recipe.SemanticVersion), + } + + objVal, d := types.ObjectValue(resourceRecipeAttrTypes, obj) + diags.Append(d...) + + result = append(result, objVal) + } + + listVal, d := types.SetValue(elemType, result) + diags.Append(d...) + + return listVal, diags + +} + type resourceLifecyclePolicyData struct { ID types.String `tfsdk:"id"` ARN fwtypes.ARN `tfsdk:"arn"` From 4655ace00f7421792f561b603b77205663ecbe77 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 17 Feb 2024 22:28:19 +0100 Subject: [PATCH 009/112] feat: added basic test and exports --- internal/service/imagebuilder/export_tests.go | 12 ++ .../imagebuilder/lifecycle_policy_test.go | 104 ++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 internal/service/imagebuilder/export_tests.go create mode 100644 internal/service/imagebuilder/lifecycle_policy_test.go diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go new file mode 100644 index 00000000000..135738a6880 --- /dev/null +++ b/internal/service/imagebuilder/export_tests.go @@ -0,0 +1,12 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package imagebuilder + +// Exports for use in tests only. + +var ( + ResourceLifecyclePolicy = newResourceLifecyclePolicy + + FindLifecyclePolicyByARN = findLifecyclePolicyByARN +) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go new file mode 100644 index 00000000000..9311d2518db --- /dev/null +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -0,0 +1,104 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package imagebuilder_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/hashicorp/terraform-provider-aws/internal/acctest" + "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/create" + tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/names" +) + +func TestAccLifecyclePolicy_basic(t *testing.T) { + ctx := acctest.Context(t) + var lifecyclePolicy types.LifecyclePolicy + resourceName := "aws_imagebuilder_lifecycle_policy.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(ctx, t) }, + ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilder), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccLifecyclePolicyConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName, &lifecyclePolicy), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckLifecyclePolicyExists(ctx context.Context, name string, lifecyclePolicy *types.LifecyclePolicy) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, name, errors.New("not found")) + } + + if rs.Primary.ID == "" { + return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, name, errors.New("not set")) + } + + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) + resp, err := tfimagebuilder.FindLifecyclePolicyByARN(ctx, conn, rs.Primary.ID) + if err != nil { + return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, err) + } + + *lifecyclePolicy = *resp + + return nil + } +} + +func testAccCheckLifecyclePolicyDestroy(ctx context.Context) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_imagebuilder_lifecycle_policy" { + continue + } + + _, err := tfimagebuilder.FindLifecyclePolicyByARN(ctx, conn, rs.Primary.ID) + if tfresource.NotFound(err) { + return nil + } + if err != nil { + return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, err) + } + + return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, errors.New("not destroyed")) + } + + return nil + } +} + +func testAccLifecyclePolicyConfig_basic(rName string) string { + return fmt.Sprintf(` +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q +} +`, rName) +} From d502ea3f19fc8f9784dc5f018bfcef85f277eb78 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Mon, 19 Feb 2024 23:48:06 +0100 Subject: [PATCH 010/112] chore: begin migrating imagebuilder service to v2 sdk --- internal/conns/awsclient_gen.go | 5 --- .../service_endpoints_gen_test.go | 41 ++++--------------- .../imagebuilder/service_package_gen.go | 10 ----- names/data/names_data.csv | 2 +- names/names.go | 2 + 5 files changed, 10 insertions(+), 50 deletions(-) diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index 73b6ac4c800..60e56b85132 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -196,7 +196,6 @@ import ( greengrass_sdkv1 "github.com/aws/aws-sdk-go/service/greengrass" guardduty_sdkv1 "github.com/aws/aws-sdk-go/service/guardduty" iam_sdkv1 "github.com/aws/aws-sdk-go/service/iam" - imagebuilder_sdkv1 "github.com/aws/aws-sdk-go/service/imagebuilder" inspector_sdkv1 "github.com/aws/aws-sdk-go/service/inspector" iot_sdkv1 "github.com/aws/aws-sdk-go/service/iot" iotanalytics_sdkv1 "github.com/aws/aws-sdk-go/service/iotanalytics" @@ -736,10 +735,6 @@ func (c *AWSClient) IdentityStoreClient(ctx context.Context) *identitystore_sdkv return errs.Must(client[*identitystore_sdkv2.Client](ctx, c, names.IdentityStore, make(map[string]any))) } -func (c *AWSClient) ImageBuilderConn(ctx context.Context) *imagebuilder_sdkv1.Imagebuilder { - return errs.Must(conn[*imagebuilder_sdkv1.Imagebuilder](ctx, c, names.ImageBuilder, make(map[string]any))) -} - func (c *AWSClient) ImageBuilderClient(ctx context.Context) *imagebuilder_sdkv2.Client { return errs.Must(client[*imagebuilder_sdkv2.Client](ctx, c, names.ImageBuilder, make(map[string]any))) } diff --git a/internal/service/imagebuilder/service_endpoints_gen_test.go b/internal/service/imagebuilder/service_endpoints_gen_test.go index 86c01451a2e..0e25bc29817 100644 --- a/internal/service/imagebuilder/service_endpoints_gen_test.go +++ b/internal/service/imagebuilder/service_endpoints_gen_test.go @@ -16,7 +16,6 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" imagebuilder_sdkv2 "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - imagebuilder_sdkv1 "github.com/aws/aws-sdk-go/service/imagebuilder" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/google/go-cmp/cmp" @@ -204,25 +203,13 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S }, } - t.Run("v1", func(t *testing.T) { - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase + for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv + testcase := testcase - t.Run(name, func(t *testing.T) { - testEndpointCase(t, region, testcase, callServiceV1) - }) - } - }) - - t.Run("v2", func(t *testing.T) { - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase - - t.Run(name, func(t *testing.T) { - testEndpointCase(t, region, testcase, callServiceV2) - }) - } - }) + t.Run(name, func(t *testing.T) { + testEndpointCase(t, region, testcase, callService) + }) + } } func defaultEndpoint(region string) string { @@ -242,7 +229,7 @@ func defaultEndpoint(region string) string { return ep.URI.String() } -func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { +func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { t.Helper() var endpoint string @@ -266,20 +253,6 @@ func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) str return endpoint } -func callServiceV1(ctx context.Context, t *testing.T, meta *conns.AWSClient) string { - t.Helper() - - client := meta.ImageBuilderConn(ctx) - - req, _ := client.ListImagesRequest(&imagebuilder_sdkv1.ListImagesInput{}) - - req.HTTPRequest.URL.Path = "/" - - endpoint := req.HTTPRequest.URL.String() - - return endpoint -} - func withNoConfig(_ *caseSetup) { // no-op } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 1287110ff43..e7968590a45 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -7,9 +7,6 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" imagebuilder_sdkv2 "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - imagebuilder_sdkv1 "github.com/aws/aws-sdk-go/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/types" "github.com/hashicorp/terraform-provider-aws/names" @@ -163,13 +160,6 @@ func (p *servicePackage) ServicePackageName() string { return names.ImageBuilder } -// 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) (*imagebuilder_sdkv1.Imagebuilder, error) { - sess := config["session"].(*session_sdkv1.Session) - - return imagebuilder_sdkv1.New(sess.Copy(&aws_sdkv1.Config{Endpoint: aws_sdkv1.String(config["endpoint"].(string))})), nil -} - // NewClient returns a new AWS SDK for Go v2 client for this service package's AWS API. func (p *servicePackage) NewClient(ctx context.Context, config map[string]any) (*imagebuilder_sdkv2.Client, error) { cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) diff --git a/names/data/names_data.csv b/names/data/names_data.csv index d883f09300d..5c9f08eb42b 100644 --- a/names/data/names_data.csv +++ b/names/data/names_data.csv @@ -130,7 +130,7 @@ dynamodbstreams,dynamodbstreams,dynamodbstreams,dynamodbstreams,,dynamodbstreams ,,,,,ec2ebs,ec2,,EC2EBS,,,,,aws_(ebs_|volume_attach|snapshot_create),aws_ec2ebs_,ebs_,ebs_;volume_attachment;snapshot_,EBS (EC2),Amazon,x,,,x,,,,,,Part of EC2 ebs,ebs,ebs,ebs,,ebs,,,EBS,EBS,,1,,,aws_ebs_,,changewhenimplemented,EBS (Elastic Block Store),Amazon,,x,,,,,EBS,,, ec2,ec2,ec2,ec2,,ec2,ec2,,EC2,EC2,,1,2,aws_(ami|availability_zone|ec2_(availability|capacity|fleet|host|instance|public_ipv4_pool|serial|spot|tag)|eip|instance|key_pair|launch_template|placement_group|spot),aws_ec2_,ec2_,ami;availability_zone;ec2_availability_;ec2_capacity_;ec2_fleet;ec2_host;ec2_image_;ec2_instance_;ec2_public_ipv4_pool;ec2_serial_;ec2_spot_;ec2_tag;eip;instance;key_pair;launch_template;placement_group;spot_,EC2 (Elastic Compute Cloud),Amazon,,,,,,,EC2,DescribeVpcs,, -imagebuilder,imagebuilder,imagebuilder,imagebuilder,,imagebuilder,,,ImageBuilder,Imagebuilder,,1,2,,aws_imagebuilder_,,imagebuilder_,EC2 Image Builder,Amazon,,,,,,,imagebuilder,ListImages,, +imagebuilder,imagebuilder,imagebuilder,imagebuilder,,imagebuilder,,,ImageBuilder,Imagebuilder,,,2,,aws_imagebuilder_,,imagebuilder_,EC2 Image Builder,Amazon,,,,,,,imagebuilder,ListImages,, ec2-instance-connect,ec2instanceconnect,ec2instanceconnect,ec2instanceconnect,,ec2instanceconnect,,,EC2InstanceConnect,EC2InstanceConnect,,1,,,aws_ec2instanceconnect_,,ec2instanceconnect_,EC2 Instance Connect,AWS,,x,,,,,EC2 Instance Connect,,, ecr,ecr,ecr,ecr,,ecr,,,ECR,ECR,,1,2,,aws_ecr_,,ecr_,ECR (Elastic Container Registry),Amazon,,,,,,,ECR,DescribeRepositories,, ecr-public,ecrpublic,ecrpublic,ecrpublic,,ecrpublic,,,ECRPublic,ECRPublic,,1,,,aws_ecrpublic_,,ecrpublic_,ECR Public,Amazon,,,,,,,ECR PUBLIC,DescribeRepositories,, diff --git a/names/names.go b/names/names.go index 4868b815590..23c781db797 100644 --- a/names/names.go +++ b/names/names.go @@ -48,6 +48,8 @@ const ( EvidentlyEndpointID = "evidently" IdentityStoreEndpointID = "identitystore" Inspector2EndpointID = "inspector2" + ImageBuilderEndpointID = "imagebuilder" + InternetMonitorEndpointID = "internetmonitor" IVSChatEndpointID = "ivschat" KendraEndpointID = "kendra" LexV2ModelsEndpointID = "models-v2-lex" From ac649f78086486b097f8920e5d8abf3476672091 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Thu, 22 Feb 2024 21:49:23 +0100 Subject: [PATCH 011/112] chore: begin v2 migration of imagebuilder --- .../imagebuilder/component_data_source.go | 16 ++++----- internal/service/imagebuilder/generate.go | 2 +- .../service_endpoints_gen_test.go | 1 - internal/service/imagebuilder/tags_gen.go | 34 +++++++++---------- 4 files changed, 25 insertions(+), 28 deletions(-) diff --git a/internal/service/imagebuilder/component_data_source.go b/internal/service/imagebuilder/component_data_source.go index 4ecf3bfd050..07589774049 100644 --- a/internal/service/imagebuilder/component_data_source.go +++ b/internal/service/imagebuilder/component_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -83,7 +83,7 @@ func DataSourceComponent() *schema.Resource { func dataSourceComponentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &imagebuilder.GetComponentInput{} @@ -92,7 +92,7 @@ func dataSourceComponentRead(ctx context.Context, d *schema.ResourceData, meta i input.ComponentBuildVersionArn = aws.String(v.(string)) } - output, err := conn.GetComponentWithContext(ctx, input) + output, err := conn.GetComponent(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "getting Image Builder Component: %s", err) @@ -104,7 +104,7 @@ func dataSourceComponentRead(ctx context.Context, d *schema.ResourceData, meta i component := output.Component - d.SetId(aws.StringValue(component.Arn)) + d.SetId(aws.ToString(component.Arn)) d.Set("arn", component.Arn) d.Set("change_description", component.ChangeDescription) @@ -116,11 +116,9 @@ func dataSourceComponentRead(ctx context.Context, d *schema.ResourceData, meta i d.Set("name", component.Name) d.Set("owner", component.Owner) d.Set("platform", component.Platform) - d.Set("supported_os_versions", aws.StringValueSlice(component.SupportedOsVersions)) + d.Set("supported_os_versions", component.SupportedOsVersions) - if err := d.Set("tags", KeyValueTags(ctx, component.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) - } + setTagsOut(ctx, component.Tags) d.Set("type", component.Type) d.Set("version", component.Version) diff --git a/internal/service/imagebuilder/generate.go b/internal/service/imagebuilder/generate.go index 2dcc8a60a9c..16f89fcdbab 100644 --- a/internal/service/imagebuilder/generate.go +++ b/internal/service/imagebuilder/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 -ServiceTagsMap -UpdateTags +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ListTags -KVTValues -ServiceTagsMap -UpdateTags //go:generate go run ../../generate/servicepackage/main.go // ONLY generate directives and package declaration! Do not add anything else to this file. diff --git a/internal/service/imagebuilder/service_endpoints_gen_test.go b/internal/service/imagebuilder/service_endpoints_gen_test.go index 0e25bc29817..a9497ea4ce0 100644 --- a/internal/service/imagebuilder/service_endpoints_gen_test.go +++ b/internal/service/imagebuilder/service_endpoints_gen_test.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "maps" - "net/url" "os" "path/filepath" "reflect" diff --git a/internal/service/imagebuilder/tags_gen.go b/internal/service/imagebuilder/tags_gen.go index 9c11e5da020..17b52ef00d8 100644 --- a/internal/service/imagebuilder/tags_gen.go +++ b/internal/service/imagebuilder/tags_gen.go @@ -5,9 +5,9 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "github.com/aws/aws-sdk-go/service/imagebuilder/imagebuilderiface" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" @@ -19,12 +19,12 @@ import ( // listTags lists imagebuilder 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 imagebuilderiface.ImagebuilderAPI, identifier string) (tftags.KeyValueTags, error) { +func listTags(ctx context.Context, conn *imagebuilder.Client, identifier string, optFns ...func(*imagebuilder.Options)) (tftags.KeyValueTags, error) { input := &imagebuilder.ListTagsForResourceInput{ ResourceArn: aws.String(identifier), } - output, err := conn.ListTagsForResourceWithContext(ctx, input) + output, err := conn.ListTagsForResource(ctx, input, optFns...) if err != nil { return tftags.New(ctx, nil), err @@ -36,7 +36,7 @@ func listTags(ctx context.Context, conn imagebuilderiface.ImagebuilderAPI, ident // ListTags lists imagebuilder 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).ImageBuilderConn(ctx), identifier) + tags, err := listTags(ctx, meta.(*conns.AWSClient).ImageBuilderClient(ctx), identifier) if err != nil { return err @@ -49,21 +49,21 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri return nil } -// map[string]*string handling +// map[string]string handling // Tags returns imagebuilder 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 imagebuilder 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 imagebuilder 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,7 +74,7 @@ func getTagsIn(ctx context.Context) map[string]*string { } // setTagsOut sets imagebuilder 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)) } @@ -83,7 +83,7 @@ func setTagsOut(ctx context.Context, tags map[string]*string) { // updateTags updates imagebuilder 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 imagebuilderiface.ImagebuilderAPI, identifier string, oldTagsMap, newTagsMap any) error { +func updateTags(ctx context.Context, conn *imagebuilder.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*imagebuilder.Options)) error { oldTags := tftags.New(ctx, oldTagsMap) newTags := tftags.New(ctx, newTagsMap) @@ -94,10 +94,10 @@ func updateTags(ctx context.Context, conn imagebuilderiface.ImagebuilderAPI, ide if len(removedTags) > 0 { input := &imagebuilder.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) @@ -112,7 +112,7 @@ func updateTags(ctx context.Context, conn imagebuilderiface.ImagebuilderAPI, ide 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) @@ -125,5 +125,5 @@ func updateTags(ctx context.Context, conn imagebuilderiface.ImagebuilderAPI, ide // UpdateTags updates imagebuilder 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).ImageBuilderConn(ctx), identifier, oldTags, newTags) + return updateTags(ctx, meta.(*conns.AWSClient).ImageBuilderClient(ctx), identifier, oldTags, newTags) } From f4cae4f87449f8d7ed6850959c2f09498c04212b Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Wed, 28 Feb 2024 13:45:14 +0100 Subject: [PATCH 012/112] chore: go mod tidy --- go.mod | 1 + go.sum | 2 ++ 2 files changed, 3 insertions(+) diff --git a/go.mod b/go.mod index 73c8c285362..31504355168 100644 --- a/go.mod +++ b/go.mod @@ -73,6 +73,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/groundstation v1.26.1 github.com/aws/aws-sdk-go-v2/service/healthlake v1.23.1 github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.1 + github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1 github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.1 github.com/aws/aws-sdk-go-v2/service/internetmonitor v1.12.1 github.com/aws/aws-sdk-go-v2/service/ivschat v1.12.1 diff --git a/go.sum b/go.sum index 293fffe4323..a6cc00756ab 100644 --- a/go.sum +++ b/go.sum @@ -170,6 +170,8 @@ github.com/aws/aws-sdk-go-v2/service/iam v1.30.1 h1:sCLZjJpGNMeyhyudAhipabxqwZpP github.com/aws/aws-sdk-go-v2/service/iam v1.30.1/go.mod h1:vc5DmJnsyyX6UpZwIKT2y1hEhzHoGDjONKhDcDwA49g= github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.1 h1:cMpbBT+CTvA/1OqnthdTpaXuXWFOBalT5RdLhtoeDeE= github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.1/go.mod h1:N5oCfOlt4oKVFU/HcVYBK3dUn6mxPgSXk5ev87mvfrM= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1 h1:5kP0+cOT2ApEUKUMM+zIP/fZpdmKeQa4Jl5iF8eHI9c= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1/go.mod h1:JUoAL2dg3oOHOv7/HB6r1z65cn9Fx34hGcMa0C4JjDc= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.1 h1:IZBvoT4DceXymN3gd5QfqiskD9WZ511ECL8yyByFtiA= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.1/go.mod h1:auZ223/ID3dhv7XU8NbSmOXBDd4acNJ427m/2NN/0Vg= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.1 h1:EyBZibRTVAs6ECHZOw5/wlylS9OcTzwyjeQMudmREjE= From 49c406312ea11c29237d709934d225ffa74a6a04 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Thu, 29 Feb 2024 23:01:42 +0100 Subject: [PATCH 013/112] chore: migrating to aws-sdk-v2 go --- internal/service/imagebuilder/component.go | 41 +++-- .../imagebuilder/component_data_source.go | 1 - .../service/imagebuilder/component_test.go | 23 +-- .../imagebuilder/components_data_source.go | 26 +-- .../service/imagebuilder/container_recipe.go | 47 ++--- .../container_recipe_data_source.go | 14 +- .../imagebuilder/container_recipe_test.go | 21 +-- .../container_recipes_data_source.go | 25 +-- .../distribution_configuration.go | 170 +++++++++--------- .../distribution_configuration_data_source.go | 10 +- .../distribution_configuration_test.go | 17 +- ...distribution_configurations_data_source.go | 15 +- internal/service/imagebuilder/image.go | 50 +++--- .../service/imagebuilder/image_data_source.go | 10 +- .../imagebuilder/image_data_source_test.go | 4 +- .../service/imagebuilder/image_pipeline.go | 97 +++++----- .../image_pipeline_data_source.go | 10 +- .../imagebuilder/image_pipeline_test.go | 37 ++-- .../image_pipelines_data_source.go | 15 +- internal/service/imagebuilder/image_recipe.go | 123 ++++++------- .../imagebuilder/image_recipe_data_source.go | 14 +- .../service/imagebuilder/image_recipe_test.go | 21 +-- .../imagebuilder/image_recipes_data_source.go | 25 +-- internal/service/imagebuilder/image_test.go | 19 +- .../infrastructure_configuration.go | 78 ++++---- ...nfrastructure_configuration_data_source.go | 14 +- .../infrastructure_configuration_test.go | 17 +- ...frastructure_configurations_data_source.go | 15 +- .../service/imagebuilder/lifecycle_policy.go | 32 ++-- internal/service/imagebuilder/status.go | 19 +- internal/service/imagebuilder/sweep.go | 54 +++--- internal/service/imagebuilder/wait.go | 21 +-- internal/service/imagebuilder/workflow.go | 35 ++-- .../service/imagebuilder/workflow_test.go | 19 +- 34 files changed, 588 insertions(+), 551 deletions(-) diff --git a/internal/service/imagebuilder/component.go b/internal/service/imagebuilder/component.go index 1ca488a41cf..90989a3aa45 100644 --- a/internal/service/imagebuilder/component.go +++ b/internal/service/imagebuilder/component.go @@ -7,14 +7,17 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -84,10 +87,10 @@ func ResourceComponent() *schema.Resource { Computed: true, }, "platform": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(imagebuilder.Platform_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.Platform](), }, "skip_destroy": { Type: schema.TypeBool, @@ -131,7 +134,7 @@ func ResourceComponent() *schema.Resource { func resourceComponentCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateComponentInput{ ClientToken: aws.String(id.UniqueId()), @@ -159,11 +162,11 @@ func resourceComponentCreate(ctx context.Context, d *schema.ResourceData, meta i } if v, ok := d.GetOk("platform"); ok { - input.Platform = aws.String(v.(string)) + input.Platform = awstypes.Platform(v.(string)) } if v, ok := d.GetOk("supported_os_versions"); ok && v.(*schema.Set).Len() > 0 { - input.SupportedOsVersions = flex.ExpandStringSet(v.(*schema.Set)) + input.SupportedOsVersions = flex.ExpandToStringSet(v.(*schema.Set)) } if v, ok := d.GetOk("uri"); ok { @@ -174,7 +177,7 @@ func resourceComponentCreate(ctx context.Context, d *schema.ResourceData, meta i input.SemanticVersion = aws.String(v.(string)) } - output, err := conn.CreateComponentWithContext(ctx, input) + output, err := conn.CreateComponent(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Component: %s", err) @@ -184,22 +187,22 @@ func resourceComponentCreate(ctx context.Context, d *schema.ResourceData, meta i return sdkdiag.AppendErrorf(diags, "creating Image Builder Component: empty result") } - d.SetId(aws.StringValue(output.ComponentBuildVersionArn)) + d.SetId(aws.ToString(output.ComponentBuildVersionArn)) return append(diags, resourceComponentRead(ctx, d, meta)...) } func resourceComponentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetComponentInput{ ComponentBuildVersionArn: aws.String(d.Id()), } - output, err := conn.GetComponentWithContext(ctx, input) + output, err := conn.GetComponent(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Component (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -225,7 +228,7 @@ func resourceComponentRead(ctx context.Context, d *schema.ResourceData, meta int d.Set("name", component.Name) d.Set("owner", component.Owner) d.Set("platform", component.Platform) - d.Set("supported_os_versions", aws.StringValueSlice(component.SupportedOsVersions)) + d.Set("supported_os_versions", component.SupportedOsVersions) setTagsOut(ctx, component.Tags) @@ -251,15 +254,15 @@ func resourceComponentDelete(ctx context.Context, d *schema.ResourceData, meta i return diags } - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteComponentInput{ ComponentBuildVersionArn: aws.String(d.Id()), } - _, err := conn.DeleteComponentWithContext(ctx, input) + _, err := conn.DeleteComponent(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } diff --git a/internal/service/imagebuilder/component_data_source.go b/internal/service/imagebuilder/component_data_source.go index 07589774049..54ec8754718 100644 --- a/internal/service/imagebuilder/component_data_source.go +++ b/internal/service/imagebuilder/component_data_source.go @@ -84,7 +84,6 @@ func DataSourceComponent() *schema.Resource { func dataSourceComponentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &imagebuilder.GetComponentInput{} diff --git a/internal/service/imagebuilder/component_test.go b/internal/service/imagebuilder/component_test.go index 77d5641c840..bf2f4ec566c 100644 --- a/internal/service/imagebuilder/component_test.go +++ b/internal/service/imagebuilder/component_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -45,10 +46,10 @@ func TestAccImageBuilderComponent_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner"), - resource.TestCheckResourceAttr(resourceName, "platform", imagebuilder.PlatformLinux), + resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "supported_os_versions.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "type", imagebuilder.ComponentTypeBuild), + resource.TestCheckResourceAttr(resourceName, "type", string(types.ComponentTypeBuild)), resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), ), }, @@ -185,7 +186,7 @@ func TestAccImageBuilderComponent_Platform_windows(t *testing.T) { Config: testAccComponentConfig_platformWindows(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComponentExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "platform", imagebuilder.PlatformWindows), + resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformWindows)), ), }, { @@ -301,7 +302,7 @@ func TestAccImageBuilderComponent_uri(t *testing.T) { func testAccCheckComponentDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_component" { @@ -312,9 +313,9 @@ func testAccCheckComponentDestroy(ctx context.Context) resource.TestCheckFunc { ComponentBuildVersionArn: aws.String(rs.Primary.ID), } - output, err := conn.GetComponentWithContext(ctx, input) + output, err := conn.GetComponent(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -338,13 +339,13 @@ func testAccCheckComponentExists(ctx context.Context, resourceName string) resou return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetComponentInput{ ComponentBuildVersionArn: aws.String(rs.Primary.ID), } - _, err := conn.GetComponentWithContext(ctx, input) + _, err := conn.GetComponent(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Component (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/components_data_source.go b/internal/service/imagebuilder/components_data_source.go index c17f065e910..797efce2269 100644 --- a/internal/service/imagebuilder/components_data_source.go +++ b/internal/service/imagebuilder/components_data_source.go @@ -6,14 +6,16 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "sigs.k8s.io/kustomize/api/types" ) // @SDKDataSource("aws_imagebuilder_components", name="Components") @@ -33,9 +35,9 @@ func DataSourceComponents() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "owner": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice(imagebuilder.Ownership_Values(), false), + Type: schema.TypeString, + Optional: true, + ValidateDiagFunc: enum.Validate[awstypes.Ownership](), }, }, } @@ -43,21 +45,21 @@ func DataSourceComponents() *schema.Resource { func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.ListComponentsInput{} if v, ok := d.GetOk("owner"); ok { - input.Owner = aws.String(v.(string)) + input.Owner = awstypes.Ownership(v.(string)) } if v, ok := d.GetOk("filter"); ok { input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*imagebuilder.ComponentVersion + var results []*types.ComponentVersion - err := conn.ListComponentsPagesWithContext(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { + err := conn.ListComponentsPages(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -80,8 +82,8 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta var arns, names []string for _, r := range results { - arns = append(arns, aws.StringValue(r.Arn)) - names = append(names, aws.StringValue(r.Name)) + arns = append(arns, aws.ToString(r.Arn)) + names = append(names, aws.ToString(r.Name)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/imagebuilder/container_recipe.go b/internal/service/imagebuilder/container_recipe.go index b459bf6b1ed..6c4c2a88262 100644 --- a/internal/service/imagebuilder/container_recipe.go +++ b/internal/service/imagebuilder/container_recipe.go @@ -8,14 +8,17 @@ import ( "log" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "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/types/nullable" @@ -179,10 +182,10 @@ func ResourceContainerRecipe() *schema.Resource { ValidateFunc: validation.IntBetween(1, 16000), }, "volume_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(imagebuilder.EbsVolumeType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.EbsVolumeType](), }, }, }, @@ -285,7 +288,7 @@ func ResourceContainerRecipe() *schema.Resource { func resourceContainerRecipeCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateContainerRecipeInput{ ClientToken: aws.String(id.UniqueId()), @@ -297,7 +300,7 @@ func resourceContainerRecipeCreate(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("container_type"); ok { - input.ContainerType = aws.String(v.(string)) + input.ContainerType = awstypes.ContainerType(v.(string)) } if v, ok := d.GetOk("description"); ok { @@ -329,7 +332,7 @@ func resourceContainerRecipeCreate(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("platform_override"); ok { - input.PlatformOverride = aws.String(v.(string)) + input.PlatformOverride = awstypes.Platform(v.(string)) } if v, ok := d.GetOk("target_repository"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { @@ -344,7 +347,7 @@ func resourceContainerRecipeCreate(ctx context.Context, d *schema.ResourceData, input.WorkingDirectory = aws.String(v.(string)) } - output, err := conn.CreateContainerRecipeWithContext(ctx, input) + output, err := conn.CreateContainerRecipe(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Container Recipe: %s", err) @@ -354,22 +357,22 @@ func resourceContainerRecipeCreate(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "creating Image Builder Container Recipe: empty response") } - d.SetId(aws.StringValue(output.ContainerRecipeArn)) + d.SetId(aws.ToString(output.ContainerRecipeArn)) return append(diags, resourceContainerRecipeRead(ctx, d, meta)...) } func resourceContainerRecipeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetContainerRecipeInput{ ContainerRecipeArn: aws.String(d.Id()), } - output, err := conn.GetContainerRecipeWithContext(ctx, input) + output, err := conn.GetContainerRecipe(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Container Recipe (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -424,15 +427,15 @@ func resourceContainerRecipeUpdate(ctx context.Context, d *schema.ResourceData, func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteContainerRecipeInput{ ContainerRecipeArn: aws.String(d.Id()), } - _, err := conn.DeleteContainerRecipeWithContext(ctx, input) + _, err := conn.DeleteContainerRecipe(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } @@ -443,12 +446,12 @@ func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, return diags } -func expandInstanceConfiguration(tfMap map[string]interface{}) *imagebuilder.InstanceConfiguration { +func expandInstanceConfiguration(tfMap map[string]interface{}) *awstypes.InstanceConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.InstanceConfiguration{} + apiObject := &awstypes.InstanceConfiguration{} if v, ok := tfMap["block_device_mapping"].(*schema.Set); ok && v.Len() > 0 { apiObject.BlockDeviceMappings = expandInstanceBlockDeviceMappings(v.List()) @@ -461,7 +464,7 @@ func expandInstanceConfiguration(tfMap map[string]interface{}) *imagebuilder.Ins return apiObject } -func flattenInstanceConfiguration(apiObject *imagebuilder.InstanceConfiguration) map[string]interface{} { +func flattenInstanceConfiguration(apiObject *awstypes.InstanceConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -473,7 +476,7 @@ func flattenInstanceConfiguration(apiObject *imagebuilder.InstanceConfiguration) } if v := apiObject.Image; v != nil { - tfMap["image"] = aws.StringValue(v) + tfMap["image"] = aws.ToString(v) } return tfMap diff --git a/internal/service/imagebuilder/container_recipe_data_source.go b/internal/service/imagebuilder/container_recipe_data_source.go index 1b57940251a..61eb8f08995 100644 --- a/internal/service/imagebuilder/container_recipe_data_source.go +++ b/internal/service/imagebuilder/container_recipe_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -197,7 +197,7 @@ func DataSourceContainerRecipe() *schema.Resource { func dataSourceContainerRecipeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &imagebuilder.GetContainerRecipeInput{} @@ -206,19 +206,19 @@ func dataSourceContainerRecipeRead(ctx context.Context, d *schema.ResourceData, input.ContainerRecipeArn = aws.String(v.(string)) } - output, err := conn.GetContainerRecipeWithContext(ctx, input) + output, err := conn.GetContainerRecipe(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): %s", aws.StringValue(input.ContainerRecipeArn), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): %s", aws.ToString(input.ContainerRecipeArn), err) } if output == nil || output.ContainerRecipe == nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): empty response", aws.StringValue(input.ContainerRecipeArn)) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): empty response", aws.ToString(input.ContainerRecipeArn)) } containerRecipe := output.ContainerRecipe - d.SetId(aws.StringValue(containerRecipe.Arn)) + d.SetId(aws.ToString(containerRecipe.Arn)) d.Set("arn", containerRecipe.Arn) d.Set("component", flattenComponentConfigurations(containerRecipe.Components)) d.Set("container_type", containerRecipe.ContainerType) diff --git a/internal/service/imagebuilder/container_recipe_test.go b/internal/service/imagebuilder/container_recipe_test.go index b207673f1ef..8679d625a2b 100644 --- a/internal/service/imagebuilder/container_recipe_test.go +++ b/internal/service/imagebuilder/container_recipe_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -50,7 +51,7 @@ func TestAccImageBuilderContainerRecipe_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner"), acctest.CheckResourceAttrRegionalARNAccountID(resourceName, "parent_image", "imagebuilder", "aws", "image/amazon-linux-x86-2/x.x.x"), - resource.TestCheckResourceAttr(resourceName, "platform", imagebuilder.PlatformLinux), + resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttr(resourceName, "target_repository.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "target_repository.0.repository_name", "aws_ecr_repository.test", "name"), @@ -466,7 +467,7 @@ func TestAccImageBuilderContainerRecipe_InstanceConfiguration_BlockDeviceMapping resource.TestCheckResourceAttr(resourceName, "instance_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "instance_configuration.0.block_device_mapping.#", "1"), resource.TestCheckResourceAttr(resourceName, "instance_configuration.0.block_device_mapping.0.ebs.#", "1"), - resource.TestCheckResourceAttr(resourceName, "instance_configuration.0.block_device_mapping.0.ebs.0.volume_type", imagebuilder.EbsVolumeTypeGp2), + resource.TestCheckResourceAttr(resourceName, "instance_configuration.0.block_device_mapping.0.ebs.0.volume_type", string(awstypes.EbsVolumeTypeGp2)), ), }, { @@ -696,7 +697,7 @@ func TestAccImageBuilderContainerRecipe_platformOverride(t *testing.T) { func testAccCheckContainerRecipeDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_container_recipe" { @@ -707,9 +708,9 @@ func testAccCheckContainerRecipeDestroy(ctx context.Context) resource.TestCheckF ContainerRecipeArn: aws.String(rs.Primary.ID), } - output, err := conn.GetContainerRecipeWithContext(ctx, input) + output, err := conn.GetContainerRecipe(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { continue } @@ -733,13 +734,13 @@ func testAccCheckContainerRecipeExists(ctx context.Context, resourceName string) return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetContainerRecipeInput{ ContainerRecipeArn: aws.String(rs.Primary.ID), } - _, err := conn.GetContainerRecipeWithContext(ctx, input) + _, err := conn.GetContainerRecipe(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Container Recipe (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/container_recipes_data_source.go b/internal/service/imagebuilder/container_recipes_data_source.go index cb018f640e9..c73e583b758 100644 --- a/internal/service/imagebuilder/container_recipes_data_source.go +++ b/internal/service/imagebuilder/container_recipes_data_source.go @@ -6,12 +6,13 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" ) @@ -33,9 +34,9 @@ func DataSourceContainerRecipes() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "owner": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice(imagebuilder.Ownership_Values(), false), + Type: schema.TypeString, + Optional: true, + ValidateDiagFunc: enum.Validate[awstypes.Ownership](), }, }, } @@ -43,21 +44,21 @@ func DataSourceContainerRecipes() *schema.Resource { func dataSourceContainerRecipesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.ListContainerRecipesInput{} if v, ok := d.GetOk("owner"); ok { - input.Owner = aws.String(v.(string)) + input.Owner = awstypes.Ownership(v.(string)) } if v, ok := d.GetOk("filter"); ok { input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*imagebuilder.ContainerRecipeSummary + var results []*awstypes.ContainerRecipeSummary - err := conn.ListContainerRecipesPagesWithContext(ctx, input, func(page *imagebuilder.ListContainerRecipesOutput, lastPage bool) bool { + err := conn.ListContainerRecipesPages(ctx, input, func(page *imagebuilder.ListContainerRecipesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -80,8 +81,8 @@ func dataSourceContainerRecipesRead(ctx context.Context, d *schema.ResourceData, var arns, names []string for _, r := range results { - arns = append(arns, aws.StringValue(r.Arn)) - names = append(names, aws.StringValue(r.Name)) + arns = append(arns, aws.ToString(r.Arn)) + names = append(names, aws.ToString(r.Name)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 58d1014af05..5616ea320ab 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -8,14 +8,16 @@ import ( "log" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -294,7 +296,7 @@ func ResourceDistributionConfiguration() *schema.Resource { func resourceDistributionConfigurationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateDistributionConfigurationInput{ ClientToken: aws.String(id.UniqueId()), @@ -313,7 +315,7 @@ func resourceDistributionConfigurationCreate(ctx context.Context, d *schema.Reso input.Name = aws.String(v.(string)) } - output, err := conn.CreateDistributionConfigurationWithContext(ctx, input) + output, err := conn.CreateDistributionConfiguration(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Distribution Configuration: %s", err) @@ -323,22 +325,22 @@ func resourceDistributionConfigurationCreate(ctx context.Context, d *schema.Reso return sdkdiag.AppendErrorf(diags, "creating Image Builder Distribution Configuration: empty response") } - d.SetId(aws.StringValue(output.DistributionConfigurationArn)) + d.SetId(aws.ToString(output.DistributionConfigurationArn)) return append(diags, resourceDistributionConfigurationRead(ctx, d, meta)...) } func resourceDistributionConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetDistributionConfigurationInput{ DistributionConfigurationArn: aws.String(d.Id()), } - output, err := conn.GetDistributionConfigurationWithContext(ctx, input) + output, err := conn.GetDistributionConfiguration(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Distribution Configuration (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -368,7 +370,7 @@ func resourceDistributionConfigurationRead(ctx context.Context, d *schema.Resour func resourceDistributionConfigurationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) if d.HasChanges("description", "distribution") { input := &imagebuilder.UpdateDistributionConfigurationInput{ @@ -384,7 +386,7 @@ func resourceDistributionConfigurationUpdate(ctx context.Context, d *schema.Reso } log.Printf("[DEBUG] UpdateDistributionConfiguration: %#v", input) - _, err := conn.UpdateDistributionConfigurationWithContext(ctx, input) + _, err := conn.UpdateDistributionConfiguration(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Image Builder Distribution Configuration (%s): %s", d.Id(), err) @@ -396,15 +398,15 @@ func resourceDistributionConfigurationUpdate(ctx context.Context, d *schema.Reso func resourceDistributionConfigurationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteDistributionConfigurationInput{ DistributionConfigurationArn: aws.String(d.Id()), } - _, err := conn.DeleteDistributionConfigurationWithContext(ctx, input) + _, err := conn.DeleteDistributionConfiguration(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } @@ -415,15 +417,15 @@ func resourceDistributionConfigurationDelete(ctx context.Context, d *schema.Reso return diags } -func expandAMIDistributionConfiguration(tfMap map[string]interface{}) *imagebuilder.AmiDistributionConfiguration { +func expandAMIDistributionConfiguration(tfMap map[string]interface{}) *awstypes.AmiDistributionConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.AmiDistributionConfiguration{} + apiObject := &awstypes.AmiDistributionConfiguration{} if v, ok := tfMap["ami_tags"].(map[string]interface{}); ok && len(v) > 0 { - apiObject.AmiTags = flex.ExpandStringMap(v) + apiObject.AmiTags = flex.ExpandToStringMap(v) } if v, ok := tfMap["description"].(string); ok && v != "" { @@ -443,21 +445,21 @@ func expandAMIDistributionConfiguration(tfMap map[string]interface{}) *imagebuil } if v, ok := tfMap["target_account_ids"].(*schema.Set); ok && v.Len() > 0 { - apiObject.TargetAccountIds = flex.ExpandStringSet(v) + apiObject.TargetAccountIds = flex.ExpandToStringSet(v) } return apiObject } -func expandContainerDistributionConfiguration(tfMap map[string]interface{}) *imagebuilder.ContainerDistributionConfiguration { +func expandContainerDistributionConfiguration(tfMap map[string]interface{}) *awstypes.ContainerDistributionConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.ContainerDistributionConfiguration{} + apiObject := &awstypes.ContainerDistributionConfiguration{} if v, ok := tfMap["container_tags"].(*schema.Set); ok && v.Len() > 0 { - apiObject.ContainerTags = flex.ExpandStringSet(v) + apiObject.ContainerTags = flex.ExpandToStringSet(v) } if v, ok := tfMap["description"].(string); ok && v != "" { @@ -471,12 +473,12 @@ func expandContainerDistributionConfiguration(tfMap map[string]interface{}) *ima return apiObject } -func expandLaunchTemplateConfigurations(tfList []interface{}) []*imagebuilder.LaunchTemplateConfiguration { +func expandLaunchTemplateConfigurations(tfList []interface{}) []*awstypes.LaunchTemplateConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*imagebuilder.LaunchTemplateConfiguration + var apiObjects []*awstypes.LaunchTemplateConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -497,12 +499,12 @@ func expandLaunchTemplateConfigurations(tfList []interface{}) []*imagebuilder.La return apiObjects } -func expandDistribution(tfMap map[string]interface{}) *imagebuilder.Distribution { +func expandDistribution(tfMap map[string]interface{}) *awstypes.Distribution { if tfMap == nil { return nil } - apiObject := &imagebuilder.Distribution{} + apiObject := &awstypes.Distribution{} if v, ok := tfMap["ami_distribution_configuration"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.AmiDistributionConfiguration = expandAMIDistributionConfiguration(v[0].(map[string]interface{})) @@ -521,7 +523,7 @@ func expandDistribution(tfMap map[string]interface{}) *imagebuilder.Distribution } if v, ok := tfMap["license_configuration_arns"].(*schema.Set); ok && v.Len() > 0 { - apiObject.LicenseConfigurationArns = flex.ExpandStringSet(v) + apiObject.LicenseConfigurationArns = flex.ExpandToStringSet(v) } if v, ok := tfMap["region"].(string); ok && v != "" { @@ -531,12 +533,12 @@ func expandDistribution(tfMap map[string]interface{}) *imagebuilder.Distribution return apiObject } -func expandDistributions(tfList []interface{}) []*imagebuilder.Distribution { +func expandDistributions(tfList []interface{}) []*awstypes.Distribution { if len(tfList) == 0 { return nil } - var apiObjects []*imagebuilder.Distribution + var apiObjects []*awstypes.Distribution for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -564,56 +566,56 @@ func expandDistributions(tfList []interface{}) []*imagebuilder.Distribution { return apiObjects } -func expandLaunchPermissionConfiguration(tfMap map[string]interface{}) *imagebuilder.LaunchPermissionConfiguration { +func expandLaunchPermissionConfiguration(tfMap map[string]interface{}) *awstypes.LaunchPermissionConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.LaunchPermissionConfiguration{} + apiObject := &awstypes.LaunchPermissionConfiguration{} if v, ok := tfMap["organization_arns"].(*schema.Set); ok && v.Len() > 0 { - apiObject.OrganizationArns = flex.ExpandStringSet(v) + apiObject.OrganizationArns = flex.ExpandToStringSet(v) } if v, ok := tfMap["organizational_unit_arns"].(*schema.Set); ok && v.Len() > 0 { - apiObject.OrganizationalUnitArns = flex.ExpandStringSet(v) + apiObject.OrganizationalUnitArns = flex.ExpandToStringSet(v) } if v, ok := tfMap["user_ids"].(*schema.Set); ok && v.Len() > 0 { - apiObject.UserIds = flex.ExpandStringSet(v) + apiObject.UserIds = flex.ExpandToStringSet(v) } if v, ok := tfMap["user_groups"].(*schema.Set); ok && v.Len() > 0 { - apiObject.UserGroups = flex.ExpandStringSet(v) + apiObject.UserGroups = flex.ExpandToStringSet(v) } return apiObject } -func expandTargetContainerRepository(tfMap map[string]interface{}) *imagebuilder.TargetContainerRepository { +func expandTargetContainerRepository(tfMap map[string]interface{}) *awstypes.TargetContainerRepository { if tfMap == nil { return nil } - apiObject := &imagebuilder.TargetContainerRepository{} + apiObject := &awstypes.TargetContainerRepository{} if v, ok := tfMap["repository_name"].(string); ok && v != "" { apiObject.RepositoryName = aws.String(v) } if v, ok := tfMap["service"].(string); ok && v != "" { - apiObject.Service = aws.String(v) + apiObject.Service = awstypes.ContainerRepositoryService(v) } return apiObject } -func expandFastLaunchConfigurations(tfList []interface{}) []*imagebuilder.FastLaunchConfiguration { +func expandFastLaunchConfigurations(tfList []interface{}) []*awstypes.FastLaunchConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*imagebuilder.FastLaunchConfiguration + var apiObjects []*awstypes.FastLaunchConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -634,12 +636,12 @@ func expandFastLaunchConfigurations(tfList []interface{}) []*imagebuilder.FastLa return apiObjects } -func expandFastLaunchConfiguration(tfMap map[string]interface{}) *imagebuilder.FastLaunchConfiguration { +func expandFastLaunchConfiguration(tfMap map[string]interface{}) *awstypes.FastLaunchConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.FastLaunchConfiguration{} + apiObject := &awstypes.FastLaunchConfiguration{} if v, ok := tfMap["account_id"].(string); ok && v != "" { apiObject.AccountId = aws.String(v) @@ -664,12 +666,12 @@ func expandFastLaunchConfiguration(tfMap map[string]interface{}) *imagebuilder.F return apiObject } -func expandFastLaunchLaunchTemplateSpecification(tfMap map[string]interface{}) *imagebuilder.FastLaunchLaunchTemplateSpecification { +func expandFastLaunchLaunchTemplateSpecification(tfMap map[string]interface{}) *awstypes.FastLaunchLaunchTemplateSpecification { if tfMap == nil { return nil } - apiObject := &imagebuilder.FastLaunchLaunchTemplateSpecification{} + apiObject := &awstypes.FastLaunchLaunchTemplateSpecification{} if v, ok := tfMap["launch_template_id"].(string); ok && v != "" { apiObject.LaunchTemplateId = aws.String(v) @@ -686,12 +688,12 @@ func expandFastLaunchLaunchTemplateSpecification(tfMap map[string]interface{}) * return apiObject } -func expandFastLaunchSnapshotConfiguration(tfMap map[string]interface{}) *imagebuilder.FastLaunchSnapshotConfiguration { +func expandFastLaunchSnapshotConfiguration(tfMap map[string]interface{}) *awstypes.FastLaunchSnapshotConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.FastLaunchSnapshotConfiguration{} + apiObject := &awstypes.FastLaunchSnapshotConfiguration{} if v, ok := tfMap["target_resource_count"].(int); ok && v != 0 { apiObject.TargetResourceCount = aws.Int64(int64(v)) @@ -700,12 +702,12 @@ func expandFastLaunchSnapshotConfiguration(tfMap map[string]interface{}) *imageb return apiObject } -func expandLaunchTemplateConfiguration(tfMap map[string]interface{}) *imagebuilder.LaunchTemplateConfiguration { +func expandLaunchTemplateConfiguration(tfMap map[string]interface{}) *awstypes.LaunchTemplateConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.LaunchTemplateConfiguration{} + apiObject := &awstypes.LaunchTemplateConfiguration{} if v, ok := tfMap["launch_template_id"].(string); ok && v != "" { apiObject.LaunchTemplateId = aws.String(v) @@ -722,7 +724,7 @@ func expandLaunchTemplateConfiguration(tfMap map[string]interface{}) *imagebuild return apiObject } -func flattenAMIDistributionConfiguration(apiObject *imagebuilder.AmiDistributionConfiguration) map[string]interface{} { +func flattenAMIDistributionConfiguration(apiObject *awstypes.AmiDistributionConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -730,15 +732,15 @@ func flattenAMIDistributionConfiguration(apiObject *imagebuilder.AmiDistribution tfMap := map[string]interface{}{} if v := apiObject.AmiTags; v != nil { - tfMap["ami_tags"] = aws.StringValueMap(v) + tfMap["ami_tags"] = aws.ToStringMap(v) } if v := apiObject.Description; v != nil { - tfMap["description"] = aws.StringValue(v) + tfMap["description"] = aws.ToString(v) } if v := apiObject.KmsKeyId; v != nil { - tfMap["kms_key_id"] = aws.StringValue(v) + tfMap["kms_key_id"] = aws.ToString(v) } if v := apiObject.LaunchPermission; v != nil { @@ -746,17 +748,17 @@ func flattenAMIDistributionConfiguration(apiObject *imagebuilder.AmiDistribution } if v := apiObject.Name; v != nil { - tfMap["name"] = aws.StringValue(v) + tfMap["name"] = aws.ToString(v) } if v := apiObject.TargetAccountIds; v != nil { - tfMap["target_account_ids"] = aws.StringValueSlice(v) + tfMap["target_account_ids"] = aws.ToStringSlice(v) } return tfMap } -func flattenContainerDistributionConfiguration(apiObject *imagebuilder.ContainerDistributionConfiguration) map[string]interface{} { +func flattenContainerDistributionConfiguration(apiObject *awstypes.ContainerDistributionConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -764,11 +766,11 @@ func flattenContainerDistributionConfiguration(apiObject *imagebuilder.Container tfMap := map[string]interface{}{} if v := apiObject.ContainerTags; v != nil { - tfMap["container_tags"] = aws.StringValueSlice(v) + tfMap["container_tags"] = aws.ToStringSlice(v) } if v := apiObject.Description; v != nil { - tfMap["description"] = aws.StringValue(v) + tfMap["description"] = aws.ToString(v) } if v := apiObject.TargetRepository; v != nil { @@ -778,7 +780,7 @@ func flattenContainerDistributionConfiguration(apiObject *imagebuilder.Container return tfMap } -func flattenLaunchTemplateConfigurations(apiObjects []*imagebuilder.LaunchTemplateConfiguration) []interface{} { +func flattenLaunchTemplateConfigurations(apiObjects []*awstypes.LaunchTemplateConfiguration) []interface{} { if apiObjects == nil { return nil } @@ -796,7 +798,7 @@ func flattenLaunchTemplateConfigurations(apiObjects []*imagebuilder.LaunchTempla return tfList } -func flattenDistribution(apiObject *imagebuilder.Distribution) map[string]interface{} { +func flattenDistribution(apiObject *awstypes.Distribution) map[string]interface{} { if apiObject == nil { return nil } @@ -820,17 +822,17 @@ func flattenDistribution(apiObject *imagebuilder.Distribution) map[string]interf } if v := apiObject.LicenseConfigurationArns; v != nil { - tfMap["license_configuration_arns"] = aws.StringValueSlice(v) + tfMap["license_configuration_arns"] = aws.ToStringSlice(v) } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.StringValue(v) + tfMap["region"] = aws.ToString(v) } return tfMap } -func flattenDistributions(apiObjects []*imagebuilder.Distribution) []interface{} { +func flattenDistributions(apiObjects []*awstypes.Distribution) []interface{} { if len(apiObjects) == 0 { return nil } @@ -848,7 +850,7 @@ func flattenDistributions(apiObjects []*imagebuilder.Distribution) []interface{} return tfList } -func flattenLaunchPermissionConfiguration(apiObject *imagebuilder.LaunchPermissionConfiguration) map[string]interface{} { +func flattenLaunchPermissionConfiguration(apiObject *awstypes.LaunchPermissionConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -856,25 +858,25 @@ func flattenLaunchPermissionConfiguration(apiObject *imagebuilder.LaunchPermissi tfMap := map[string]interface{}{} if v := apiObject.OrganizationArns; v != nil { - tfMap["organization_arns"] = aws.StringValueSlice(v) + tfMap["organization_arns"] = aws.ToStringSlice(v) } if v := apiObject.OrganizationalUnitArns; v != nil { - tfMap["organizational_unit_arns"] = aws.StringValueSlice(v) + tfMap["organizational_unit_arns"] = aws.ToStringSlice(v) } if v := apiObject.UserGroups; v != nil { - tfMap["user_groups"] = aws.StringValueSlice(v) + tfMap["user_groups"] = aws.ToStringSlice(v) } if v := apiObject.UserIds; v != nil { - tfMap["user_ids"] = aws.StringValueSlice(v) + tfMap["user_ids"] = aws.ToStringSlice(v) } return tfMap } -func flattenTargetContainerRepository(apiObject *imagebuilder.TargetContainerRepository) map[string]interface{} { +func flattenTargetContainerRepository(apiObject *awstypes.TargetContainerRepository) map[string]interface{} { if apiObject == nil { return nil } @@ -882,17 +884,17 @@ func flattenTargetContainerRepository(apiObject *imagebuilder.TargetContainerRep tfMap := map[string]interface{}{} if v := apiObject.RepositoryName; v != nil { - tfMap["repository_name"] = aws.StringValue(v) + tfMap["repository_name"] = aws.ToString(v) } if v := apiObject.Service; v != nil { - tfMap["service"] = aws.StringValue(v) + tfMap["service"] = aws.ToString(v) } return tfMap } -func flattenLaunchTemplateConfiguration(apiObject *imagebuilder.LaunchTemplateConfiguration) map[string]interface{} { +func flattenLaunchTemplateConfiguration(apiObject *awstypes.LaunchTemplateConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -900,21 +902,21 @@ func flattenLaunchTemplateConfiguration(apiObject *imagebuilder.LaunchTemplateCo tfMap := map[string]interface{}{} if v := apiObject.LaunchTemplateId; v != nil { - tfMap["launch_template_id"] = aws.StringValue(v) + tfMap["launch_template_id"] = aws.ToString(v) } if v := apiObject.SetDefaultVersion; v != nil { - tfMap["default"] = aws.BoolValue(v) + tfMap["default"] = aws.ToBool(v) } if v := apiObject.AccountId; v != nil { - tfMap["account_id"] = aws.StringValue(v) + tfMap["account_id"] = aws.ToString(v) } return tfMap } -func flattenFastLaunchConfigurations(apiObjects []*imagebuilder.FastLaunchConfiguration) []interface{} { +func flattenFastLaunchConfigurations(apiObjects []*awstypes.FastLaunchConfiguration) []interface{} { if apiObjects == nil { return nil } @@ -932,7 +934,7 @@ func flattenFastLaunchConfigurations(apiObjects []*imagebuilder.FastLaunchConfig return tfList } -func flattenFastLaunchConfiguration(apiObject *imagebuilder.FastLaunchConfiguration) map[string]interface{} { +func flattenFastLaunchConfiguration(apiObject *awstypes.FastLaunchConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -940,11 +942,11 @@ func flattenFastLaunchConfiguration(apiObject *imagebuilder.FastLaunchConfigurat tfMap := map[string]interface{}{} if v := apiObject.AccountId; v != nil { - tfMap["account_id"] = aws.StringValue(v) + tfMap["account_id"] = aws.ToString(v) } if v := apiObject.Enabled; v != nil { - tfMap["enabled"] = aws.BoolValue(v) + tfMap["enabled"] = aws.ToBool(v) } if v := apiObject.LaunchTemplate; v != nil { @@ -952,7 +954,7 @@ func flattenFastLaunchConfiguration(apiObject *imagebuilder.FastLaunchConfigurat } if v := apiObject.MaxParallelLaunches; v != nil { - tfMap["max_parallel_launches"] = aws.Int64Value(v) + tfMap["max_parallel_launches"] = aws.ToInt64(v) } if v := apiObject.SnapshotConfiguration; v != nil { @@ -962,7 +964,7 @@ func flattenFastLaunchConfiguration(apiObject *imagebuilder.FastLaunchConfigurat return tfMap } -func flattenFastLaunchLaunchTemplateSpecification(apiObject *imagebuilder.FastLaunchLaunchTemplateSpecification) map[string]interface{} { +func flattenFastLaunchLaunchTemplateSpecification(apiObject *awstypes.FastLaunchLaunchTemplateSpecification) map[string]interface{} { if apiObject == nil { return nil } @@ -970,21 +972,21 @@ func flattenFastLaunchLaunchTemplateSpecification(apiObject *imagebuilder.FastLa tfMap := map[string]interface{}{} if v := apiObject.LaunchTemplateId; v != nil { - tfMap["launch_template_id"] = aws.StringValue(v) + tfMap["launch_template_id"] = aws.ToString(v) } if v := apiObject.LaunchTemplateName; v != nil { - tfMap["launch_template_name"] = aws.StringValue(v) + tfMap["launch_template_name"] = aws.ToString(v) } if v := apiObject.LaunchTemplateVersion; v != nil { - tfMap["launch_template_version"] = aws.StringValue(v) + tfMap["launch_template_version"] = aws.ToString(v) } return tfMap } -func flattenFastLaunchSnapshotConfiguration(apiObject *imagebuilder.FastLaunchSnapshotConfiguration) map[string]interface{} { +func flattenFastLaunchSnapshotConfiguration(apiObject *awstypes.FastLaunchSnapshotConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -992,7 +994,7 @@ func flattenFastLaunchSnapshotConfiguration(apiObject *imagebuilder.FastLaunchSn tfMap := map[string]interface{}{} if v := apiObject.TargetResourceCount; v != nil { - tfMap["target_resource_count"] = aws.Int64Value(v) + tfMap["target_resource_count"] = aws.ToInt64(v) } return tfMap diff --git a/internal/service/imagebuilder/distribution_configuration_data_source.go b/internal/service/imagebuilder/distribution_configuration_data_source.go index 75a2f1f3b28..fac133a98b7 100644 --- a/internal/service/imagebuilder/distribution_configuration_data_source.go +++ b/internal/service/imagebuilder/distribution_configuration_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -240,7 +240,7 @@ func DataSourceDistributionConfiguration() *schema.Resource { func dataSourceDistributionConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &imagebuilder.GetDistributionConfigurationInput{} @@ -249,7 +249,7 @@ func dataSourceDistributionConfigurationRead(ctx context.Context, d *schema.Reso input.DistributionConfigurationArn = aws.String(v.(string)) } - output, err := conn.GetDistributionConfigurationWithContext(ctx, input) + output, err := conn.GetDistributionConfiguration(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "getting Image Builder Distribution Configuration (%s): %s", d.Id(), err) @@ -261,7 +261,7 @@ func dataSourceDistributionConfigurationRead(ctx context.Context, d *schema.Reso distributionConfiguration := output.DistributionConfiguration - d.SetId(aws.StringValue(distributionConfiguration.Arn)) + d.SetId(aws.ToString(distributionConfiguration.Arn)) d.Set("arn", distributionConfiguration.Arn) d.Set("date_created", distributionConfiguration.DateCreated) d.Set("date_updated", distributionConfiguration.DateUpdated) diff --git a/internal/service/imagebuilder/distribution_configuration_test.go b/internal/service/imagebuilder/distribution_configuration_test.go index f75dc514ce9..b87e98154bf 100644 --- a/internal/service/imagebuilder/distribution_configuration_test.go +++ b/internal/service/imagebuilder/distribution_configuration_test.go @@ -8,14 +8,15 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -914,7 +915,7 @@ func TestAccImageBuilderDistributionConfiguration_tags(t *testing.T) { func testAccCheckDistributionConfigurationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_distribution_configuration" { @@ -925,9 +926,9 @@ func testAccCheckDistributionConfigurationDestroy(ctx context.Context) resource. DistributionConfigurationArn: aws.String(rs.Primary.ID), } - output, err := conn.GetDistributionConfigurationWithContext(ctx, input) + output, err := conn.GetDistributionConfiguration(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -951,13 +952,13 @@ func testAccCheckDistributionConfigurationExists(ctx context.Context, resourceNa return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetDistributionConfigurationInput{ DistributionConfigurationArn: aws.String(rs.Primary.ID), } - _, err := conn.GetDistributionConfigurationWithContext(ctx, input) + _, err := conn.GetDistributionConfiguration(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Distribution Configuration (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/distribution_configurations_data_source.go b/internal/service/imagebuilder/distribution_configurations_data_source.go index 297b019d0d8..dd70a503893 100644 --- a/internal/service/imagebuilder/distribution_configurations_data_source.go +++ b/internal/service/imagebuilder/distribution_configurations_data_source.go @@ -6,8 +6,9 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -37,7 +38,7 @@ func DataSourceDistributionConfigurations() *schema.Resource { func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.ListDistributionConfigurationsInput{} @@ -45,9 +46,9 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*imagebuilder.DistributionConfigurationSummary + var results []*awstypes.DistributionConfigurationSummary - err := conn.ListDistributionConfigurationsPagesWithContext(ctx, input, func(page *imagebuilder.ListDistributionConfigurationsOutput, lastPage bool) bool { + err := conn.ListDistributionConfigurationsPages(ctx, input, func(page *imagebuilder.ListDistributionConfigurationsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -70,8 +71,8 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res var arns, names []string for _, r := range results { - arns = append(arns, aws.StringValue(r.Arn)) - names = append(names, aws.StringValue(r.Name)) + arns = append(arns, aws.ToString(r.Arn)) + names = append(names, aws.ToString(r.Name)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index 51a3d98b7e6..8f591ce06af 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -9,14 +9,16 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -220,7 +222,7 @@ func ResourceImage() *schema.Resource { func resourceImageCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateImageInput{ ClientToken: aws.String(id.UniqueId()), @@ -252,7 +254,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, meta inter input.InfrastructureConfigurationArn = aws.String(v.(string)) } - output, err := conn.CreateImageWithContext(ctx, input) + output, err := conn.CreateImage(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Image: %s", err) @@ -262,7 +264,7 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "creating Image Builder Image: empty response") } - d.SetId(aws.StringValue(output.ImageBuildVersionArn)) + d.SetId(aws.ToString(output.ImageBuildVersionArn)) if _, err := waitImageStatusAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Image Builder Image (%s) to become available: %s", d.Id(), err) @@ -273,15 +275,15 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, meta inter func resourceImageRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImageInput{ ImageBuildVersionArn: aws.String(d.Id()), } - output, err := conn.GetImageWithContext(ctx, input) + output, err := conn.GetImage(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Image (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -357,15 +359,15 @@ func resourceImageUpdate(ctx context.Context, d *schema.ResourceData, meta inter func resourceImageDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteImageInput{ ImageBuildVersionArn: aws.String(d.Id()), } - _, err := conn.DeleteImageWithContext(ctx, input) + _, err := conn.DeleteImage(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } @@ -376,7 +378,7 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, meta inter return diags } -func flattenOutputResources(apiObject *imagebuilder.OutputResources) map[string]interface{} { +func flattenOutputResources(apiObject *awstypes.OutputResources) map[string]interface{} { if apiObject == nil { return nil } @@ -394,7 +396,7 @@ func flattenOutputResources(apiObject *imagebuilder.OutputResources) map[string] return tfMap } -func flattenAMI(apiObject *imagebuilder.Ami) map[string]interface{} { +func flattenAMI(apiObject *awstypes.Ami) map[string]interface{} { if apiObject == nil { return nil } @@ -402,29 +404,29 @@ func flattenAMI(apiObject *imagebuilder.Ami) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.AccountId; v != nil { - tfMap["account_id"] = aws.StringValue(v) + tfMap["account_id"] = aws.ToString(v) } if v := apiObject.Description; v != nil { - tfMap["description"] = aws.StringValue(v) + tfMap["description"] = aws.ToString(v) } if v := apiObject.Image; v != nil { - tfMap["image"] = aws.StringValue(v) + tfMap["image"] = aws.ToString(v) } if v := apiObject.Name; v != nil { - tfMap["name"] = aws.StringValue(v) + tfMap["name"] = aws.ToString(v) } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.StringValue(v) + tfMap["region"] = aws.ToString(v) } return tfMap } -func flattenAMIs(apiObjects []*imagebuilder.Ami) []interface{} { +func flattenAMIs(apiObjects []*awstypes.Ami) []interface{} { if len(apiObjects) == 0 { return nil } @@ -442,7 +444,7 @@ func flattenAMIs(apiObjects []*imagebuilder.Ami) []interface{} { return tfList } -func flattenContainer(apiObject *imagebuilder.Container) map[string]interface{} { +func flattenContainer(apiObject *awstypes.Container) map[string]interface{} { if apiObject == nil { return nil } @@ -450,17 +452,17 @@ func flattenContainer(apiObject *imagebuilder.Container) map[string]interface{} tfMap := map[string]interface{}{} if v := apiObject.ImageUris; v != nil { - tfMap["image_uris"] = aws.StringValueSlice(v) + tfMap["image_uris"] = aws.ToStringSlice(v) } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.StringValue(v) + tfMap["region"] = aws.ToString(v) } return tfMap } -func flattenContainers(apiObjects []*imagebuilder.Container) []interface{} { +func flattenContainers(apiObjects []*awstypes.Container) []interface{} { if len(apiObjects) == 0 { return nil } diff --git a/internal/service/imagebuilder/image_data_source.go b/internal/service/imagebuilder/image_data_source.go index c9118fe1471..311c47138c8 100644 --- a/internal/service/imagebuilder/image_data_source.go +++ b/internal/service/imagebuilder/image_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -178,7 +178,7 @@ func DataSourceImage() *schema.Resource { func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImageInput{} @@ -186,7 +186,7 @@ func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, meta inter input.ImageBuildVersionArn = aws.String(v.(string)) } - output, err := conn.GetImageWithContext(ctx, input) + output, err := conn.GetImage(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "getting Image Builder Image: %s", err) @@ -198,7 +198,7 @@ func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, meta inter image := output.Image - d.SetId(aws.StringValue(image.Arn)) + d.SetId(aws.ToString(image.Arn)) // To prevent Terraform errors, only reset arn if not configured. // The configured ARN may contain x.x.x wildcards while the API returns diff --git a/internal/service/imagebuilder/image_data_source_test.go b/internal/service/imagebuilder/image_data_source_test.go index a5f7c6f63a9..60b4379e185 100644 --- a/internal/service/imagebuilder/image_data_source_test.go +++ b/internal/service/imagebuilder/image_data_source_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -40,7 +40,7 @@ func TestAccImageBuilderImageDataSource_ARN_aws(t *testing.T) { // nosemgrep:ci. resource.TestCheckResourceAttr(dataSourceName, "name", "Amazon Linux 2 x86"), resource.TestCheckResourceAttr(dataSourceName, "os_version", "Amazon Linux 2"), resource.TestCheckResourceAttr(dataSourceName, "output_resources.#", "1"), - resource.TestCheckResourceAttr(dataSourceName, "platform", imagebuilder.PlatformLinux), + resource.TestCheckResourceAttr(dataSourceName, "platform", string(awstypes.PlatformLinux)), resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), resource.TestMatchResourceAttr(dataSourceName, "version", regexache.MustCompile(`\d+\.\d+\.\d+/\d+`)), ), diff --git a/internal/service/imagebuilder/image_pipeline.go b/internal/service/imagebuilder/image_pipeline.go index ca1084d66e3..37092979fdc 100644 --- a/internal/service/imagebuilder/image_pipeline.go +++ b/internal/service/imagebuilder/image_pipeline.go @@ -8,14 +8,17 @@ import ( "log" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -164,10 +167,10 @@ func ResourceImagePipeline() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "pipeline_execution_start_condition": { - Type: schema.TypeString, - Optional: true, - Default: imagebuilder.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable, - ValidateFunc: validation.StringInSlice(imagebuilder.PipelineExecutionStartCondition_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: string(awstypes.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable), + ValidateDiagFunc: enum.Validate[awstypes.PipelineExecutionStartCondition](), }, "schedule_expression": { Type: schema.TypeString, @@ -186,10 +189,10 @@ func ResourceImagePipeline() *schema.Resource { }, }, "status": { - Type: schema.TypeString, - Optional: true, - Default: imagebuilder.PipelineStatusEnabled, - ValidateFunc: validation.StringInSlice(imagebuilder.PipelineStatus_Values(), false), + Type: schema.TypeString, + Optional: true, + Default: string(awstypes.PipelineStatusEnabled), + ValidateDiagFunc: enum.Validate[awstypes.PipelineStatus](), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -201,7 +204,7 @@ func ResourceImagePipeline() *schema.Resource { func resourceImagePipelineCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateImagePipelineInput{ ClientToken: aws.String(id.UniqueId()), @@ -246,10 +249,10 @@ func resourceImagePipelineCreate(ctx context.Context, d *schema.ResourceData, me } if v, ok := d.GetOk("status"); ok { - input.Status = aws.String(v.(string)) + input.Status = awstypes.PipelineStatus(v.(string)) } - output, err := conn.CreateImagePipelineWithContext(ctx, input) + output, err := conn.CreateImagePipeline(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Pipeline: %s", err) @@ -259,22 +262,22 @@ func resourceImagePipelineCreate(ctx context.Context, d *schema.ResourceData, me return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Pipeline: empty response") } - d.SetId(aws.StringValue(output.ImagePipelineArn)) + d.SetId(aws.ToString(output.ImagePipelineArn)) return append(diags, resourceImagePipelineRead(ctx, d, meta)...) } func resourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImagePipelineInput{ ImagePipelineArn: aws.String(d.Id()), } - output, err := conn.GetImagePipelineWithContext(ctx, input) + output, err := conn.GetImagePipeline(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Image Pipeline (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -327,7 +330,7 @@ func resourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta func resourceImagePipelineUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) if d.HasChanges( "description", @@ -378,10 +381,10 @@ func resourceImagePipelineUpdate(ctx context.Context, d *schema.ResourceData, me } if v, ok := d.GetOk("status"); ok { - input.Status = aws.String(v.(string)) + input.Status = awstypes.PipelineStatus(v.(string)) } - _, err := conn.UpdateImagePipelineWithContext(ctx, input) + _, err := conn.UpdateImagePipeline(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Image Builder Image Pipeline (%s): %s", d.Id(), err) @@ -393,15 +396,15 @@ func resourceImagePipelineUpdate(ctx context.Context, d *schema.ResourceData, me func resourceImagePipelineDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteImagePipelineInput{ ImagePipelineArn: aws.String(d.Id()), } - _, err := conn.DeleteImagePipelineWithContext(ctx, input) + _, err := conn.DeleteImagePipeline(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } @@ -412,12 +415,12 @@ func resourceImagePipelineDelete(ctx context.Context, d *schema.ResourceData, me return diags } -func expandImageScanningConfiguration(tfMap map[string]interface{}) *imagebuilder.ImageScanningConfiguration { +func expandImageScanningConfiguration(tfMap map[string]interface{}) *awstypes.ImageScanningConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.ImageScanningConfiguration{} + apiObject := &awstypes.ImageScanningConfiguration{} if v, ok := tfMap["image_scanning_enabled"].(bool); ok { apiObject.ImageScanningEnabled = aws.Bool(v) @@ -430,15 +433,15 @@ func expandImageScanningConfiguration(tfMap map[string]interface{}) *imagebuilde return apiObject } -func expandECRConfiguration(tfMap map[string]interface{}) *imagebuilder.EcrConfiguration { +func expandECRConfiguration(tfMap map[string]interface{}) *awstypes.EcrConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.EcrConfiguration{} + apiObject := &awstypes.EcrConfiguration{} if v, ok := tfMap["container_tags"].(*schema.Set); ok { - apiObject.ContainerTags = flex.ExpandStringSet(v) + apiObject.ContainerTags = flex.ExpandStringValueSet(v) } if v, ok := tfMap["repository_name"].(string); ok { @@ -448,33 +451,33 @@ func expandECRConfiguration(tfMap map[string]interface{}) *imagebuilder.EcrConfi return apiObject } -func expandImageTestConfiguration(tfMap map[string]interface{}) *imagebuilder.ImageTestsConfiguration { +func expandImageTestConfiguration(tfMap map[string]interface{}) *awstypes.ImageTestsConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.ImageTestsConfiguration{} + apiObject := &awstypes.ImageTestsConfiguration{} if v, ok := tfMap["image_tests_enabled"].(bool); ok { apiObject.ImageTestsEnabled = aws.Bool(v) } if v, ok := tfMap["timeout_minutes"].(int); ok && v != 0 { - apiObject.TimeoutMinutes = aws.Int64(int64(v)) + apiObject.TimeoutMinutes = aws.Int32(int32(v)) } return apiObject } -func expandPipelineSchedule(tfMap map[string]interface{}) *imagebuilder.Schedule { +func expandPipelineSchedule(tfMap map[string]interface{}) *awstypes.Schedule { if tfMap == nil { return nil } - apiObject := &imagebuilder.Schedule{} + apiObject := &awstypes.Schedule{} if v, ok := tfMap["pipeline_execution_start_condition"].(string); ok && v != "" { - apiObject.PipelineExecutionStartCondition = aws.String(v) + apiObject.PipelineExecutionStartCondition = awstypes.PipelineExecutionStartCondition(v) } if v, ok := tfMap["schedule_expression"].(string); ok && v != "" { @@ -488,7 +491,7 @@ func expandPipelineSchedule(tfMap map[string]interface{}) *imagebuilder.Schedule return apiObject } -func flattenImageScanningConfiguration(apiObject *imagebuilder.ImageScanningConfiguration) map[string]interface{} { +func flattenImageScanningConfiguration(apiObject *awstypes.ImageScanningConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -496,7 +499,7 @@ func flattenImageScanningConfiguration(apiObject *imagebuilder.ImageScanningConf tfMap := map[string]interface{}{} if v := apiObject.ImageScanningEnabled; v != nil { - tfMap["image_scanning_enabled"] = aws.BoolValue(v) + tfMap["image_scanning_enabled"] = aws.ToBool(v) } if v := apiObject.EcrConfiguration; v != nil { @@ -506,7 +509,7 @@ func flattenImageScanningConfiguration(apiObject *imagebuilder.ImageScanningConf return tfMap } -func flattenECRConfiguration(apiObject *imagebuilder.EcrConfiguration) map[string]interface{} { +func flattenECRConfiguration(apiObject *awstypes.EcrConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -514,17 +517,17 @@ func flattenECRConfiguration(apiObject *imagebuilder.EcrConfiguration) map[strin tfMap := map[string]interface{}{} if v := apiObject.RepositoryName; v != nil { - tfMap["repository_name"] = aws.StringValue(v) + tfMap["repository_name"] = aws.ToString(v) } if v := apiObject.ContainerTags; v != nil { - tfMap["container_tags"] = aws.StringValueSlice(v) + tfMap["container_tags"] = aws.ToStringSlice(v) } return tfMap } -func flattenImageTestsConfiguration(apiObject *imagebuilder.ImageTestsConfiguration) map[string]interface{} { +func flattenImageTestsConfiguration(apiObject *awstypes.ImageTestsConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -532,17 +535,17 @@ func flattenImageTestsConfiguration(apiObject *imagebuilder.ImageTestsConfigurat tfMap := map[string]interface{}{} if v := apiObject.ImageTestsEnabled; v != nil { - tfMap["image_tests_enabled"] = aws.BoolValue(v) + tfMap["image_tests_enabled"] = aws.ToBool(v) } if v := apiObject.TimeoutMinutes; v != nil { - tfMap["timeout_minutes"] = aws.Int64Value(v) + tfMap["timeout_minutes"] = aws.ToInt64(v) } return tfMap } -func flattenSchedule(apiObject *imagebuilder.Schedule) map[string]interface{} { +func flattenSchedule(apiObject *awstypes.Schedule) map[string]interface{} { if apiObject == nil { return nil } @@ -550,15 +553,15 @@ func flattenSchedule(apiObject *imagebuilder.Schedule) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.PipelineExecutionStartCondition; v != nil { - tfMap["pipeline_execution_start_condition"] = aws.StringValue(v) + tfMap["pipeline_execution_start_condition"] = string(v) } if v := apiObject.ScheduleExpression; v != nil { - tfMap["schedule_expression"] = aws.StringValue(v) + tfMap["schedule_expression"] = aws.ToString(v) } if v := apiObject.Timezone; v != nil { - tfMap["timezone"] = aws.StringValue(v) + tfMap["timezone"] = aws.ToString(v) } return tfMap diff --git a/internal/service/imagebuilder/image_pipeline_data_source.go b/internal/service/imagebuilder/image_pipeline_data_source.go index 04b380cd567..14cc2f9d315 100644 --- a/internal/service/imagebuilder/image_pipeline_data_source.go +++ b/internal/service/imagebuilder/image_pipeline_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -149,7 +149,7 @@ func DataSourceImagePipeline() *schema.Resource { func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImagePipelineInput{} @@ -157,7 +157,7 @@ func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, me input.ImagePipelineArn = aws.String(v.(string)) } - output, err := conn.GetImagePipelineWithContext(ctx, input) + output, err := conn.GetImagePipeline(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Pipeline: %s", err) @@ -169,7 +169,7 @@ func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, me imagePipeline := output.ImagePipeline - d.SetId(aws.StringValue(imagePipeline.Arn)) + d.SetId(aws.ToString(imagePipeline.Arn)) d.Set("arn", imagePipeline.Arn) d.Set("container_recipe_arn", imagePipeline.ContainerRecipeArn) d.Set("date_created", imagePipeline.DateCreated) diff --git a/internal/service/imagebuilder/image_pipeline_test.go b/internal/service/imagebuilder/image_pipeline_test.go index 01202d38e3e..2d4191bbfef 100644 --- a/internal/service/imagebuilder/image_pipeline_test.go +++ b/internal/service/imagebuilder/image_pipeline_test.go @@ -9,14 +9,15 @@ import ( "strings" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -53,9 +54,9 @@ func TestAccImageBuilderImagePipeline_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.0.timeout_minutes", "720"), resource.TestCheckResourceAttrPair(resourceName, "infrastructure_configuration_arn", infrastructureConfigurationResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "platform", imagebuilder.PlatformLinux), + resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "schedule.#", "0"), - resource.TestCheckResourceAttr(resourceName, "status", imagebuilder.PipelineStatusEnabled), + resource.TestCheckResourceAttr(resourceName, "status", string(types.PipelineStatusEnabled)), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, @@ -464,11 +465,11 @@ func TestAccImageBuilderImagePipeline_Schedule_pipelineExecutionStartCondition(t CheckDestroy: testAccCheckImagePipelineDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImagePipelineConfig_scheduleExecutionStartCondition(rName, imagebuilder.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable), + Config: testAccImagePipelineConfig_scheduleExecutionStartCondition(rName, string(types.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "schedule.#", "1"), - resource.TestCheckResourceAttr(resourceName, "schedule.0.pipeline_execution_start_condition", imagebuilder.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable), + resource.TestCheckResourceAttr(resourceName, "schedule.0.pipeline_execution_start_condition", string(types.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable)), ), }, { @@ -478,11 +479,11 @@ func TestAccImageBuilderImagePipeline_Schedule_pipelineExecutionStartCondition(t ImportStateVerifyIgnore: []string{"date_next_run"}, }, { - Config: testAccImagePipelineConfig_scheduleExecutionStartCondition(rName, imagebuilder.PipelineExecutionStartConditionExpressionMatchOnly), + Config: testAccImagePipelineConfig_scheduleExecutionStartCondition(rName, string(types.PipelineExecutionStartConditionExpressionMatchOnly)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "schedule.#", "1"), - resource.TestCheckResourceAttr(resourceName, "schedule.0.pipeline_execution_start_condition", imagebuilder.PipelineExecutionStartConditionExpressionMatchOnly), + resource.TestCheckResourceAttr(resourceName, "schedule.0.pipeline_execution_start_condition", string(types.PipelineExecutionStartConditionExpressionMatchOnly)), ), }, }, @@ -577,10 +578,10 @@ func TestAccImageBuilderImagePipeline_status(t *testing.T) { CheckDestroy: testAccCheckImagePipelineDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImagePipelineConfig_status(rName, imagebuilder.PipelineStatusDisabled), + Config: testAccImagePipelineConfig_status(rName, string(types.PipelineStatusDisabled)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "status", imagebuilder.PipelineStatusDisabled), + resource.TestCheckResourceAttr(resourceName, "status", string(types.PipelineStatusDisabled)), ), }, { @@ -589,10 +590,10 @@ func TestAccImageBuilderImagePipeline_status(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccImagePipelineConfig_status(rName, imagebuilder.PipelineStatusEnabled), + Config: testAccImagePipelineConfig_status(rName, string(types.PipelineStatusEnabled)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "status", imagebuilder.PipelineStatusEnabled), + resource.TestCheckResourceAttr(resourceName, "status", string(types.PipelineStatusEnabled)), ), }, }, @@ -646,7 +647,7 @@ func TestAccImageBuilderImagePipeline_tags(t *testing.T) { func testAccCheckImagePipelineDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_image_pipeline" { @@ -657,9 +658,9 @@ func testAccCheckImagePipelineDestroy(ctx context.Context) resource.TestCheckFun ImagePipelineArn: aws.String(rs.Primary.ID), } - output, err := conn.GetImagePipelineWithContext(ctx, input) + output, err := conn.GetImagePipeline(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -683,13 +684,13 @@ func testAccCheckImagePipelineExists(ctx context.Context, resourceName string) r return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImagePipelineInput{ ImagePipelineArn: aws.String(rs.Primary.ID), } - _, err := conn.GetImagePipelineWithContext(ctx, input) + _, err := conn.GetImagePipeline(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Image Pipeline (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/image_pipelines_data_source.go b/internal/service/imagebuilder/image_pipelines_data_source.go index e47d46ae286..54c8a25ddde 100644 --- a/internal/service/imagebuilder/image_pipelines_data_source.go +++ b/internal/service/imagebuilder/image_pipelines_data_source.go @@ -6,8 +6,9 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -37,7 +38,7 @@ func DataSourceImagePipelines() *schema.Resource { func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.ListImagePipelinesInput{} @@ -45,9 +46,9 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*imagebuilder.ImagePipeline + var results []*awstypes.ImagePipeline - err := conn.ListImagePipelinesPagesWithContext(ctx, input, func(page *imagebuilder.ListImagePipelinesOutput, lastPage bool) bool { + err := conn.ListImagePipelinesPages(ctx, input, func(page *imagebuilder.ListImagePipelinesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -70,8 +71,8 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m var arns, names []string for _, r := range results { - arns = append(arns, aws.StringValue(r.Arn)) - names = append(names, aws.StringValue(r.Name)) + arns = append(arns, aws.ToString(r.Arn)) + names = append(names, aws.ToString(r.Name)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index fce38e8a381..435820e4459 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -9,14 +9,17 @@ import ( "log" "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "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/types/nullable" @@ -105,10 +108,10 @@ func ResourceImageRecipe() *schema.Resource { ValidateFunc: validation.IntBetween(1, 16000), }, "volume_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(imagebuilder.EbsVolumeType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.EbsVolumeType](), }, }, }, @@ -251,7 +254,7 @@ func ResourceImageRecipe() *schema.Resource { func resourceImageRecipeCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateImageRecipeInput{ ClientToken: aws.String(id.UniqueId()), @@ -279,14 +282,14 @@ func resourceImageRecipeCreate(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("systems_manager_agent"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - input.AdditionalInstanceConfiguration = &imagebuilder.AdditionalInstanceConfiguration{ + input.AdditionalInstanceConfiguration = &awstypes.AdditionalInstanceConfiguration{ SystemsManagerAgent: expandSystemsManagerAgent(v.([]interface{})[0].(map[string]interface{})), } } if v, ok := d.GetOk("user_data_base64"); ok { if input.AdditionalInstanceConfiguration == nil { - input.AdditionalInstanceConfiguration = &imagebuilder.AdditionalInstanceConfiguration{} + input.AdditionalInstanceConfiguration = &awstypes.AdditionalInstanceConfiguration{} } input.AdditionalInstanceConfiguration.UserDataOverride = aws.String(v.(string)) } @@ -298,7 +301,7 @@ func resourceImageRecipeCreate(ctx context.Context, d *schema.ResourceData, meta input.WorkingDirectory = aws.String(v.(string)) } - output, err := conn.CreateImageRecipeWithContext(ctx, input) + output, err := conn.CreateImageRecipe(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Recipe: %s", err) @@ -308,22 +311,22 @@ func resourceImageRecipeCreate(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Recipe: empty response") } - d.SetId(aws.StringValue(output.ImageRecipeArn)) + d.SetId(aws.ToString(output.ImageRecipeArn)) return append(diags, resourceImageRecipeRead(ctx, d, meta)...) } func resourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImageRecipeInput{ ImageRecipeArn: aws.String(d.Id()), } - output, err := conn.GetImageRecipeWithContext(ctx, input) + output, err := conn.GetImageRecipe(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Image Recipe (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -372,15 +375,15 @@ func resourceImageRecipeUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceImageRecipeDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteImageRecipeInput{ ImageRecipeArn: aws.String(d.Id()), } - _, err := conn.DeleteImageRecipeWithContext(ctx, input) + _, err := conn.DeleteImageRecipe(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } @@ -391,12 +394,12 @@ func resourceImageRecipeDelete(ctx context.Context, d *schema.ResourceData, meta return diags } -func expandComponentConfiguration(tfMap map[string]interface{}) *imagebuilder.ComponentConfiguration { +func expandComponentConfiguration(tfMap map[string]interface{}) *awstypes.ComponentConfiguration { if tfMap == nil { return nil } - apiObject := &imagebuilder.ComponentConfiguration{} + apiObject := &awstypes.ComponentConfiguration{} if v, ok := tfMap["component_arn"].(string); ok && v != "" { apiObject.ComponentArn = aws.String(v) @@ -409,12 +412,12 @@ func expandComponentConfiguration(tfMap map[string]interface{}) *imagebuilder.Co return apiObject } -func expandComponentParameters(tfList []interface{}) []*imagebuilder.ComponentParameter { +func expandComponentParameters(tfList []interface{}) []*awstypes.ComponentParameter { if len(tfList) == 0 { return nil } - var apiObjects []*imagebuilder.ComponentParameter + var apiObjects []*awstypes.ComponentParameter for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -435,12 +438,12 @@ func expandComponentParameters(tfList []interface{}) []*imagebuilder.ComponentPa return apiObjects } -func expandComponentParameter(tfMap map[string]interface{}) *imagebuilder.ComponentParameter { +func expandComponentParameter(tfMap map[string]interface{}) *awstypes.ComponentParameter { if tfMap == nil { return nil } - apiObject := &imagebuilder.ComponentParameter{} + apiObject := &awstypes.ComponentParameter{} if v, ok := tfMap["name"].(string); ok && v != "" { apiObject.Name = aws.String(v) @@ -455,12 +458,12 @@ func expandComponentParameter(tfMap map[string]interface{}) *imagebuilder.Compon return apiObject } -func expandComponentConfigurations(tfList []interface{}) []*imagebuilder.ComponentConfiguration { +func expandComponentConfigurations(tfList []interface{}) []*awstypes.ComponentConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*imagebuilder.ComponentConfiguration + var apiObjects []*awstypes.ComponentConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -481,12 +484,12 @@ func expandComponentConfigurations(tfList []interface{}) []*imagebuilder.Compone return apiObjects } -func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *imagebuilder.EbsInstanceBlockDeviceSpecification { +func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *awstypes.EbsInstanceBlockDeviceSpecification { if tfMap == nil { return nil } - apiObject := &imagebuilder.EbsInstanceBlockDeviceSpecification{} + apiObject := &awstypes.EbsInstanceBlockDeviceSpecification{} if v, null, _ := nullable.Bool(tfMap["delete_on_termination"].(string)).Value(); !null { apiObject.DeleteOnTermination = aws.Bool(v) @@ -497,7 +500,7 @@ func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *im } if v, ok := tfMap["iops"].(int); ok && v != 0 { - apiObject.Iops = aws.Int64(int64(v)) + apiObject.Iops = aws.Int32(int32(v)) } if v, ok := tfMap["kms_key_id"].(string); ok && v != "" { @@ -509,26 +512,26 @@ func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *im } if v, ok := tfMap["throughput"].(int); ok && v != 0 { - apiObject.Throughput = aws.Int64(int64(v)) + apiObject.Throughput = aws.Int32(int32(v)) } if v, ok := tfMap["volume_size"].(int); ok && v != 0 { - apiObject.VolumeSize = aws.Int64(int64(v)) + apiObject.VolumeSize = aws.Int32(int32(v)) } if v, ok := tfMap["volume_type"].(string); ok && v != "" { - apiObject.VolumeType = aws.String(v) + apiObject.VolumeType = awstypes.EbsVolumeType(v) } return apiObject } -func expandInstanceBlockDeviceMapping(tfMap map[string]interface{}) *imagebuilder.InstanceBlockDeviceMapping { +func expandInstanceBlockDeviceMapping(tfMap map[string]interface{}) *awstypes.InstanceBlockDeviceMapping { if tfMap == nil { return nil } - apiObject := &imagebuilder.InstanceBlockDeviceMapping{} + apiObject := &awstypes.InstanceBlockDeviceMapping{} if v, ok := tfMap["device_name"].(string); ok && v != "" { apiObject.DeviceName = aws.String(v) @@ -549,12 +552,12 @@ func expandInstanceBlockDeviceMapping(tfMap map[string]interface{}) *imagebuilde return apiObject } -func expandInstanceBlockDeviceMappings(tfList []interface{}) []*imagebuilder.InstanceBlockDeviceMapping { +func expandInstanceBlockDeviceMappings(tfList []interface{}) []*awstypes.InstanceBlockDeviceMapping { if len(tfList) == 0 { return nil } - var apiObjects []*imagebuilder.InstanceBlockDeviceMapping + var apiObjects []*awstypes.InstanceBlockDeviceMapping for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -575,12 +578,12 @@ func expandInstanceBlockDeviceMappings(tfList []interface{}) []*imagebuilder.Ins return apiObjects } -func expandSystemsManagerAgent(tfMap map[string]interface{}) *imagebuilder.SystemsManagerAgent { +func expandSystemsManagerAgent(tfMap map[string]interface{}) *awstypes.SystemsManagerAgent { if tfMap == nil { return nil } - apiObject := &imagebuilder.SystemsManagerAgent{} + apiObject := &awstypes.SystemsManagerAgent{} if v, ok := tfMap["uninstall_after_build"].(bool); ok { apiObject.UninstallAfterBuild = aws.Bool(v) @@ -589,7 +592,7 @@ func expandSystemsManagerAgent(tfMap map[string]interface{}) *imagebuilder.Syste return apiObject } -func flattenComponentConfiguration(apiObject *imagebuilder.ComponentConfiguration) map[string]interface{} { +func flattenComponentConfiguration(apiObject *awstypes.ComponentConfiguration) map[string]interface{} { if apiObject == nil { return nil } @@ -597,7 +600,7 @@ func flattenComponentConfiguration(apiObject *imagebuilder.ComponentConfiguratio tfMap := map[string]interface{}{} if v := apiObject.ComponentArn; v != nil { - tfMap["component_arn"] = aws.StringValue(v) + tfMap["component_arn"] = aws.ToString(v) } if v := apiObject.Parameters; v != nil { @@ -607,7 +610,7 @@ func flattenComponentConfiguration(apiObject *imagebuilder.ComponentConfiguratio return tfMap } -func flattenComponentParameters(apiObjects []*imagebuilder.ComponentParameter) []interface{} { +func flattenComponentParameters(apiObjects []*awstypes.ComponentParameter) []interface{} { if len(apiObjects) == 0 { return nil } @@ -625,7 +628,7 @@ func flattenComponentParameters(apiObjects []*imagebuilder.ComponentParameter) [ return tfList } -func flattenComponentParameter(apiObject *imagebuilder.ComponentParameter) map[string]interface{} { +func flattenComponentParameter(apiObject *awstypes.ComponentParameter) map[string]interface{} { if apiObject == nil { return nil } @@ -633,19 +636,19 @@ func flattenComponentParameter(apiObject *imagebuilder.ComponentParameter) map[s tfMap := map[string]interface{}{} if v := apiObject.Name; v != nil { - tfMap["name"] = aws.StringValue(v) + tfMap["name"] = aws.ToString(v) } if v := apiObject.Value; v != nil { // ImageBuilder API quirk // Even though Value is a slice, only one element is accepted. - tfMap["value"] = aws.StringValueSlice(v)[0] + tfMap["value"] = aws.ToStringSlice(v)[0] } return tfMap } -func flattenComponentConfigurations(apiObjects []*imagebuilder.ComponentConfiguration) []interface{} { +func flattenComponentConfigurations(apiObjects []*awstypes.ComponentConfiguration) []interface{} { if len(apiObjects) == 0 { return nil } @@ -663,7 +666,7 @@ func flattenComponentConfigurations(apiObjects []*imagebuilder.ComponentConfigur return tfList } -func flattenEBSInstanceBlockDeviceSpecification(apiObject *imagebuilder.EbsInstanceBlockDeviceSpecification) map[string]interface{} { +func flattenEBSInstanceBlockDeviceSpecification(apiObject *awstypes.EbsInstanceBlockDeviceSpecification) map[string]interface{} { if apiObject == nil { return nil } @@ -671,41 +674,41 @@ func flattenEBSInstanceBlockDeviceSpecification(apiObject *imagebuilder.EbsInsta tfMap := map[string]interface{}{} if v := apiObject.DeleteOnTermination; v != nil { - tfMap["delete_on_termination"] = strconv.FormatBool(aws.BoolValue(v)) + tfMap["delete_on_termination"] = strconv.FormatBool(aws.ToBool(v)) } if v := apiObject.Encrypted; v != nil { - tfMap["encrypted"] = strconv.FormatBool(aws.BoolValue(v)) + tfMap["encrypted"] = strconv.FormatBool(aws.ToBool(v)) } if v := apiObject.Iops; v != nil { - tfMap["iops"] = aws.Int64Value(v) + tfMap["iops"] = aws.ToInt64(v) } if v := apiObject.KmsKeyId; v != nil { - tfMap["kms_key_id"] = aws.StringValue(v) + tfMap["kms_key_id"] = aws.ToString(v) } if v := apiObject.SnapshotId; v != nil { - tfMap["snapshot_id"] = aws.StringValue(v) + tfMap["snapshot_id"] = aws.ToString(v) } if v := apiObject.Throughput; v != nil { - tfMap["throughput"] = aws.Int64Value(v) + tfMap["throughput"] = aws.ToInt32(v) } if v := apiObject.VolumeSize; v != nil { - tfMap["volume_size"] = aws.Int64Value(v) + tfMap["volume_size"] = aws.ToInt32(v) } if v := apiObject.VolumeType; v != nil { - tfMap["volume_type"] = aws.StringValue(v) + tfMap["volume_type"] = awstypes.EbsVolumeType(v) } return tfMap } -func flattenInstanceBlockDeviceMapping(apiObject *imagebuilder.InstanceBlockDeviceMapping) map[string]interface{} { +func flattenInstanceBlockDeviceMapping(apiObject *awstypes.InstanceBlockDeviceMapping) map[string]interface{} { if apiObject == nil { return nil } @@ -713,7 +716,7 @@ func flattenInstanceBlockDeviceMapping(apiObject *imagebuilder.InstanceBlockDevi tfMap := map[string]interface{}{} if v := apiObject.DeviceName; v != nil { - tfMap["device_name"] = aws.StringValue(v) + tfMap["device_name"] = aws.ToString(v) } if v := apiObject.Ebs; v != nil { @@ -725,13 +728,13 @@ func flattenInstanceBlockDeviceMapping(apiObject *imagebuilder.InstanceBlockDevi } if v := apiObject.VirtualName; v != nil { - tfMap["virtual_name"] = aws.StringValue(v) + tfMap["virtual_name"] = aws.ToString(v) } return tfMap } -func flattenInstanceBlockDeviceMappings(apiObjects []*imagebuilder.InstanceBlockDeviceMapping) []interface{} { +func flattenInstanceBlockDeviceMappings(apiObjects []*awstypes.InstanceBlockDeviceMapping) []interface{} { if len(apiObjects) == 0 { return nil } @@ -749,7 +752,7 @@ func flattenInstanceBlockDeviceMappings(apiObjects []*imagebuilder.InstanceBlock return tfList } -func flattenSystemsManagerAgent(apiObject *imagebuilder.SystemsManagerAgent) map[string]interface{} { +func flattenSystemsManagerAgent(apiObject *awstypes.SystemsManagerAgent) map[string]interface{} { if apiObject == nil { return nil } @@ -757,7 +760,7 @@ func flattenSystemsManagerAgent(apiObject *imagebuilder.SystemsManagerAgent) map tfMap := map[string]interface{}{} if v := apiObject.UninstallAfterBuild; v != nil { - tfMap["uninstall_after_build"] = aws.BoolValue(v) + tfMap["uninstall_after_build"] = aws.ToBool(v) } return tfMap diff --git a/internal/service/imagebuilder/image_recipe_data_source.go b/internal/service/imagebuilder/image_recipe_data_source.go index 4d9aaa3c2fa..da92502791a 100644 --- a/internal/service/imagebuilder/image_recipe_data_source.go +++ b/internal/service/imagebuilder/image_recipe_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -158,7 +158,7 @@ func DataSourceImageRecipe() *schema.Resource { func dataSourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &imagebuilder.GetImageRecipeInput{} @@ -167,19 +167,19 @@ func dataSourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta input.ImageRecipeArn = aws.String(v.(string)) } - output, err := conn.GetImageRecipeWithContext(ctx, input) + output, err := conn.GetImageRecipe(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): %s", aws.StringValue(input.ImageRecipeArn), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): %s", aws.ToString(input.ImageRecipeArn), err) } if output == nil || output.ImageRecipe == nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): empty response", aws.StringValue(input.ImageRecipeArn)) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): empty response", aws.ToString(input.ImageRecipeArn)) } imageRecipe := output.ImageRecipe - d.SetId(aws.StringValue(imageRecipe.Arn)) + d.SetId(aws.ToString(imageRecipe.Arn)) d.Set("arn", imageRecipe.Arn) d.Set("block_device_mapping", flattenInstanceBlockDeviceMappings(imageRecipe.BlockDeviceMappings)) d.Set("component", flattenComponentConfigurations(imageRecipe.Components)) diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index bf3975e55cb..3c5f5021edb 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" @@ -332,12 +333,12 @@ func TestAccImageBuilderImageRecipe_BlockDeviceMappingEBS_volumeTypeGP2(t *testi CheckDestroy: testAccCheckImageRecipeDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, imagebuilder.EbsVolumeTypeGp2), + Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(types.EbsVolumeTypeGp2)), Check: resource.ComposeTestCheckFunc( testAccCheckImageRecipeExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "block_device_mapping.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "block_device_mapping.*", map[string]string{ - "ebs.0.volume_type": imagebuilder.EbsVolumeTypeGp2, + "ebs.0.volume_type": string(types.EbsVolumeTypeGp2)), }), ), }, @@ -742,7 +743,7 @@ func TestAccImageBuilderImageRecipe_windowsBaseImage(t *testing.T) { func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_image_recipe" { @@ -753,9 +754,9 @@ func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc ImageRecipeArn: aws.String(rs.Primary.ID), } - output, err := conn.GetImageRecipeWithContext(ctx, input) + output, err := conn.GetImageRecipe(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -779,13 +780,13 @@ func testAccCheckImageRecipeExists(ctx context.Context, resourceName string) res return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImageRecipeInput{ ImageRecipeArn: aws.String(rs.Primary.ID), } - _, err := conn.GetImageRecipeWithContext(ctx, input) + _, err := conn.GetImageRecipe(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Image Recipe (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/image_recipes_data_source.go b/internal/service/imagebuilder/image_recipes_data_source.go index 3f6217240aa..8cd77610ece 100644 --- a/internal/service/imagebuilder/image_recipes_data_source.go +++ b/internal/service/imagebuilder/image_recipes_data_source.go @@ -6,12 +6,13 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" ) @@ -33,9 +34,9 @@ func DataSourceImageRecipes() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "owner": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice(imagebuilder.Ownership_Values(), false), + Type: schema.TypeString, + Optional: true, + ValidateDiagFunc: enum.Validate[awstypes.Ownership](), }, }, } @@ -43,21 +44,21 @@ func DataSourceImageRecipes() *schema.Resource { func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.ListImageRecipesInput{} if v, ok := d.GetOk("owner"); ok { - input.Owner = aws.String(v.(string)) + input.Owner = awstypes.Ownership(v.(string)) } if v, ok := d.GetOk("filter"); ok { input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*imagebuilder.ImageRecipeSummary + var results []*awstypes.ImageRecipeSummary - err := conn.ListImageRecipesPagesWithContext(ctx, input, func(page *imagebuilder.ListImageRecipesOutput, lastPage bool) bool { + err := conn.ListImageRecipesPages(ctx, input, func(page *imagebuilder.ListImageRecipesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -80,8 +81,8 @@ func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, met var arns, names []string for _, r := range results { - arns = append(arns, aws.StringValue(r.Arn)) - names = append(names, aws.StringValue(r.Name)) + arns = append(arns, aws.ToString(r.Arn)) + names = append(names, aws.ToString(r.Name)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/imagebuilder/image_test.go b/internal/service/imagebuilder/image_test.go index 65720fd8dcb..1d1ac32b868 100644 --- a/internal/service/imagebuilder/image_test.go +++ b/internal/service/imagebuilder/image_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -49,7 +50,7 @@ func TestAccImageBuilderImage_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.0.timeout_minutes", "720"), resource.TestCheckResourceAttrPair(resourceName, "infrastructure_configuration_arn", infrastructureConfigurationResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "platform", imagebuilder.PlatformLinux), + resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "os_version", "Amazon Linux 2"), resource.TestCheckResourceAttr(resourceName, "output_resources.#", "1"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -322,7 +323,7 @@ func TestAccImageBuilderImage_outputResources_containers(t *testing.T) { func testAccCheckImageDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_image_pipeline" { @@ -333,9 +334,9 @@ func testAccCheckImageDestroy(ctx context.Context) resource.TestCheckFunc { ImageBuildVersionArn: aws.String(rs.Primary.ID), } - output, err := conn.GetImageWithContext(ctx, input) + output, err := conn.GetImage(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -359,13 +360,13 @@ func testAccCheckImageExists(ctx context.Context, resourceName string) resource. return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetImageInput{ ImageBuildVersionArn: aws.String(rs.Primary.ID), } - _, err := conn.GetImageWithContext(ctx, input) + _, err := conn.GetImage(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Image (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/infrastructure_configuration.go b/internal/service/imagebuilder/infrastructure_configuration.go index 845f4184c78..44afaf0672c 100644 --- a/internal/service/imagebuilder/infrastructure_configuration.go +++ b/internal/service/imagebuilder/infrastructure_configuration.go @@ -7,15 +7,17 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "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" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -155,7 +157,7 @@ func ResourceInfrastructureConfiguration() *schema.Resource { func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateInfrastructureConfigurationInput{ ClientToken: aws.String(id.UniqueId()), @@ -176,7 +178,7 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re } if v, ok := d.GetOk("instance_types"); ok && v.(*schema.Set).Len() > 0 { - input.InstanceTypes = flex.ExpandStringSet(v.(*schema.Set)) + input.InstanceTypes = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("key_pair"); ok { @@ -196,7 +198,7 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re } if v, ok := d.GetOk("security_group_ids"); ok && v.(*schema.Set).Len() > 0 { - input.SecurityGroupIds = flex.ExpandStringSet(v.(*schema.Set)) + input.SecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("sns_topic_arn"); ok { @@ -211,9 +213,9 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re err := retry.RetryContext(ctx, propagationTimeout, func() *retry.RetryError { var err error - output, err = conn.CreateInfrastructureConfigurationWithContext(ctx, input) + output, err = conn.CreateInfrastructureConfiguration(ctx, input) - if tfawserr.ErrMessageContains(err, imagebuilder.ErrCodeInvalidParameterValueException, "instance profile does not exist") { + if errs.Contains(err, "instance profile does not exist") { return retry.RetryableError(err) } @@ -225,7 +227,7 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re }) if tfresource.TimedOut(err) { - output, err = conn.CreateInfrastructureConfigurationWithContext(ctx, input) + output, err = conn.CreateInfrastructureConfiguration(ctx, input) } if err != nil { @@ -236,22 +238,22 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re return sdkdiag.AppendErrorf(diags, "creating Image Builder Infrastructure Configuration: empty response") } - d.SetId(aws.StringValue(output.InfrastructureConfigurationArn)) + d.SetId(aws.ToString(output.InfrastructureConfigurationArn)) return append(diags, resourceInfrastructureConfigurationRead(ctx, d, meta)...) } func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetInfrastructureConfigurationInput{ InfrastructureConfigurationArn: aws.String(d.Id()), } - output, err := conn.GetInfrastructureConfigurationWithContext(ctx, input) + output, err := conn.GetInfrastructureConfiguration(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Infrastructure Configuration (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -281,7 +283,7 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso } d.Set("instance_profile_name", infrastructureConfiguration.InstanceProfileName) - d.Set("instance_types", aws.StringValueSlice(infrastructureConfiguration.InstanceTypes)) + d.Set("instance_types", infrastructureConfiguration.InstanceTypes) d.Set("key_pair", infrastructureConfiguration.KeyPair) if infrastructureConfiguration.Logging != nil { d.Set("logging", []interface{}{flattenLogging(infrastructureConfiguration.Logging)}) @@ -290,7 +292,7 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso } d.Set("name", infrastructureConfiguration.Name) d.Set("resource_tags", KeyValueTags(ctx, infrastructureConfiguration.ResourceTags).Map()) - d.Set("security_group_ids", aws.StringValueSlice(infrastructureConfiguration.SecurityGroupIds)) + d.Set("security_group_ids", infrastructureConfiguration.SecurityGroupIds) d.Set("sns_topic_arn", infrastructureConfiguration.SnsTopicArn) d.Set("subnet_id", infrastructureConfiguration.SubnetId) @@ -303,7 +305,7 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) if d.HasChanges( "description", @@ -336,7 +338,7 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re } if v, ok := d.GetOk("instance_types"); ok && v.(*schema.Set).Len() > 0 { - input.InstanceTypes = flex.ExpandStringSet(v.(*schema.Set)) + input.InstanceTypes = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("key_pair"); ok { @@ -352,7 +354,7 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re } if v, ok := d.GetOk("security_group_ids"); ok && v.(*schema.Set).Len() > 0 { - input.SecurityGroupIds = flex.ExpandStringSet(v.(*schema.Set)) + input.SecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("sns_topic_arn"); ok { @@ -364,9 +366,9 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re } err := retry.RetryContext(ctx, propagationTimeout, func() *retry.RetryError { - _, err := conn.UpdateInfrastructureConfigurationWithContext(ctx, input) + _, err := conn.UpdateInfrastructureConfiguration(ctx, input) - if tfawserr.ErrMessageContains(err, imagebuilder.ErrCodeInvalidParameterValueException, "instance profile does not exist") { + if errs.Contains(err, "instance profile does not exist") { return retry.RetryableError(err) } @@ -378,7 +380,7 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re }) if tfresource.TimedOut(err) { - _, err = conn.UpdateInfrastructureConfigurationWithContext(ctx, input) + _, err = conn.UpdateInfrastructureConfiguration(ctx, input) } if err != nil { @@ -391,15 +393,15 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re func resourceInfrastructureConfigurationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteInfrastructureConfigurationInput{ InfrastructureConfigurationArn: aws.String(d.Id()), } - _, err := conn.DeleteInfrastructureConfigurationWithContext(ctx, input) + _, err := conn.DeleteInfrastructureConfiguration(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } @@ -410,15 +412,15 @@ func resourceInfrastructureConfigurationDelete(ctx context.Context, d *schema.Re return diags } -func expandInstanceMetadataOptions(tfMap map[string]interface{}) *imagebuilder.InstanceMetadataOptions { +func expandInstanceMetadataOptions(tfMap map[string]interface{}) *awstypes.InstanceMetadataOptions { if tfMap == nil { return nil } - apiObject := &imagebuilder.InstanceMetadataOptions{} + apiObject := &awstypes.InstanceMetadataOptions{} if v, ok := tfMap["http_put_response_hop_limit"].(int); ok && v != 0 { - apiObject.HttpPutResponseHopLimit = aws.Int64(int64(v)) + apiObject.HttpPutResponseHopLimit = aws.Int32(int32(v)) } if v, ok := tfMap["http_tokens"].(string); ok && v != "" { @@ -428,12 +430,12 @@ func expandInstanceMetadataOptions(tfMap map[string]interface{}) *imagebuilder.I return apiObject } -func expandLogging(tfMap map[string]interface{}) *imagebuilder.Logging { +func expandLogging(tfMap map[string]interface{}) *awstypes.Logging { if tfMap == nil { return nil } - apiObject := &imagebuilder.Logging{} + apiObject := &awstypes.Logging{} if v, ok := tfMap["s3_logs"].([]interface{}); ok && len(v) > 0 && v[0] != nil { apiObject.S3Logs = expandS3Logs(v[0].(map[string]interface{})) @@ -442,12 +444,12 @@ func expandLogging(tfMap map[string]interface{}) *imagebuilder.Logging { return apiObject } -func expandS3Logs(tfMap map[string]interface{}) *imagebuilder.S3Logs { +func expandS3Logs(tfMap map[string]interface{}) *awstypes.S3Logs { if tfMap == nil { return nil } - apiObject := &imagebuilder.S3Logs{} + apiObject := &awstypes.S3Logs{} if v, ok := tfMap["s3_bucket_name"].(string); ok && v != "" { apiObject.S3BucketName = aws.String(v) @@ -460,7 +462,7 @@ func expandS3Logs(tfMap map[string]interface{}) *imagebuilder.S3Logs { return apiObject } -func flattenInstanceMetadataOptions(apiObject *imagebuilder.InstanceMetadataOptions) map[string]interface{} { +func flattenInstanceMetadataOptions(apiObject *awstypes.InstanceMetadataOptions) map[string]interface{} { if apiObject == nil { return nil } @@ -468,17 +470,17 @@ func flattenInstanceMetadataOptions(apiObject *imagebuilder.InstanceMetadataOpti tfMap := map[string]interface{}{} if v := apiObject.HttpPutResponseHopLimit; v != nil { - tfMap["http_put_response_hop_limit"] = aws.Int64Value(v) + tfMap["http_put_response_hop_limit"] = aws.ToInt32(v) } if v := apiObject.HttpTokens; v != nil { - tfMap["http_tokens"] = aws.StringValue(v) + tfMap["http_tokens"] = aws.ToString(v) } return tfMap } -func flattenLogging(apiObject *imagebuilder.Logging) map[string]interface{} { +func flattenLogging(apiObject *awstypes.Logging) map[string]interface{} { if apiObject == nil { return nil } @@ -492,7 +494,7 @@ func flattenLogging(apiObject *imagebuilder.Logging) map[string]interface{} { return tfMap } -func flattenS3Logs(apiObject *imagebuilder.S3Logs) map[string]interface{} { +func flattenS3Logs(apiObject *awstypes.S3Logs) map[string]interface{} { if apiObject == nil { return nil } @@ -500,11 +502,11 @@ func flattenS3Logs(apiObject *imagebuilder.S3Logs) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.S3BucketName; v != nil { - tfMap["s3_bucket_name"] = aws.StringValue(v) + tfMap["s3_bucket_name"] = aws.ToString(v) } if v := apiObject.S3KeyPrefix; v != nil { - tfMap["s3_key_prefix"] = aws.StringValue(v) + tfMap["s3_key_prefix"] = aws.ToString(v) } return tfMap diff --git a/internal/service/imagebuilder/infrastructure_configuration_data_source.go b/internal/service/imagebuilder/infrastructure_configuration_data_source.go index 40bda575f19..c43d404c0d8 100644 --- a/internal/service/imagebuilder/infrastructure_configuration_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configuration_data_source.go @@ -6,8 +6,8 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -121,7 +121,7 @@ func DataSourceInfrastructureConfiguration() *schema.Resource { func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &imagebuilder.GetInfrastructureConfigurationInput{} @@ -130,7 +130,7 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re input.InfrastructureConfigurationArn = aws.String(v.(string)) } - output, err := conn.GetInfrastructureConfigurationWithContext(ctx, input) + output, err := conn.GetInfrastructureConfiguration(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "getting Image Builder Infrastructure Configuration (%s): %s", d.Id(), err) @@ -142,7 +142,7 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re infrastructureConfiguration := output.InfrastructureConfiguration - d.SetId(aws.StringValue(infrastructureConfiguration.Arn)) + d.SetId(aws.ToString(infrastructureConfiguration.Arn)) d.Set("arn", infrastructureConfiguration.Arn) d.Set("date_created", infrastructureConfiguration.DateCreated) d.Set("date_updated", infrastructureConfiguration.DateUpdated) @@ -155,7 +155,7 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re } d.Set("instance_profile_name", infrastructureConfiguration.InstanceProfileName) - d.Set("instance_types", aws.StringValueSlice(infrastructureConfiguration.InstanceTypes)) + d.Set("instance_types", infrastructureConfiguration.InstanceTypes) d.Set("key_pair", infrastructureConfiguration.KeyPair) if infrastructureConfiguration.Logging != nil { d.Set("logging", []interface{}{flattenLogging(infrastructureConfiguration.Logging)}) @@ -164,7 +164,7 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re } d.Set("name", infrastructureConfiguration.Name) d.Set("resource_tags", KeyValueTags(ctx, infrastructureConfiguration.ResourceTags).Map()) - d.Set("security_group_ids", aws.StringValueSlice(infrastructureConfiguration.SecurityGroupIds)) + d.Set("security_group_ids", infrastructureConfiguration.SecurityGroupIds) d.Set("sns_topic_arn", infrastructureConfiguration.SnsTopicArn) d.Set("subnet_id", infrastructureConfiguration.SubnetId) d.Set("tags", KeyValueTags(ctx, infrastructureConfiguration.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) diff --git a/internal/service/imagebuilder/infrastructure_configuration_test.go b/internal/service/imagebuilder/infrastructure_configuration_test.go index 7bb46442942..c79063ec708 100644 --- a/internal/service/imagebuilder/infrastructure_configuration_test.go +++ b/internal/service/imagebuilder/infrastructure_configuration_test.go @@ -8,14 +8,15 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -580,7 +581,7 @@ func TestAccImageBuilderInfrastructureConfiguration_terminateInstanceOnFailure(t func testAccCheckInfrastructureConfigurationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_infrastructure_configuration" { @@ -591,9 +592,9 @@ func testAccCheckInfrastructureConfigurationDestroy(ctx context.Context) resourc InfrastructureConfigurationArn: aws.String(rs.Primary.ID), } - output, err := conn.GetInfrastructureConfigurationWithContext(ctx, input) + output, err := conn.GetInfrastructureConfiguration(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -617,13 +618,13 @@ func testAccCheckInfrastructureConfigurationExists(ctx context.Context, resource return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetInfrastructureConfigurationInput{ InfrastructureConfigurationArn: aws.String(rs.Primary.ID), } - _, err := conn.GetInfrastructureConfigurationWithContext(ctx, input) + _, err := conn.GetInfrastructureConfiguration(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Infrastructure Configuration (%s): %w", rs.Primary.ID, err) diff --git a/internal/service/imagebuilder/infrastructure_configurations_data_source.go b/internal/service/imagebuilder/infrastructure_configurations_data_source.go index 399c39f12a9..df469ee2649 100644 --- a/internal/service/imagebuilder/infrastructure_configurations_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configurations_data_source.go @@ -6,8 +6,9 @@ package imagebuilder import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -37,7 +38,7 @@ func DataSourceInfrastructureConfigurations() *schema.Resource { func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.ListInfrastructureConfigurationsInput{} @@ -45,9 +46,9 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*imagebuilder.InfrastructureConfigurationSummary + var results []*awstypes.InfrastructureConfigurationSummary - err := conn.ListInfrastructureConfigurationsPagesWithContext(ctx, input, func(page *imagebuilder.ListInfrastructureConfigurationsOutput, lastPage bool) bool { + err := conn.ListInfrastructureConfigurationsPages(ctx, input, func(page *imagebuilder.ListInfrastructureConfigurationsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -70,8 +71,8 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R var arns, names []string for _, r := range results { - arns = append(arns, aws.StringValue(r.Arn)) - names = append(names, aws.StringValue(r.Name)) + arns = append(arns, aws.ToString(r.Arn)) + names = append(names, aws.ToString(r.Name)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 82d3705436c..02c59a8c36a 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -374,8 +374,8 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq resp.Diagnostics.Append(d...) state.ResourceSelection = resourceSelection - state.ResourceType = flex.StringValueToFramework(ctx, out.ResourceType) - state.Status = flex.StringValueToFramework(ctx, out.Status) + state.ResourceType = flex.ToStringToFramework(ctx, out.ResourceType) + state.Status = flex.ToStringToFramework(ctx, out.Status) resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } @@ -680,7 +680,7 @@ func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExcl } if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + apiObject.TagMap = flex.ExpandFrameworkToStringMap(ctx, tfObj.TagMap) } return &apiObject, diags @@ -712,15 +712,15 @@ func expandPolicyDetailExclusionRulesAmis(ctx context.Context, tfList []resource } if !tfObj.Regions.IsNull() { - apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.LastLaunched) + apiObject.Regions = flex.ExpandFrameworkToStringList(ctx, tfObj.LastLaunched) } if !tfObj.SharedAccounts.IsNull() { - apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.SharedAccounts) + apiObject.Regions = flex.ExpandFrameworkToStringList(ctx, tfObj.SharedAccounts) } if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + apiObject.TagMap = flex.ExpandFrameworkToStringMap(ctx, tfObj.TagMap) } return &apiObject, diags @@ -764,7 +764,7 @@ func expandResourceSelection(ctx context.Context, tfList []resourceResourceSelec } if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + apiObject.TagMap = flex.ExpandFrameworkToStringMap(ctx, tfObj.TagMap) } return &apiObject, diags @@ -836,7 +836,7 @@ func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolic } obj := map[string]attr.Value{ - "type": flex.StringValueToFramework(ctx, apiObject.Type), + "type": flex.ToStringToFramework(ctx, apiObject.Type), } if apiObject.IncludeResources != nil { @@ -889,10 +889,10 @@ func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolic } obj := map[string]attr.Value{ - "type": flex.StringValueToFramework(ctx, apiObject.Type), + "type": flex.ToStringToFramework(ctx, apiObject.Type), "value": flex.Int32ToFramework(ctx, apiObject.Value), "retain_at_least": flex.Int32ToFramework(ctx, apiObject.RetainAtLeast), - "unit": flex.StringValueToFramework(ctx, apiObject.Unit), + "unit": flex.ToStringToFramework(ctx, apiObject.Unit), } objVal, d := types.ObjectValue(resourceFilterAttrTypes, obj) @@ -923,7 +923,7 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy } if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + obj["tag_map"] = flex.FlattenFrameworkToStringMap(ctx, apiObject.TagMap) } objVal, d := types.ObjectValue(resourceExclusionRulesAttrTypes, obj) @@ -956,15 +956,15 @@ func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.Lifecycl } if apiObject.Regions != nil { - obj["regions"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions) + obj["regions"] = flex.FlattenFrameworkToStringList(ctx, apiObject.Regions) } if apiObject.SharedAccounts != nil { - obj["shared_accounts"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts) + obj["shared_accounts"] = flex.FlattenFrameworkToStringList(ctx, apiObject.SharedAccounts) } if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + obj["tag_map"] = flex.FlattenFrameworkToStringMap(ctx, apiObject.TagMap) } objVal, d := types.ObjectValue(resourceAmisAttrTypes, obj) @@ -986,7 +986,7 @@ func flattenExclusionRulesAmisLastLaunched(ctx context.Context, apiObject *awsty } obj := map[string]attr.Value{ - "unit": flex.StringValueToFramework(ctx, apiObject.Unit), + "unit": flex.ToStringToFramework(ctx, apiObject.Unit), "value": flex.Int32ToFramework(ctx, apiObject.Value), } @@ -1018,7 +1018,7 @@ func flattenResourceSelection(ctx context.Context, apiObject *awstypes.Lifecycle } if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + obj["tag_map"] = flex.FlattenFrameworkToStringMap(ctx, apiObject.TagMap) } objVal, d := types.ObjectValue(resourceResourceSelectionAttrTypes, obj) diff --git a/internal/service/imagebuilder/status.go b/internal/service/imagebuilder/status.go index 225838f1025..0394f753aa1 100644 --- a/internal/service/imagebuilder/status.go +++ b/internal/service/imagebuilder/status.go @@ -7,32 +7,33 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" ) // statusImage fetches the Image and its Status -func statusImage(ctx context.Context, conn *imagebuilder.Imagebuilder, imageBuildVersionArn string) retry.StateRefreshFunc { +func statusImage(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string) retry.StateRefreshFunc { return func() (interface{}, string, error) { input := &imagebuilder.GetImageInput{ ImageBuildVersionArn: aws.String(imageBuildVersionArn), } - output, err := conn.GetImageWithContext(ctx, input) + output, err := conn.GetImage(ctx, input) if err != nil { - return nil, imagebuilder.ImageStatusPending, err + return nil, string(awstypes.ImageStatusPending), err } if output == nil || output.Image == nil || output.Image.State == nil { - return nil, imagebuilder.ImageStatusPending, nil + return nil, string(awstypes.ImageStatusPending), nil } - status := aws.StringValue(output.Image.State.Status) + status := aws.ToString(output.Image.State.Status) - if status == imagebuilder.ImageStatusFailed { - return output.Image, status, fmt.Errorf("%s", aws.StringValue(output.Image.State.Reason)) + if status == string(awstypes.ImageStatusFailed) { + return output.Image, status, fmt.Errorf("%s", aws.ToString(output.Image.State.Reason)) } return output.Image, status, nil diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index 76ce60ad7e4..b585c36c4b9 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -7,8 +7,8 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/sweep" @@ -58,7 +58,7 @@ func sweepComponents(region string) error { if err != nil { return fmt.Errorf("error getting client: %s", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var sweeperErrs *multierror.Error @@ -66,7 +66,7 @@ func sweepComponents(region string) error { input := &imagebuilder.ListComponentsInput{ Owner: aws.String(imagebuilder.OwnershipSelf), } - err = conn.ListComponentsPagesWithContext(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { + err = conn.ListComponentsPages(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -76,12 +76,12 @@ func sweepComponents(region string) error { continue } - arn := aws.StringValue(componentVersion.Arn) + arn := aws.ToString(componentVersion.Arn) input := &imagebuilder.ListComponentBuildVersionsInput{ ComponentVersionArn: componentVersion.Arn, } - err := conn.ListComponentBuildVersionsPagesWithContext(ctx, input, func(page *imagebuilder.ListComponentBuildVersionsOutput, lastPage bool) bool { + err := conn.ListComponentBuildVersionsPages(ctx, input, func(page *imagebuilder.ListComponentBuildVersionsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -91,7 +91,7 @@ func sweepComponents(region string) error { continue } - arn := aws.StringValue(componentSummary.Arn) + arn := aws.ToString(componentSummary.Arn) r := ResourceComponent() d := r.Data(nil) @@ -135,13 +135,13 @@ func sweepDistributionConfigurations(region string) error { if err != nil { return fmt.Errorf("error getting client: %s", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var sweeperErrs *multierror.Error input := &imagebuilder.ListDistributionConfigurationsInput{} - err = conn.ListDistributionConfigurationsPagesWithContext(ctx, input, func(page *imagebuilder.ListDistributionConfigurationsOutput, lastPage bool) bool { + err = conn.ListDistributionConfigurationsPages(ctx, input, func(page *imagebuilder.ListDistributionConfigurationsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -151,7 +151,7 @@ func sweepDistributionConfigurations(region string) error { continue } - arn := aws.StringValue(distributionConfigurationSummary.Arn) + arn := aws.ToString(distributionConfigurationSummary.Arn) r := ResourceDistributionConfiguration() d := r.Data(nil) @@ -184,13 +184,13 @@ func sweepImagePipelines(region string) error { if err != nil { return fmt.Errorf("error getting client: %w", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var sweeperErrs *multierror.Error input := &imagebuilder.ListImagePipelinesInput{} - err = conn.ListImagePipelinesPagesWithContext(ctx, input, func(page *imagebuilder.ListImagePipelinesOutput, lastPage bool) bool { + err = conn.ListImagePipelinesPages(ctx, input, func(page *imagebuilder.ListImagePipelinesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -200,7 +200,7 @@ func sweepImagePipelines(region string) error { continue } - arn := aws.StringValue(imagePipeline.Arn) + arn := aws.ToString(imagePipeline.Arn) r := ResourceImagePipeline() d := r.Data(nil) @@ -233,7 +233,7 @@ func sweepImageRecipes(region string) error { if err != nil { return fmt.Errorf("error getting client: %w", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var sweeperErrs *multierror.Error @@ -241,7 +241,7 @@ func sweepImageRecipes(region string) error { input := &imagebuilder.ListImageRecipesInput{ Owner: aws.String(imagebuilder.OwnershipSelf), } - err = conn.ListImageRecipesPagesWithContext(ctx, input, func(page *imagebuilder.ListImageRecipesOutput, lastPage bool) bool { + err = conn.ListImageRecipesPages(ctx, input, func(page *imagebuilder.ListImageRecipesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -251,7 +251,7 @@ func sweepImageRecipes(region string) error { continue } - arn := aws.StringValue(imageRecipeSummary.Arn) + arn := aws.ToString(imageRecipeSummary.Arn) r := ResourceImageRecipe() d := r.Data(nil) @@ -284,7 +284,7 @@ func sweepContainerRecipes(region string) error { if err != nil { return fmt.Errorf("error getting client: %w", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var sweeperErrs *multierror.Error @@ -292,7 +292,7 @@ func sweepContainerRecipes(region string) error { input := &imagebuilder.ListContainerRecipesInput{ Owner: aws.String(imagebuilder.OwnershipSelf), } - err = conn.ListContainerRecipesPagesWithContext(ctx, input, func(page *imagebuilder.ListContainerRecipesOutput, lastPage bool) bool { + err = conn.ListContainerRecipesPages(ctx, input, func(page *imagebuilder.ListContainerRecipesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -302,7 +302,7 @@ func sweepContainerRecipes(region string) error { continue } - arn := aws.StringValue(containerRecipeSummary.Arn) + arn := aws.ToString(containerRecipeSummary.Arn) r := ResourceContainerRecipe() d := r.Data(nil) @@ -337,7 +337,7 @@ func sweepImages(region string) error { return fmt.Errorf("error getting client: %w", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var errs *multierror.Error @@ -345,7 +345,7 @@ func sweepImages(region string) error { Owner: aws.String(imagebuilder.OwnershipSelf), } - err = conn.ListImagesPagesWithContext(ctx, input, func(page *imagebuilder.ListImagesOutput, lastPage bool) bool { + err = conn.ListImagesPages(ctx, input, func(page *imagebuilder.ListImagesOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -358,13 +358,13 @@ func sweepImages(region string) error { // Retrieve the Image's Build Version ARNs required as input // to the ResourceImage()'s Delete operation // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/19851 - imageVersionArn := aws.StringValue(imageVersion.Arn) + imageVersionArn := aws.ToString(imageVersion.Arn) input := &imagebuilder.ListImageBuildVersionsInput{ ImageVersionArn: imageVersion.Arn, } - err := conn.ListImageBuildVersionsPagesWithContext(ctx, input, func(page *imagebuilder.ListImageBuildVersionsOutput, lastPage bool) bool { + err := conn.ListImageBuildVersionsPages(ctx, input, func(page *imagebuilder.ListImageBuildVersionsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -374,7 +374,7 @@ func sweepImages(region string) error { continue } - imageBuildVersionArn := aws.StringValue(imageSummary.Arn) + imageBuildVersionArn := aws.ToString(imageSummary.Arn) r := ResourceImage() d := r.Data(nil) @@ -416,14 +416,14 @@ func sweepInfrastructureConfigurations(region string) error { if err != nil { return fmt.Errorf("error getting client: %s", err) } - conn := client.ImageBuilderConn(ctx) + conn := client.ImageBuilderClient(ctx) sweepResources := make([]sweep.Sweepable, 0) var sweeperErrs *multierror.Error input := &imagebuilder.ListInfrastructureConfigurationsInput{} - err = conn.ListInfrastructureConfigurationsPagesWithContext(ctx, input, func(page *imagebuilder.ListInfrastructureConfigurationsOutput, lastPage bool) bool { + err = conn.ListInfrastructureConfigurationsPages(ctx, input, func(page *imagebuilder.ListInfrastructureConfigurationsOutput, lastPage bool) bool { if page == nil { return !lastPage } @@ -433,7 +433,7 @@ func sweepInfrastructureConfigurations(region string) error { continue } - arn := aws.StringValue(infrastructureConfigurationSummary.Arn) + arn := aws.ToString(infrastructureConfigurationSummary.Arn) r := ResourceInfrastructureConfiguration() d := r.Data(nil) diff --git a/internal/service/imagebuilder/wait.go b/internal/service/imagebuilder/wait.go index ac4b4d2aa76..79267d5dab3 100644 --- a/internal/service/imagebuilder/wait.go +++ b/internal/service/imagebuilder/wait.go @@ -7,29 +7,30 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/service/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" ) // waitImageStatusAvailable waits for an Image to return Available -func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Imagebuilder, imageBuildVersionArn string, timeout time.Duration) (*imagebuilder.Image, error) { +func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string, timeout time.Duration) (*imagebuilder.Image, error) { stateConf := &retry.StateChangeConf{ Pending: []string{ - imagebuilder.ImageStatusBuilding, - imagebuilder.ImageStatusCreating, - imagebuilder.ImageStatusDistributing, - imagebuilder.ImageStatusIntegrating, - imagebuilder.ImageStatusPending, - imagebuilder.ImageStatusTesting, + string(awstypes.ImageStatusBuilding), + string(awstypes.ImageStatusCreating), + string(awstypes.ImageStatusDistributing), + string(awstypes.ImageStatusIntegrating), + string(awstypes.ImageStatusPending), + string(awstypes.ImageStatusTesting), }, - Target: []string{imagebuilder.ImageStatusAvailable}, + Target: []string{string(awstypes.ImageStatusAvailable)}, Refresh: statusImage(ctx, conn, imageBuildVersionArn), Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if v, ok := outputRaw.(*imagebuilder.Image); ok { + if v, ok := outputRaw.(*awstypes.Image); ok { return v, err } diff --git a/internal/service/imagebuilder/workflow.go b/internal/service/imagebuilder/workflow.go index 28a6bcadb70..b41e2cd76ce 100644 --- a/internal/service/imagebuilder/workflow.go +++ b/internal/service/imagebuilder/workflow.go @@ -8,14 +8,17 @@ import ( "log" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" @@ -82,10 +85,10 @@ func ResourceWorkflow() *schema.Resource { names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), "type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(imagebuilder.WorkflowType_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.Workflow](), }, "uri": { Type: schema.TypeString, @@ -107,7 +110,7 @@ func ResourceWorkflow() *schema.Resource { func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.CreateWorkflowInput{ ClientToken: aws.String(id.UniqueId()), @@ -137,7 +140,7 @@ func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta in input.Uri = aws.String(v.(string)) } - output, err := conn.CreateWorkflowWithContext(ctx, input) + output, err := conn.CreateWorkflow(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Workflow: %s", err) @@ -147,22 +150,22 @@ func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta in return sdkdiag.AppendErrorf(diags, "creating Image Builder Workflow: empty response") } - d.SetId(aws.StringValue(output.WorkflowBuildVersionArn)) + d.SetId(aws.ToString(output.WorkflowBuildVersionArn)) return append(diags, resourceWorkflowRead(ctx, d, meta)...) } func resourceWorkflowRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetWorkflowInput{ WorkflowBuildVersionArn: aws.String(d.Id()), } - output, err := conn.GetWorkflowWithContext(ctx, input) + output, err := conn.GetWorkflow(ctx, input) - if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { log.Printf("[WARN] Image Builder Workflow (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -201,15 +204,15 @@ func resourceWorkflowUpdate(ctx context.Context, d *schema.ResourceData, meta in func resourceWorkflowDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).ImageBuilderConn(ctx) + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.DeleteWorkflowInput{ WorkflowBuildVersionArn: aws.String(d.Id()), } - _, err := conn.DeleteWorkflowWithContext(ctx, input) + _, err := conn.DeleteWorkflow(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { return diags } diff --git a/internal/service/imagebuilder/workflow_test.go b/internal/service/imagebuilder/workflow_test.go index 8961282dd2b..ca4ed6cf27c 100644 --- a/internal/service/imagebuilder/workflow_test.go +++ b/internal/service/imagebuilder/workflow_test.go @@ -9,14 +9,15 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/imagebuilder" - "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/imagebuilder" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -45,7 +46,7 @@ func TestAccImageBuilderWorkflow_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "type", imagebuilder.WorkflowTypeTest), + resource.TestCheckResourceAttr(resourceName, "type", string(types.WorkflowTypeTest)), resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), ), }, @@ -239,7 +240,7 @@ func TestAccImageBuilderWorkflow_uri(t *testing.T) { func testAccCheckWorkflowDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_imagebuilder_workflow" { @@ -250,9 +251,9 @@ func testAccCheckWorkflowDestroy(ctx context.Context) resource.TestCheckFunc { WorkflowBuildVersionArn: aws.String(rs.Primary.ID), } - output, err := conn.GetWorkflowWithContext(ctx, input) + output, err := conn.GetWorkflow(ctx, input) - if tfawserr.ErrCodeEquals(err, imagebuilder.ErrCodeResourceNotFoundException) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } @@ -276,13 +277,13 @@ func testAccCheckWorkflowExists(ctx context.Context, resourceName string) resour return fmt.Errorf("resource not found: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderConn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) input := &imagebuilder.GetWorkflowInput{ WorkflowBuildVersionArn: aws.String(rs.Primary.ID), } - _, err := conn.GetWorkflowWithContext(ctx, input) + _, err := conn.GetWorkflow(ctx, input) if err != nil { return fmt.Errorf("error getting Image Builder Workflow (%s): %w", rs.Primary.ID, err) From 149c1c4a80b5ae359caa6e34872e3845f5f5ab39 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Thu, 29 Feb 2024 23:03:58 +0100 Subject: [PATCH 014/112] chore: migrating to aws-sdk-v2 go --- internal/service/imagebuilder/components_data_source.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/internal/service/imagebuilder/components_data_source.go b/internal/service/imagebuilder/components_data_source.go index 797efce2269..1e6f7a8dbaf 100644 --- a/internal/service/imagebuilder/components_data_source.go +++ b/internal/service/imagebuilder/components_data_source.go @@ -15,7 +15,6 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" - "sigs.k8s.io/kustomize/api/types" ) // @SDKDataSource("aws_imagebuilder_components", name="Components") @@ -57,7 +56,7 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*types.ComponentVersion + var results []*awstypes.ComponentVersion err := conn.ListComponentsPages(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { if page == nil { From efd667207d95d97a65c6e7da7813caaad422ab8d Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Thu, 29 Feb 2024 23:45:14 +0100 Subject: [PATCH 015/112] feat: migrated resources to v2 --- internal/service/imagebuilder/component.go | 2 +- .../service/imagebuilder/component_test.go | 7 +- .../imagebuilder/components_data_source.go | 20 +--- .../distribution_configuration.go | 110 +++++++----------- .../service/imagebuilder/image_pipeline.go | 8 +- internal/service/imagebuilder/image_recipe.go | 64 +++------- .../service/imagebuilder/lifecycle_policy.go | 32 ++--- internal/service/imagebuilder/status.go | 8 +- 8 files changed, 88 insertions(+), 163 deletions(-) diff --git a/internal/service/imagebuilder/component.go b/internal/service/imagebuilder/component.go index 90989a3aa45..ea7d304ce0f 100644 --- a/internal/service/imagebuilder/component.go +++ b/internal/service/imagebuilder/component.go @@ -166,7 +166,7 @@ func resourceComponentCreate(ctx context.Context, d *schema.ResourceData, meta i } if v, ok := d.GetOk("supported_os_versions"); ok && v.(*schema.Set).Len() > 0 { - input.SupportedOsVersions = flex.ExpandToStringSet(v.(*schema.Set)) + input.SupportedOsVersions = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("uri"); ok { diff --git a/internal/service/imagebuilder/component_test.go b/internal/service/imagebuilder/component_test.go index bf2f4ec566c..a74d421bb06 100644 --- a/internal/service/imagebuilder/component_test.go +++ b/internal/service/imagebuilder/component_test.go @@ -17,6 +17,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/names" @@ -314,13 +315,11 @@ func testAccCheckComponentDestroy(ctx context.Context) resource.TestCheckFunc { } output, err := conn.GetComponent(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { - continue + return nil } - if err != nil { - return fmt.Errorf("error getting Image Builder Component (%s): %w", rs.Primary.ID, err) + return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, "tfimagebuilder", rs.Primary.ID, err) } if output != nil { diff --git a/internal/service/imagebuilder/components_data_source.go b/internal/service/imagebuilder/components_data_source.go index 1e6f7a8dbaf..a3f170e0b52 100644 --- a/internal/service/imagebuilder/components_data_source.go +++ b/internal/service/imagebuilder/components_data_source.go @@ -56,23 +56,7 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*awstypes.ComponentVersion - - err := conn.ListComponentsPages(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, componentVersion := range page.ComponentVersionList { - if componentVersion == nil { - continue - } - - results = append(results, componentVersion) - } - - return !lastPage - }) + out, err := conn.ListComponents(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Components: %s", err) @@ -80,7 +64,7 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta var arns, names []string - for _, r := range results { + for _, r := range out.ComponentVersionList { arns = append(arns, aws.ToString(r.Arn)) names = append(names, aws.ToString(r.Name)) } diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 5616ea320ab..8d46968269d 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -425,7 +425,7 @@ func expandAMIDistributionConfiguration(tfMap map[string]interface{}) *awstypes. apiObject := &awstypes.AmiDistributionConfiguration{} if v, ok := tfMap["ami_tags"].(map[string]interface{}); ok && len(v) > 0 { - apiObject.AmiTags = flex.ExpandToStringMap(v) + apiObject.AmiTags = flex.ExpandStringValueMap(v) } if v, ok := tfMap["description"].(string); ok && v != "" { @@ -445,7 +445,7 @@ func expandAMIDistributionConfiguration(tfMap map[string]interface{}) *awstypes. } if v, ok := tfMap["target_account_ids"].(*schema.Set); ok && v.Len() > 0 { - apiObject.TargetAccountIds = flex.ExpandToStringSet(v) + apiObject.TargetAccountIds = flex.ExpandStringValueSet(v) } return apiObject @@ -459,7 +459,7 @@ func expandContainerDistributionConfiguration(tfMap map[string]interface{}) *aws apiObject := &awstypes.ContainerDistributionConfiguration{} if v, ok := tfMap["container_tags"].(*schema.Set); ok && v.Len() > 0 { - apiObject.ContainerTags = flex.ExpandToStringSet(v) + apiObject.ContainerTags = flex.ExpandStringValueSet(v) } if v, ok := tfMap["description"].(string); ok && v != "" { @@ -473,12 +473,12 @@ func expandContainerDistributionConfiguration(tfMap map[string]interface{}) *aws return apiObject } -func expandLaunchTemplateConfigurations(tfList []interface{}) []*awstypes.LaunchTemplateConfiguration { +func expandLaunchTemplateConfigurations(tfList []interface{}) []awstypes.LaunchTemplateConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*awstypes.LaunchTemplateConfiguration + var apiObjects []awstypes.LaunchTemplateConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -493,7 +493,7 @@ func expandLaunchTemplateConfigurations(tfList []interface{}) []*awstypes.Launch continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects @@ -523,7 +523,7 @@ func expandDistribution(tfMap map[string]interface{}) *awstypes.Distribution { } if v, ok := tfMap["license_configuration_arns"].(*schema.Set); ok && v.Len() > 0 { - apiObject.LicenseConfigurationArns = flex.ExpandToStringSet(v) + apiObject.LicenseConfigurationArns = flex.ExpandStringValueSet(v) } if v, ok := tfMap["region"].(string); ok && v != "" { @@ -533,12 +533,12 @@ func expandDistribution(tfMap map[string]interface{}) *awstypes.Distribution { return apiObject } -func expandDistributions(tfList []interface{}) []*awstypes.Distribution { +func expandDistributions(tfList []interface{}) []awstypes.Distribution { if len(tfList) == 0 { return nil } - var apiObjects []*awstypes.Distribution + var apiObjects []awstypes.Distribution for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -560,7 +560,7 @@ func expandDistributions(tfList []interface{}) []*awstypes.Distribution { continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects @@ -574,19 +574,19 @@ func expandLaunchPermissionConfiguration(tfMap map[string]interface{}) *awstypes apiObject := &awstypes.LaunchPermissionConfiguration{} if v, ok := tfMap["organization_arns"].(*schema.Set); ok && v.Len() > 0 { - apiObject.OrganizationArns = flex.ExpandToStringSet(v) + apiObject.OrganizationArns = flex.ExpandStringValueSet(v) } if v, ok := tfMap["organizational_unit_arns"].(*schema.Set); ok && v.Len() > 0 { - apiObject.OrganizationalUnitArns = flex.ExpandToStringSet(v) + apiObject.OrganizationalUnitArns = flex.ExpandStringValueSet(v) } if v, ok := tfMap["user_ids"].(*schema.Set); ok && v.Len() > 0 { - apiObject.UserIds = flex.ExpandToStringSet(v) + apiObject.UserIds = flex.ExpandStringValueSet(v) } if v, ok := tfMap["user_groups"].(*schema.Set); ok && v.Len() > 0 { - apiObject.UserGroups = flex.ExpandToStringSet(v) + apiObject.UserGroups = flex.ExpandStringValueSet(v) } return apiObject @@ -610,12 +610,12 @@ func expandTargetContainerRepository(tfMap map[string]interface{}) *awstypes.Tar return apiObject } -func expandFastLaunchConfigurations(tfList []interface{}) []*awstypes.FastLaunchConfiguration { +func expandFastLaunchConfigurations(tfList []interface{}) []awstypes.FastLaunchConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*awstypes.FastLaunchConfiguration + var apiObjects []awstypes.FastLaunchConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -630,7 +630,7 @@ func expandFastLaunchConfigurations(tfList []interface{}) []*awstypes.FastLaunch continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects @@ -648,7 +648,7 @@ func expandFastLaunchConfiguration(tfMap map[string]interface{}) *awstypes.FastL } if v, ok := tfMap["enabled"].(bool); ok { - apiObject.Enabled = aws.Bool(v) + apiObject.Enabled = v } if v, ok := tfMap["launch_template"].([]interface{}); ok && len(v) > 0 && v[0] != nil { @@ -656,7 +656,7 @@ func expandFastLaunchConfiguration(tfMap map[string]interface{}) *awstypes.FastL } if v, ok := tfMap["max_parallel_launches"].(int); ok && v != 0 { - apiObject.MaxParallelLaunches = aws.Int64(int64(v)) + apiObject.MaxParallelLaunches = aws.Int32(int32(v)) } if v, ok := tfMap["snapshot_configuration"].([]interface{}); ok && len(v) > 0 && v[0] != nil { @@ -696,7 +696,7 @@ func expandFastLaunchSnapshotConfiguration(tfMap map[string]interface{}) *awstyp apiObject := &awstypes.FastLaunchSnapshotConfiguration{} if v, ok := tfMap["target_resource_count"].(int); ok && v != 0 { - apiObject.TargetResourceCount = aws.Int64(int64(v)) + apiObject.TargetResourceCount = aws.Int32(int32(v)) } return apiObject @@ -714,7 +714,7 @@ func expandLaunchTemplateConfiguration(tfMap map[string]interface{}) *awstypes.L } if v, ok := tfMap["default"].(bool); ok { - apiObject.SetDefaultVersion = aws.Bool(v) + apiObject.SetDefaultVersion = v } if v, ok := tfMap["account_id"].(string); ok && v != "" { @@ -732,7 +732,7 @@ func flattenAMIDistributionConfiguration(apiObject *awstypes.AmiDistributionConf tfMap := map[string]interface{}{} if v := apiObject.AmiTags; v != nil { - tfMap["ami_tags"] = aws.ToStringMap(v) + tfMap["ami_tags"] = aws.StringMap(v) } if v := apiObject.Description; v != nil { @@ -752,7 +752,7 @@ func flattenAMIDistributionConfiguration(apiObject *awstypes.AmiDistributionConf } if v := apiObject.TargetAccountIds; v != nil { - tfMap["target_account_ids"] = aws.ToStringSlice(v) + tfMap["target_account_ids"] = aws.StringSlice(v) } return tfMap @@ -766,7 +766,7 @@ func flattenContainerDistributionConfiguration(apiObject *awstypes.ContainerDist tfMap := map[string]interface{}{} if v := apiObject.ContainerTags; v != nil { - tfMap["container_tags"] = aws.ToStringSlice(v) + tfMap["container_tags"] = aws.StringSlice(v) } if v := apiObject.Description; v != nil { @@ -780,7 +780,7 @@ func flattenContainerDistributionConfiguration(apiObject *awstypes.ContainerDist return tfMap } -func flattenLaunchTemplateConfigurations(apiObjects []*awstypes.LaunchTemplateConfiguration) []interface{} { +func flattenLaunchTemplateConfigurations(apiObjects []awstypes.LaunchTemplateConfiguration) []interface{} { if apiObjects == nil { return nil } @@ -788,21 +788,13 @@ func flattenLaunchTemplateConfigurations(apiObjects []*awstypes.LaunchTemplateCo var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenLaunchTemplateConfiguration(apiObject)) } return tfList } -func flattenDistribution(apiObject *awstypes.Distribution) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenDistribution(apiObject awstypes.Distribution) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.AmiDistributionConfiguration; v != nil { @@ -822,7 +814,7 @@ func flattenDistribution(apiObject *awstypes.Distribution) map[string]interface{ } if v := apiObject.LicenseConfigurationArns; v != nil { - tfMap["license_configuration_arns"] = aws.ToStringSlice(v) + tfMap["license_configuration_arns"] = aws.StringSlice(v) } if v := apiObject.Region; v != nil { @@ -832,7 +824,7 @@ func flattenDistribution(apiObject *awstypes.Distribution) map[string]interface{ return tfMap } -func flattenDistributions(apiObjects []*awstypes.Distribution) []interface{} { +func flattenDistributions(apiObjects []awstypes.Distribution) []interface{} { if len(apiObjects) == 0 { return nil } @@ -840,10 +832,6 @@ func flattenDistributions(apiObjects []*awstypes.Distribution) []interface{} { var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenDistribution(apiObject)) } @@ -858,19 +846,19 @@ func flattenLaunchPermissionConfiguration(apiObject *awstypes.LaunchPermissionCo tfMap := map[string]interface{}{} if v := apiObject.OrganizationArns; v != nil { - tfMap["organization_arns"] = aws.ToStringSlice(v) + tfMap["organization_arns"] = aws.StringSlice(v) } if v := apiObject.OrganizationalUnitArns; v != nil { - tfMap["organizational_unit_arns"] = aws.ToStringSlice(v) + tfMap["organizational_unit_arns"] = aws.StringSlice(v) } if v := apiObject.UserGroups; v != nil { - tfMap["user_groups"] = aws.ToStringSlice(v) + tfMap["user_groups"] = aws.StringSlice(v) } if v := apiObject.UserIds; v != nil { - tfMap["user_ids"] = aws.ToStringSlice(v) + tfMap["user_ids"] = aws.StringSlice(v) } return tfMap @@ -887,27 +875,19 @@ func flattenTargetContainerRepository(apiObject *awstypes.TargetContainerReposit tfMap["repository_name"] = aws.ToString(v) } - if v := apiObject.Service; v != nil { - tfMap["service"] = aws.ToString(v) - } + tfMap["service"] = string(apiObject.Service) return tfMap } -func flattenLaunchTemplateConfiguration(apiObject *awstypes.LaunchTemplateConfiguration) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenLaunchTemplateConfiguration(apiObject awstypes.LaunchTemplateConfiguration) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.LaunchTemplateId; v != nil { tfMap["launch_template_id"] = aws.ToString(v) } - if v := apiObject.SetDefaultVersion; v != nil { - tfMap["default"] = aws.ToBool(v) - } + tfMap["default"] = aws.Bool(apiObject.SetDefaultVersion) if v := apiObject.AccountId; v != nil { tfMap["account_id"] = aws.ToString(v) @@ -916,7 +896,7 @@ func flattenLaunchTemplateConfiguration(apiObject *awstypes.LaunchTemplateConfig return tfMap } -func flattenFastLaunchConfigurations(apiObjects []*awstypes.FastLaunchConfiguration) []interface{} { +func flattenFastLaunchConfigurations(apiObjects []awstypes.FastLaunchConfiguration) []interface{} { if apiObjects == nil { return nil } @@ -924,37 +904,27 @@ func flattenFastLaunchConfigurations(apiObjects []*awstypes.FastLaunchConfigurat var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenFastLaunchConfiguration(apiObject)) } return tfList } -func flattenFastLaunchConfiguration(apiObject *awstypes.FastLaunchConfiguration) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenFastLaunchConfiguration(apiObject awstypes.FastLaunchConfiguration) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.AccountId; v != nil { tfMap["account_id"] = aws.ToString(v) } - if v := apiObject.Enabled; v != nil { - tfMap["enabled"] = aws.ToBool(v) - } + tfMap["enabled"] = aws.Bool(apiObject.Enabled) if v := apiObject.LaunchTemplate; v != nil { tfMap["launch_template"] = []interface{}{flattenFastLaunchLaunchTemplateSpecification(v)} } if v := apiObject.MaxParallelLaunches; v != nil { - tfMap["max_parallel_launches"] = aws.ToInt64(v) + tfMap["max_parallel_launches"] = aws.ToInt32(v) } if v := apiObject.SnapshotConfiguration; v != nil { @@ -994,7 +964,7 @@ func flattenFastLaunchSnapshotConfiguration(apiObject *awstypes.FastLaunchSnapsh tfMap := map[string]interface{}{} if v := apiObject.TargetResourceCount; v != nil { - tfMap["target_resource_count"] = aws.ToInt64(v) + tfMap["target_resource_count"] = aws.ToInt32(v) } return tfMap diff --git a/internal/service/imagebuilder/image_pipeline.go b/internal/service/imagebuilder/image_pipeline.go index 37092979fdc..5acf66dd53f 100644 --- a/internal/service/imagebuilder/image_pipeline.go +++ b/internal/service/imagebuilder/image_pipeline.go @@ -521,7 +521,7 @@ func flattenECRConfiguration(apiObject *awstypes.EcrConfiguration) map[string]in } if v := apiObject.ContainerTags; v != nil { - tfMap["container_tags"] = aws.ToStringSlice(v) + tfMap["container_tags"] = aws.StringSlice(v) } return tfMap @@ -539,7 +539,7 @@ func flattenImageTestsConfiguration(apiObject *awstypes.ImageTestsConfiguration) } if v := apiObject.TimeoutMinutes; v != nil { - tfMap["timeout_minutes"] = aws.ToInt64(v) + tfMap["timeout_minutes"] = aws.ToInt32(v) } return tfMap @@ -552,9 +552,7 @@ func flattenSchedule(apiObject *awstypes.Schedule) map[string]interface{} { tfMap := map[string]interface{}{} - if v := apiObject.PipelineExecutionStartCondition; v != nil { - tfMap["pipeline_execution_start_condition"] = string(v) - } + tfMap["pipeline_execution_start_condition"] = string(apiObject.PipelineExecutionStartCondition) if v := apiObject.ScheduleExpression; v != nil { tfMap["schedule_expression"] = aws.ToString(v) diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index 435820e4459..cdb41187654 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -412,12 +412,12 @@ func expandComponentConfiguration(tfMap map[string]interface{}) *awstypes.Compon return apiObject } -func expandComponentParameters(tfList []interface{}) []*awstypes.ComponentParameter { +func expandComponentParameters(tfList []interface{}) []awstypes.ComponentParameter { if len(tfList) == 0 { return nil } - var apiObjects []*awstypes.ComponentParameter + var apiObjects []awstypes.ComponentParameter for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -432,7 +432,7 @@ func expandComponentParameters(tfList []interface{}) []*awstypes.ComponentParame continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects @@ -452,18 +452,18 @@ func expandComponentParameter(tfMap map[string]interface{}) *awstypes.ComponentP if v, ok := tfMap["value"].(string); ok && v != "" { // ImageBuilder API quirk // Even though Value is a slice, only one element is accepted. - apiObject.Value = aws.StringSlice([]string{v}) + apiObject.Value = []string{v} } return apiObject } -func expandComponentConfigurations(tfList []interface{}) []*awstypes.ComponentConfiguration { +func expandComponentConfigurations(tfList []interface{}) []awstypes.ComponentConfiguration { if len(tfList) == 0 { return nil } - var apiObjects []*awstypes.ComponentConfiguration + var apiObjects []awstypes.ComponentConfiguration for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -478,7 +478,7 @@ func expandComponentConfigurations(tfList []interface{}) []*awstypes.ComponentCo continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects @@ -552,12 +552,12 @@ func expandInstanceBlockDeviceMapping(tfMap map[string]interface{}) *awstypes.In return apiObject } -func expandInstanceBlockDeviceMappings(tfList []interface{}) []*awstypes.InstanceBlockDeviceMapping { +func expandInstanceBlockDeviceMappings(tfList []interface{}) []awstypes.InstanceBlockDeviceMapping { if len(tfList) == 0 { return nil } - var apiObjects []*awstypes.InstanceBlockDeviceMapping + var apiObjects []awstypes.InstanceBlockDeviceMapping for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -572,7 +572,7 @@ func expandInstanceBlockDeviceMappings(tfList []interface{}) []*awstypes.Instanc continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects @@ -592,11 +592,7 @@ func expandSystemsManagerAgent(tfMap map[string]interface{}) *awstypes.SystemsMa return apiObject } -func flattenComponentConfiguration(apiObject *awstypes.ComponentConfiguration) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenComponentConfiguration(apiObject awstypes.ComponentConfiguration) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.ComponentArn; v != nil { @@ -610,7 +606,7 @@ func flattenComponentConfiguration(apiObject *awstypes.ComponentConfiguration) m return tfMap } -func flattenComponentParameters(apiObjects []*awstypes.ComponentParameter) []interface{} { +func flattenComponentParameters(apiObjects []awstypes.ComponentParameter) []interface{} { if len(apiObjects) == 0 { return nil } @@ -618,21 +614,13 @@ func flattenComponentParameters(apiObjects []*awstypes.ComponentParameter) []int var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenComponentParameter(apiObject)) } return tfList } -func flattenComponentParameter(apiObject *awstypes.ComponentParameter) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenComponentParameter(apiObject awstypes.ComponentParameter) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.Name; v != nil { @@ -642,13 +630,13 @@ func flattenComponentParameter(apiObject *awstypes.ComponentParameter) map[strin if v := apiObject.Value; v != nil { // ImageBuilder API quirk // Even though Value is a slice, only one element is accepted. - tfMap["value"] = aws.ToStringSlice(v)[0] + tfMap["value"] = aws.StringSlice(v)[0] } return tfMap } -func flattenComponentConfigurations(apiObjects []*awstypes.ComponentConfiguration) []interface{} { +func flattenComponentConfigurations(apiObjects []awstypes.ComponentConfiguration) []interface{} { if len(apiObjects) == 0 { return nil } @@ -656,10 +644,6 @@ func flattenComponentConfigurations(apiObjects []*awstypes.ComponentConfiguratio var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenComponentConfiguration(apiObject)) } @@ -682,7 +666,7 @@ func flattenEBSInstanceBlockDeviceSpecification(apiObject *awstypes.EbsInstanceB } if v := apiObject.Iops; v != nil { - tfMap["iops"] = aws.ToInt64(v) + tfMap["iops"] = aws.ToInt32(v) } if v := apiObject.KmsKeyId; v != nil { @@ -701,18 +685,12 @@ func flattenEBSInstanceBlockDeviceSpecification(apiObject *awstypes.EbsInstanceB tfMap["volume_size"] = aws.ToInt32(v) } - if v := apiObject.VolumeType; v != nil { - tfMap["volume_type"] = awstypes.EbsVolumeType(v) - } + tfMap["volume_type"] = awstypes.EbsVolumeType(apiObject.VolumeType) return tfMap } -func flattenInstanceBlockDeviceMapping(apiObject *awstypes.InstanceBlockDeviceMapping) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenInstanceBlockDeviceMapping(apiObject awstypes.InstanceBlockDeviceMapping) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.DeviceName; v != nil { @@ -734,7 +712,7 @@ func flattenInstanceBlockDeviceMapping(apiObject *awstypes.InstanceBlockDeviceMa return tfMap } -func flattenInstanceBlockDeviceMappings(apiObjects []*awstypes.InstanceBlockDeviceMapping) []interface{} { +func flattenInstanceBlockDeviceMappings(apiObjects []awstypes.InstanceBlockDeviceMapping) []interface{} { if len(apiObjects) == 0 { return nil } @@ -742,10 +720,6 @@ func flattenInstanceBlockDeviceMappings(apiObjects []*awstypes.InstanceBlockDevi var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenInstanceBlockDeviceMapping(apiObject)) } diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 02c59a8c36a..82d3705436c 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -374,8 +374,8 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq resp.Diagnostics.Append(d...) state.ResourceSelection = resourceSelection - state.ResourceType = flex.ToStringToFramework(ctx, out.ResourceType) - state.Status = flex.ToStringToFramework(ctx, out.Status) + state.ResourceType = flex.StringValueToFramework(ctx, out.ResourceType) + state.Status = flex.StringValueToFramework(ctx, out.Status) resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } @@ -680,7 +680,7 @@ func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExcl } if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkToStringMap(ctx, tfObj.TagMap) + apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) } return &apiObject, diags @@ -712,15 +712,15 @@ func expandPolicyDetailExclusionRulesAmis(ctx context.Context, tfList []resource } if !tfObj.Regions.IsNull() { - apiObject.Regions = flex.ExpandFrameworkToStringList(ctx, tfObj.LastLaunched) + apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.LastLaunched) } if !tfObj.SharedAccounts.IsNull() { - apiObject.Regions = flex.ExpandFrameworkToStringList(ctx, tfObj.SharedAccounts) + apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.SharedAccounts) } if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkToStringMap(ctx, tfObj.TagMap) + apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) } return &apiObject, diags @@ -764,7 +764,7 @@ func expandResourceSelection(ctx context.Context, tfList []resourceResourceSelec } if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkToStringMap(ctx, tfObj.TagMap) + apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) } return &apiObject, diags @@ -836,7 +836,7 @@ func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolic } obj := map[string]attr.Value{ - "type": flex.ToStringToFramework(ctx, apiObject.Type), + "type": flex.StringValueToFramework(ctx, apiObject.Type), } if apiObject.IncludeResources != nil { @@ -889,10 +889,10 @@ func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolic } obj := map[string]attr.Value{ - "type": flex.ToStringToFramework(ctx, apiObject.Type), + "type": flex.StringValueToFramework(ctx, apiObject.Type), "value": flex.Int32ToFramework(ctx, apiObject.Value), "retain_at_least": flex.Int32ToFramework(ctx, apiObject.RetainAtLeast), - "unit": flex.ToStringToFramework(ctx, apiObject.Unit), + "unit": flex.StringValueToFramework(ctx, apiObject.Unit), } objVal, d := types.ObjectValue(resourceFilterAttrTypes, obj) @@ -923,7 +923,7 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy } if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkToStringMap(ctx, apiObject.TagMap) + obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) } objVal, d := types.ObjectValue(resourceExclusionRulesAttrTypes, obj) @@ -956,15 +956,15 @@ func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.Lifecycl } if apiObject.Regions != nil { - obj["regions"] = flex.FlattenFrameworkToStringList(ctx, apiObject.Regions) + obj["regions"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions) } if apiObject.SharedAccounts != nil { - obj["shared_accounts"] = flex.FlattenFrameworkToStringList(ctx, apiObject.SharedAccounts) + obj["shared_accounts"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts) } if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkToStringMap(ctx, apiObject.TagMap) + obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) } objVal, d := types.ObjectValue(resourceAmisAttrTypes, obj) @@ -986,7 +986,7 @@ func flattenExclusionRulesAmisLastLaunched(ctx context.Context, apiObject *awsty } obj := map[string]attr.Value{ - "unit": flex.ToStringToFramework(ctx, apiObject.Unit), + "unit": flex.StringValueToFramework(ctx, apiObject.Unit), "value": flex.Int32ToFramework(ctx, apiObject.Value), } @@ -1018,7 +1018,7 @@ func flattenResourceSelection(ctx context.Context, apiObject *awstypes.Lifecycle } if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkToStringMap(ctx, apiObject.TagMap) + obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) } objVal, d := types.ObjectValue(resourceResourceSelectionAttrTypes, obj) diff --git a/internal/service/imagebuilder/status.go b/internal/service/imagebuilder/status.go index 0394f753aa1..cf69f17a853 100644 --- a/internal/service/imagebuilder/status.go +++ b/internal/service/imagebuilder/status.go @@ -30,12 +30,12 @@ func statusImage(ctx context.Context, conn *imagebuilder.Client, imageBuildVersi return nil, string(awstypes.ImageStatusPending), nil } - status := aws.ToString(output.Image.State.Status) + status := output.Image.State.Status - if status == string(awstypes.ImageStatusFailed) { - return output.Image, status, fmt.Errorf("%s", aws.ToString(output.Image.State.Reason)) + if status == awstypes.ImageStatusFailed { + return output.Image, string(status), fmt.Errorf("%s", aws.ToString(output.Image.State.Reason)) } - return output.Image, status, nil + return output.Image, string(status), nil } } From 14990325d79d349ac26ce416f7c5b4cbd1a7b9f6 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 2 Mar 2024 16:43:34 +0100 Subject: [PATCH 016/112] chore: migrate to aws-sdk-go-v2 --- internal/service/imagebuilder/image_recipe_test.go | 5 +++-- internal/service/imagebuilder/wait.go | 2 +- internal/service/imagebuilder/workflow.go | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index 3c5f5021edb..dbc431a5d6b 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -12,6 +12,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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" @@ -46,7 +47,7 @@ func TestAccImageBuilderImageRecipe_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner"), acctest.CheckResourceAttrRegionalARNAccountID(resourceName, "parent_image", "imagebuilder", "aws", "image/amazon-linux-2-x86/x.x.x"), - resource.TestCheckResourceAttr(resourceName, "platform", imagebuilder.PlatformLinux), + resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), ), @@ -338,7 +339,7 @@ func TestAccImageBuilderImageRecipe_BlockDeviceMappingEBS_volumeTypeGP2(t *testi testAccCheckImageRecipeExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "block_device_mapping.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "block_device_mapping.*", map[string]string{ - "ebs.0.volume_type": string(types.EbsVolumeTypeGp2)), + "ebs.0.volume_type": string(types.EbsVolumeTypeGp2), }), ), }, diff --git a/internal/service/imagebuilder/wait.go b/internal/service/imagebuilder/wait.go index 79267d5dab3..3ed96553b39 100644 --- a/internal/service/imagebuilder/wait.go +++ b/internal/service/imagebuilder/wait.go @@ -13,7 +13,7 @@ import ( ) // waitImageStatusAvailable waits for an Image to return Available -func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string, timeout time.Duration) (*imagebuilder.Image, error) { +func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string, timeout time.Duration) (*awstypes.Image, error) { stateConf := &retry.StateChangeConf{ Pending: []string{ string(awstypes.ImageStatusBuilding), diff --git a/internal/service/imagebuilder/workflow.go b/internal/service/imagebuilder/workflow.go index b41e2cd76ce..b825e62e30c 100644 --- a/internal/service/imagebuilder/workflow.go +++ b/internal/service/imagebuilder/workflow.go @@ -88,7 +88,7 @@ func ResourceWorkflow() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateDiagFunc: enum.Validate[awstypes.Workflow](), + ValidateDiagFunc: enum.Validate[awstypes.WorkflowType](), }, "uri": { Type: schema.TypeString, @@ -116,7 +116,7 @@ func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta in ClientToken: aws.String(id.UniqueId()), Name: aws.String(d.Get("name").(string)), SemanticVersion: aws.String(d.Get("version").(string)), - Type: aws.String(d.Get("type").(string)), + Type: awstypes.WorkflowType(d.Get("type").(string)), Tags: getTagsIn(ctx), } From 124e0ace59ffb2800346b1c1623531087036a9cf Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 2 Mar 2024 22:00:52 +0100 Subject: [PATCH 017/112] chore: migrate to aws-sdk-go-v2 --- .../namevaluesfiltersv2/generators/servicefilters/main.go | 1 + internal/service/imagebuilder/components_data_source.go | 6 +++--- .../service/imagebuilder/container_recipes_data_source.go | 3 ++- .../imagebuilder/distribution_configurations_data_source.go | 3 ++- .../service/imagebuilder/image_pipelines_data_source.go | 3 ++- internal/service/imagebuilder/image_recipes_data_source.go | 3 ++- .../infrastructure_configurations_data_source.go | 3 ++- 7 files changed, 14 insertions(+), 8 deletions(-) diff --git a/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go b/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go index 88368f5110d..010775f099b 100644 --- a/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go +++ b/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go @@ -20,6 +20,7 @@ const filename = `service_filters_v2_gen.go` // Representing types such as []*ec2.Filter, []*rds.Filter, ... var sliceServiceNames = []string{ "secretsmanager", + "imagebuilder", } type TemplateData struct { diff --git a/internal/service/imagebuilder/components_data_source.go b/internal/service/imagebuilder/components_data_source.go index a3f170e0b52..2726ae850ea 100644 --- a/internal/service/imagebuilder/components_data_source.go +++ b/internal/service/imagebuilder/components_data_source.go @@ -14,7 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" - "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) // @SDKDataSource("aws_imagebuilder_components", name="Components") @@ -27,7 +27,7 @@ func DataSourceComponents() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "filter": namevaluesfilters.Schema(), + "filter": namevaluesfiltersv2.Schema(), "names": { Type: schema.TypeSet, Computed: true, @@ -53,7 +53,7 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } out, err := conn.ListComponents(ctx, input) diff --git a/internal/service/imagebuilder/container_recipes_data_source.go b/internal/service/imagebuilder/container_recipes_data_source.go index c73e583b758..a4abca88f86 100644 --- a/internal/service/imagebuilder/container_recipes_data_source.go +++ b/internal/service/imagebuilder/container_recipes_data_source.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) // @SDKDataSource("aws_imagebuilder_container_recipes", name="Container Recipes") @@ -53,7 +54,7 @@ func dataSourceContainerRecipesRead(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } var results []*awstypes.ContainerRecipeSummary diff --git a/internal/service/imagebuilder/distribution_configurations_data_source.go b/internal/service/imagebuilder/distribution_configurations_data_source.go index dd70a503893..d71f7b3d193 100644 --- a/internal/service/imagebuilder/distribution_configurations_data_source.go +++ b/internal/service/imagebuilder/distribution_configurations_data_source.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) // @SDKDataSource("aws_imagebuilder_distribution_configurations") @@ -43,7 +44,7 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res input := &imagebuilder.ListDistributionConfigurationsInput{} if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } var results []*awstypes.DistributionConfigurationSummary diff --git a/internal/service/imagebuilder/image_pipelines_data_source.go b/internal/service/imagebuilder/image_pipelines_data_source.go index 54c8a25ddde..7e9e92a053c 100644 --- a/internal/service/imagebuilder/image_pipelines_data_source.go +++ b/internal/service/imagebuilder/image_pipelines_data_source.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) // @SDKDataSource("aws_imagebuilder_image_pipelines") @@ -43,7 +44,7 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m input := &imagebuilder.ListImagePipelinesInput{} if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } var results []*awstypes.ImagePipeline diff --git a/internal/service/imagebuilder/image_recipes_data_source.go b/internal/service/imagebuilder/image_recipes_data_source.go index 8cd77610ece..ee5c065b5b2 100644 --- a/internal/service/imagebuilder/image_recipes_data_source.go +++ b/internal/service/imagebuilder/image_recipes_data_source.go @@ -15,6 +15,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) // @SDKDataSource("aws_imagebuilder_image_recipes", name="Image Recipes") @@ -53,7 +54,7 @@ func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } var results []*awstypes.ImageRecipeSummary diff --git a/internal/service/imagebuilder/infrastructure_configurations_data_source.go b/internal/service/imagebuilder/infrastructure_configurations_data_source.go index df469ee2649..f687f5d36d4 100644 --- a/internal/service/imagebuilder/infrastructure_configurations_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configurations_data_source.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) // @SDKDataSource("aws_imagebuilder_infrastructure_configurations") @@ -43,7 +44,7 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R input := &imagebuilder.ListInfrastructureConfigurationsInput{} if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfilters.New(v.(*schema.Set)).ImagebuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } var results []*awstypes.InfrastructureConfigurationSummary From 8cf23199e6fa66d1a67c70f12b19dd57afeb9e73 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 3 Mar 2024 00:43:40 +0100 Subject: [PATCH 018/112] feat: fixed namevaluesfiltersv2 code generator and tests --- .../generators/servicefilters/main.go | 9 +++-- .../imagebuilder_filters.go | 36 +++++++++++++++++++ .../name_values_filters_test.go | 9 ++--- .../imagebuilder/components_data_source.go | 2 +- .../container_recipes_data_source.go | 25 +++---------- ...distribution_configurations_data_source.go | 23 ++---------- internal/service/imagebuilder/generate.go | 2 +- internal/service/imagebuilder/image.go | 26 +++----------- .../image_pipelines_data_source.go | 23 ++---------- .../imagebuilder/image_recipes_data_source.go | 22 ++---------- ...frastructure_configurations_data_source.go | 26 +++----------- internal/service/imagebuilder/tags_gen.go | 1 - 12 files changed, 69 insertions(+), 135 deletions(-) create mode 100644 internal/generate/namevaluesfiltersv2/imagebuilder_filters.go diff --git a/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go b/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go index 010775f099b..8d8ac6f5cc5 100644 --- a/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go +++ b/internal/generate/namevaluesfiltersv2/generators/servicefilters/main.go @@ -83,10 +83,9 @@ var templateBody = ` package namevaluesfiltersv2 import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports + "github.com/aws/aws-sdk-go-v2/aws" {{- range .SliceServiceNames }} -{{- if eq . (. | FilterPackage) }} - {{ . }} -{{- end }} + {{ . | FilterPackage }} {{- end }} ) @@ -94,7 +93,7 @@ import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports {{- range .SliceServiceNames }} // {{ . | Title }}Filters returns {{ . }} service filters. -func (filters NameValuesFilters) {{ . | Title }}Filters() []*{{ . | FilterPackagePrefix }}.{{ . | FilterType }} { +func (filters NameValuesFilters) {{ . | Title }}Filters() []{{ . | FilterPackagePrefix }}.{{ . | FilterType }} { m := filters.Map() if len(m) == 0 { @@ -105,7 +104,7 @@ func (filters NameValuesFilters) {{ . | Title }}Filters() []*{{ . | FilterPackag for k, v := range m { filter := {{ . | FilterPackagePrefix }}.{{ . | FilterType }}{ - {{ . | FilterTypeNameField }}: { . | FilterPackagePrefix }}.FilterNameStringType(k), + {{ . | FilterTypeNameField }}: {{ . | FilterPackagePrefix }}.FilterNameStringType(k), {{ . | FilterTypeValuesField }}: v, } diff --git a/internal/generate/namevaluesfiltersv2/imagebuilder_filters.go b/internal/generate/namevaluesfiltersv2/imagebuilder_filters.go new file mode 100644 index 00000000000..896acfc4fc8 --- /dev/null +++ b/internal/generate/namevaluesfiltersv2/imagebuilder_filters.go @@ -0,0 +1,36 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +//go:build !generate +// +build !generate + +package namevaluesfiltersv2 + +import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports + "github.com/aws/aws-sdk-go-v2/aws" + imagebuildertypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" +) + +// []*SERVICE.Filter handling + +// ImagebuilderFilters returns imagebuilder service filters. +func (filters NameValuesFilters) ImagebuilderFilters() []imagebuildertypes.Filter { + m := filters.Map() + + if len(m) == 0 { + return nil + } + + result := make([]imagebuildertypes.Filter, 0, len(m)) + + for k, v := range m { + filter := imagebuildertypes.Filter{ + Name: aws.String(k), + Values: v, + } + + result = append(result, filter) + } + + return result +} diff --git a/internal/generate/namevaluesfiltersv2/name_values_filters_test.go b/internal/generate/namevaluesfiltersv2/name_values_filters_test.go index 5e98ab0ba72..94d0cdc4837 100644 --- a/internal/generate/namevaluesfiltersv2/name_values_filters_test.go +++ b/internal/generate/namevaluesfiltersv2/name_values_filters_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" + "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) func TestNameValuesFiltersMap(t *testing.T) { @@ -17,17 +18,17 @@ func TestNameValuesFiltersMap(t *testing.T) { testCases := []struct { name string - filters namevaluesfilters.NameValuesFilters + filters namevaluesfiltersv2.NameValuesFilters want map[string][]string }{ { name: "empty", - filters: namevaluesfilters.New(map[string][]string{}), + filters: namevaluesfiltersv2.New(map[string][]string{}), want: map[string][]string{}, }, { name: "empty_strings", - filters: namevaluesfilters.New(map[string][]string{ + filters: namevaluesfiltersv2.New(map[string][]string{ "name1": {""}, "name2": {"", ""}, }), @@ -35,7 +36,7 @@ func TestNameValuesFiltersMap(t *testing.T) { }, { name: "duplicates", - filters: namevaluesfilters.New(map[string][]string{ + filters: namevaluesfiltersv2.New(map[string][]string{ "name1": {"value1"}, "name2": {"value2a", "value2b", "", "value2a", "value2c", "value2c"}, }), diff --git a/internal/service/imagebuilder/components_data_source.go b/internal/service/imagebuilder/components_data_source.go index 2726ae850ea..c628b274660 100644 --- a/internal/service/imagebuilder/components_data_source.go +++ b/internal/service/imagebuilder/components_data_source.go @@ -53,7 +53,7 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImagebuilderFilters() } out, err := conn.ListComponents(ctx, input) diff --git a/internal/service/imagebuilder/container_recipes_data_source.go b/internal/service/imagebuilder/container_recipes_data_source.go index a4abca88f86..0f45ee1c850 100644 --- a/internal/service/imagebuilder/container_recipes_data_source.go +++ b/internal/service/imagebuilder/container_recipes_data_source.go @@ -14,7 +14,6 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" - "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) @@ -28,7 +27,7 @@ func DataSourceContainerRecipes() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "filter": namevaluesfilters.Schema(), + "filter": namevaluesfiltersv2.Schema(), "names": { Type: schema.TypeSet, Computed: true, @@ -54,26 +53,10 @@ func dataSourceContainerRecipesRead(ctx context.Context, d *schema.ResourceData, } if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*awstypes.ContainerRecipeSummary - - err := conn.ListContainerRecipesPages(ctx, input, func(page *imagebuilder.ListContainerRecipesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, containerRecipeSummary := range page.ContainerRecipeSummaryList { - if containerRecipeSummary == nil { - continue - } - - results = append(results, containerRecipeSummary) - } - - return !lastPage - }) + out, err := conn.ListContainerRecipes(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipes: %s", err) @@ -81,7 +64,7 @@ func dataSourceContainerRecipesRead(ctx context.Context, d *schema.ResourceData, var arns, names []string - for _, r := range results { + for _, r := range out.ContainerRecipeSummaryList { arns = append(arns, aws.ToString(r.Arn)) names = append(names, aws.ToString(r.Name)) } diff --git a/internal/service/imagebuilder/distribution_configurations_data_source.go b/internal/service/imagebuilder/distribution_configurations_data_source.go index d71f7b3d193..75453b01667 100644 --- a/internal/service/imagebuilder/distribution_configurations_data_source.go +++ b/internal/service/imagebuilder/distribution_configurations_data_source.go @@ -8,7 +8,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -44,26 +43,10 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res input := &imagebuilder.ListDistributionConfigurationsInput{} if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*awstypes.DistributionConfigurationSummary - - err := conn.ListDistributionConfigurationsPages(ctx, input, func(page *imagebuilder.ListDistributionConfigurationsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, distributionConfigurationSummary := range page.DistributionConfigurationSummaryList { - if distributionConfigurationSummary == nil { - continue - } - - results = append(results, distributionConfigurationSummary) - } - - return !lastPage - }) + out, err := conn.ListDistributionConfigurations(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Distribution Configurations: %s", err) @@ -71,7 +54,7 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res var arns, names []string - for _, r := range results { + for _, r := range out.DistributionConfigurationSummaryList { arns = append(arns, aws.ToString(r.Arn)) names = append(names, aws.ToString(r.Name)) } diff --git a/internal/service/imagebuilder/generate.go b/internal/service/imagebuilder/generate.go index 16f89fcdbab..7f42904673b 100644 --- a/internal/service/imagebuilder/generate.go +++ b/internal/service/imagebuilder/generate.go @@ -1,7 +1,7 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ListTags -KVTValues -ServiceTagsMap -UpdateTags +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -ListTags -KVTValues -ServiceTagsMap -UpdateTags -SkipTypesImp //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/imagebuilder/image.go b/internal/service/imagebuilder/image.go index 8f591ce06af..fcd8a793c50 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -396,11 +396,7 @@ func flattenOutputResources(apiObject *awstypes.OutputResources) map[string]inte return tfMap } -func flattenAMI(apiObject *awstypes.Ami) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenAMI(apiObject awstypes.Ami) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.AccountId; v != nil { @@ -426,7 +422,7 @@ func flattenAMI(apiObject *awstypes.Ami) map[string]interface{} { return tfMap } -func flattenAMIs(apiObjects []*awstypes.Ami) []interface{} { +func flattenAMIs(apiObjects []awstypes.Ami) []interface{} { if len(apiObjects) == 0 { return nil } @@ -434,25 +430,17 @@ func flattenAMIs(apiObjects []*awstypes.Ami) []interface{} { var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenAMI(apiObject)) } return tfList } -func flattenContainer(apiObject *awstypes.Container) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenContainer(apiObject awstypes.Container) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.ImageUris; v != nil { - tfMap["image_uris"] = aws.ToStringSlice(v) + tfMap["image_uris"] = aws.StringSlice(v) } if v := apiObject.Region; v != nil { @@ -462,7 +450,7 @@ func flattenContainer(apiObject *awstypes.Container) map[string]interface{} { return tfMap } -func flattenContainers(apiObjects []*awstypes.Container) []interface{} { +func flattenContainers(apiObjects []awstypes.Container) []interface{} { if len(apiObjects) == 0 { return nil } @@ -470,10 +458,6 @@ func flattenContainers(apiObjects []*awstypes.Container) []interface{} { var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenContainer(apiObject)) } diff --git a/internal/service/imagebuilder/image_pipelines_data_source.go b/internal/service/imagebuilder/image_pipelines_data_source.go index 7e9e92a053c..3768ff0a7bc 100644 --- a/internal/service/imagebuilder/image_pipelines_data_source.go +++ b/internal/service/imagebuilder/image_pipelines_data_source.go @@ -8,7 +8,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -44,26 +43,10 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m input := &imagebuilder.ListImagePipelinesInput{} if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*awstypes.ImagePipeline - - err := conn.ListImagePipelinesPages(ctx, input, func(page *imagebuilder.ListImagePipelinesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, imagePipeline := range page.ImagePipelineList { - if imagePipeline == nil { - continue - } - - results = append(results, imagePipeline) - } - - return !lastPage - }) + out, err := conn.ListImagePipelines(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Pipelines: %s", err) @@ -71,7 +54,7 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m var arns, names []string - for _, r := range results { + for _, r := range out.ImagePipelineList { arns = append(arns, aws.ToString(r.Arn)) names = append(names, aws.ToString(r.Name)) } diff --git a/internal/service/imagebuilder/image_recipes_data_source.go b/internal/service/imagebuilder/image_recipes_data_source.go index ee5c065b5b2..62e3896e863 100644 --- a/internal/service/imagebuilder/image_recipes_data_source.go +++ b/internal/service/imagebuilder/image_recipes_data_source.go @@ -54,26 +54,10 @@ func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, met } if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*awstypes.ImageRecipeSummary - - err := conn.ListImageRecipesPages(ctx, input, func(page *imagebuilder.ListImageRecipesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, imageRecipeSummary := range page.ImageRecipeSummaryList { - if imageRecipeSummary == nil { - continue - } - - results = append(results, imageRecipeSummary) - } - - return !lastPage - }) + out, err := conn.ListImageRecipes(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipes: %s", err) @@ -81,7 +65,7 @@ func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, met var arns, names []string - for _, r := range results { + for _, r := range out.ImageRecipeSummaryList { arns = append(arns, aws.ToString(r.Arn)) names = append(names, aws.ToString(r.Name)) } diff --git a/internal/service/imagebuilder/infrastructure_configurations_data_source.go b/internal/service/imagebuilder/infrastructure_configurations_data_source.go index f687f5d36d4..f0b3d945752 100644 --- a/internal/service/imagebuilder/infrastructure_configurations_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configurations_data_source.go @@ -8,12 +8,10 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" - "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfiltersv2" ) @@ -27,7 +25,7 @@ func DataSourceInfrastructureConfigurations() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "filter": namevaluesfilters.Schema(), + "filter": namevaluesfiltersv2.Schema(), "names": { Type: schema.TypeSet, Computed: true, @@ -44,26 +42,10 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R input := &imagebuilder.ListInfrastructureConfigurationsInput{} if v, ok := d.GetOk("filter"); ok { - input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() + input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImagebuilderFilters() } - var results []*awstypes.InfrastructureConfigurationSummary - - err := conn.ListInfrastructureConfigurationsPages(ctx, input, func(page *imagebuilder.ListInfrastructureConfigurationsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, infrastructureConfigurationSummary := range page.InfrastructureConfigurationSummaryList { - if infrastructureConfigurationSummary == nil { - continue - } - - results = append(results, infrastructureConfigurationSummary) - } - - return !lastPage - }) + out, err := conn.ListInfrastructureConfigurations(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Infrastructure Configurations: %s", err) @@ -71,7 +53,7 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R var arns, names []string - for _, r := range results { + for _, r := range out.InfrastructureConfigurationSummaryList { arns = append(arns, aws.ToString(r.Arn)) names = append(names, aws.ToString(r.Name)) } diff --git a/internal/service/imagebuilder/tags_gen.go b/internal/service/imagebuilder/tags_gen.go index 17b52ef00d8..553a9befa11 100644 --- a/internal/service/imagebuilder/tags_gen.go +++ b/internal/service/imagebuilder/tags_gen.go @@ -7,7 +7,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" From c66f2afc4cb3f969653cadb9fc684ed049b648cd Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Mon, 11 Mar 2024 22:53:30 +0100 Subject: [PATCH 019/112] feat: migrate imagebuilder sweepers to aws-sdk-go-v2 --- internal/service/imagebuilder/sweep.go | 378 +++++++++++-------------- 1 file changed, 170 insertions(+), 208 deletions(-) diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index b585c36c4b9..8fcbebfdad7 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -9,10 +9,11 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - "github.com/hashicorp/go-multierror" + "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/sweep" - "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv1" + "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv2" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func RegisterSweepers() { @@ -60,73 +61,51 @@ func sweepComponents(region string) error { } conn := client.ImageBuilderClient(ctx) - sweepResources := make([]sweep.Sweepable, 0) - var sweeperErrs *multierror.Error - input := &imagebuilder.ListComponentsInput{ - Owner: aws.String(imagebuilder.OwnershipSelf), + Owner: types.OwnershipSelf, } - err = conn.ListComponentsPages(ctx, input, func(page *imagebuilder.ListComponentsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, componentVersion := range page.ComponentVersionList { - if componentVersion == nil { - continue - } - - arn := aws.ToString(componentVersion.Arn) - input := &imagebuilder.ListComponentBuildVersionsInput{ - ComponentVersionArn: componentVersion.Arn, - } - err := conn.ListComponentBuildVersionsPages(ctx, input, func(page *imagebuilder.ListComponentBuildVersionsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + sweepResources := make([]sweep.Sweepable, 0) - for _, componentSummary := range page.ComponentSummaryList { - if componentSummary == nil { - continue - } + pages := imagebuilder.NewListComponentsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - arn := aws.ToString(componentSummary.Arn) + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Components sweep for %s: %s", region, err) + return nil + } - r := ResourceComponent() - d := r.Data(nil) - d.SetId(arn) + if err != nil { + return fmt.Errorf("error listing ImageBuilder Components (%s): %w", region, err) + } - sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) - } + for _, v := range page.ComponentVersionList { + arn := aws.ToString(v.Arn) - return !lastPage - }) + if tfresource.NotFound(err) { + continue + } if err != nil { - sweeperErr := fmt.Errorf("error listing Image Builder Component (%s) versions: %w", arn, err) - log.Printf("[ERROR] %s", sweeperErr) - sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) - continue + return fmt.Errorf("error reading ImageBuilder Components (%s): %w", arn, err) } - } - return !lastPage - }) + r := ResourceComponent() + d := r.Data(nil) + d.SetId(arn) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Component sweep for %s: %s", region, err) - return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors - } - if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Image Builder Components: %w", err)) + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } } - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Image Builder Components: %w", err)) + err = sweep.SweepOrchestrator(ctx, sweepResources) + + if err != nil { + return fmt.Errorf("error sweeping ImageBuilder Components (%s): %w", region, err) } - return sweeperErrs.ErrorOrNil() + return nil } func sweepDistributionConfigurations(region string) error { @@ -137,21 +116,32 @@ func sweepDistributionConfigurations(region string) error { } conn := client.ImageBuilderClient(ctx) + input := &imagebuilder.ListDistributionConfigurationsInput{} sweepResources := make([]sweep.Sweepable, 0) - var sweeperErrs *multierror.Error - input := &imagebuilder.ListDistributionConfigurationsInput{} - err = conn.ListDistributionConfigurationsPages(ctx, input, func(page *imagebuilder.ListDistributionConfigurationsOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := imagebuilder.NewListDistributionConfigurationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Distribution Configuration Summary sweep for %s: %s", region, err) + return nil } - for _, distributionConfigurationSummary := range page.DistributionConfigurationSummaryList { - if distributionConfigurationSummary == nil { + if err != nil { + return fmt.Errorf("error listing ImageBuilder Distribution Configuration Summary (%s): %w", region, err) + } + + for _, v := range page.DistributionConfigurationSummaryList { + arn := aws.ToString(v.Arn) + + if tfresource.NotFound(err) { continue } - arn := aws.ToString(distributionConfigurationSummary.Arn) + if err != nil { + return fmt.Errorf("error reading ImageBuilder Distribution Configuration Summary (%s): %w", arn, err) + } r := ResourceDistributionConfiguration() d := r.Data(nil) @@ -159,23 +149,15 @@ func sweepDistributionConfigurations(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } + } - return !lastPage - }) + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Distribution Configuration sweep for %s: %s", region, err) - return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors - } if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Image Builder Distribution Configurations: %w", err)) - } - - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Image Builder Distribution Configurations: %w", err)) + return fmt.Errorf("error sweeping ImageBuilder Distribution Configuration Summary (%s): %w", region, err) } - return sweeperErrs.ErrorOrNil() + return nil } func sweepImagePipelines(region string) error { @@ -186,21 +168,32 @@ func sweepImagePipelines(region string) error { } conn := client.ImageBuilderClient(ctx) + input := &imagebuilder.ListImagePipelinesInput{} sweepResources := make([]sweep.Sweepable, 0) - var sweeperErrs *multierror.Error - input := &imagebuilder.ListImagePipelinesInput{} - err = conn.ListImagePipelinesPages(ctx, input, func(page *imagebuilder.ListImagePipelinesOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := imagebuilder.NewListImagePipelinesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Image Pipelines sweep for %s: %s", region, err) + return nil } - for _, imagePipeline := range page.ImagePipelineList { - if imagePipeline == nil { + if err != nil { + return fmt.Errorf("error listing ImageBuilder Image Pipelines (%s): %w", region, err) + } + + for _, v := range page.ImagePipelineList { + arn := aws.ToString(v.Arn) + + if tfresource.NotFound(err) { continue } - arn := aws.ToString(imagePipeline.Arn) + if err != nil { + return fmt.Errorf("error reading ImageBuilder Image Pipelines (%s): %w", arn, err) + } r := ResourceImagePipeline() d := r.Data(nil) @@ -208,23 +201,15 @@ func sweepImagePipelines(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } + } - return !lastPage - }) + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Image Pipeline sweep for %s: %s", region, err) - return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors - } if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Image Builder Image Pipelines: %w", err)) + return fmt.Errorf("error sweeping ImageBuilder Image Pipelines (%s): %w", region, err) } - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Image Builder Image Pipelines: %w", err)) - } - - return sweeperErrs.ErrorOrNil() + return nil } func sweepImageRecipes(region string) error { @@ -235,23 +220,32 @@ func sweepImageRecipes(region string) error { } conn := client.ImageBuilderClient(ctx) + input := &imagebuilder.ListImageRecipesInput{} sweepResources := make([]sweep.Sweepable, 0) - var sweeperErrs *multierror.Error - input := &imagebuilder.ListImageRecipesInput{ - Owner: aws.String(imagebuilder.OwnershipSelf), - } - err = conn.ListImageRecipesPages(ctx, input, func(page *imagebuilder.ListImageRecipesOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := imagebuilder.NewListImageRecipesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Image Recipes sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error listing ImageBuilder Image Recipes (%s): %w", region, err) } - for _, imageRecipeSummary := range page.ImageRecipeSummaryList { - if imageRecipeSummary == nil { + for _, v := range page.ImageRecipeSummaryList { + arn := aws.ToString(v.Arn) + + if tfresource.NotFound(err) { continue } - arn := aws.ToString(imageRecipeSummary.Arn) + if err != nil { + return fmt.Errorf("error reading ImageBuilder Image Recipes (%s): %w", arn, err) + } r := ResourceImageRecipe() d := r.Data(nil) @@ -259,23 +253,15 @@ func sweepImageRecipes(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } + } - return !lastPage - }) + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Image Recipe sweep for %s: %s", region, err) - return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors - } if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Image Builder Image Recipes: %w", err)) - } - - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Image Builder Image Recipes: %w", err)) + return fmt.Errorf("error sweeping ImageBuilder Image Recipes (%s): %w", region, err) } - return sweeperErrs.ErrorOrNil() + return nil } func sweepContainerRecipes(region string) error { @@ -286,23 +272,32 @@ func sweepContainerRecipes(region string) error { } conn := client.ImageBuilderClient(ctx) + input := &imagebuilder.ListContainerRecipesInput{} sweepResources := make([]sweep.Sweepable, 0) - var sweeperErrs *multierror.Error - input := &imagebuilder.ListContainerRecipesInput{ - Owner: aws.String(imagebuilder.OwnershipSelf), - } - err = conn.ListContainerRecipesPages(ctx, input, func(page *imagebuilder.ListContainerRecipesOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := imagebuilder.NewListContainerRecipesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Container Recipes sweep for %s: %s", region, err) + return nil } - for _, containerRecipeSummary := range page.ContainerRecipeSummaryList { - if containerRecipeSummary == nil { + if err != nil { + return fmt.Errorf("error listing ImageBuilder Container Recipes (%s): %w", region, err) + } + + for _, v := range page.ContainerRecipeSummaryList { + arn := aws.ToString(v.Arn) + + if tfresource.NotFound(err) { continue } - arn := aws.ToString(containerRecipeSummary.Arn) + if err != nil { + return fmt.Errorf("error reading ImageBuilder Container Recipes (%s): %w", arn, err) + } r := ResourceContainerRecipe() d := r.Data(nil) @@ -310,23 +305,15 @@ func sweepContainerRecipes(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } + } - return !lastPage - }) + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Container Recipe sweep for %s: %s", region, err) - return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors - } if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Image Builder Container Recipes: %w", err)) + return fmt.Errorf("error sweeping ImageBuilder Container Recipes (%s): %w", region, err) } - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Image Builder Container Recipes: %w", err)) - } - - return sweeperErrs.ErrorOrNil() + return nil } func sweepImages(region string) error { @@ -338,76 +325,49 @@ func sweepImages(region string) error { } conn := client.ImageBuilderClient(ctx) + + input := &imagebuilder.ListImagesInput{} sweepResources := make([]sweep.Sweepable, 0) - var errs *multierror.Error - input := &imagebuilder.ListImagesInput{ - Owner: aws.String(imagebuilder.OwnershipSelf), - } + pages := imagebuilder.NewListImagesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - err = conn.ListImagesPages(ctx, input, func(page *imagebuilder.ListImagesOutput, lastPage bool) bool { - if page == nil { - return !lastPage + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Images sweep for %s: %s", region, err) + return nil } - for _, imageVersion := range page.ImageVersionList { - if imageVersion == nil { - continue - } + if err != nil { + return fmt.Errorf("error listing ImageBuilder Images (%s): %w", region, err) + } - // Retrieve the Image's Build Version ARNs required as input - // to the ResourceImage()'s Delete operation - // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/19851 - imageVersionArn := aws.ToString(imageVersion.Arn) + for _, v := range page.ImageVersionList { + arn := aws.ToString(v.Arn) - input := &imagebuilder.ListImageBuildVersionsInput{ - ImageVersionArn: imageVersion.Arn, + if tfresource.NotFound(err) { + continue } - err := conn.ListImageBuildVersionsPages(ctx, input, func(page *imagebuilder.ListImageBuildVersionsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, imageSummary := range page.ImageSummaryList { - if imageSummary == nil { - continue - } - - imageBuildVersionArn := aws.ToString(imageSummary.Arn) - - r := ResourceImage() - d := r.Data(nil) - d.SetId(imageBuildVersionArn) - - sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) - } - - return !lastPage - }) - if err != nil { - errs = multierror.Append(errs, fmt.Errorf("error listing Image Builder Image Build Versions for image (%s): %w", imageVersionArn, err)) + return fmt.Errorf("error reading ImageBuilder Images (%s): %w", arn, err) } - } - return !lastPage - }) + r := ResourceImage() + d := r.Data(nil) + d.SetId(arn) - if err != nil { - errs = multierror.Append(errs, fmt.Errorf("error listing Image Builder Images for %s: %w", region, err)) + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } } - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - errs = multierror.Append(errs, fmt.Errorf("error sweeping Image Builder Images for %s: %w", region, err)) - } + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Image sweep for %s: %s", region, err) - return nil + if err != nil { + return fmt.Errorf("error sweeping ImageBuilder Images (%s): %w", region, err) } - return errs.ErrorOrNil() + return nil } func sweepInfrastructureConfigurations(region string) error { @@ -418,22 +378,32 @@ func sweepInfrastructureConfigurations(region string) error { } conn := client.ImageBuilderClient(ctx) + input := &imagebuilder.ListInfrastructureConfigurationsInput{} sweepResources := make([]sweep.Sweepable, 0) - var sweeperErrs *multierror.Error - input := &imagebuilder.ListInfrastructureConfigurationsInput{} + pages := imagebuilder.NewListInfrastructureConfigurationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - err = conn.ListInfrastructureConfigurationsPages(ctx, input, func(page *imagebuilder.ListInfrastructureConfigurationsOutput, lastPage bool) bool { - if page == nil { - return !lastPage + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Infrastructure Configurations sweep for %s: %s", region, err) + return nil } - for _, infrastructureConfigurationSummary := range page.InfrastructureConfigurationSummaryList { - if infrastructureConfigurationSummary == nil { + if err != nil { + return fmt.Errorf("error listing ImageBuilder Infrastructure Configurations (%s): %w", region, err) + } + + for _, v := range page.InfrastructureConfigurationSummaryList { + arn := aws.ToString(v.Arn) + + if tfresource.NotFound(err) { continue } - arn := aws.ToString(infrastructureConfigurationSummary.Arn) + if err != nil { + return fmt.Errorf("error reading ImageBuilder Infrastructure Configurations (%s): %w", arn, err) + } r := ResourceInfrastructureConfiguration() d := r.Data(nil) @@ -441,21 +411,13 @@ func sweepInfrastructureConfigurations(region string) error { sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } + } - return !lastPage - }) + err = sweep.SweepOrchestrator(ctx, sweepResources) - if awsv1.SkipSweepError(err) { - log.Printf("[WARN] Skipping Image Builder Infrastructure Configuration sweep for %s: %s", region, err) - return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors - } if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Image Builder Infrastructure Configurations: %w", err)) - } - - if err := sweep.SweepOrchestrator(ctx, sweepResources); err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error sweeping Image Builder Infrastructure Configurations: %w", err)) + return fmt.Errorf("error sweeping ImageBuilder Infrastructure Configurations (%s): %w", region, err) } - return sweeperErrs.ErrorOrNil() + return nil } From c1f37cec4f3c4c4d3fb2cd05e72105b6a48dfe55 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Mon, 11 Mar 2024 22:58:28 +0100 Subject: [PATCH 020/112] chore: go mod tidy --- go.mod | 140 +-------------------------------------------------------- go.sum | 8 +--- 2 files changed, 3 insertions(+), 145 deletions(-) diff --git a/go.mod b/go.mod index c85173e3177..7ac93daee01 100644 --- a/go.mod +++ b/go.mod @@ -6,145 +6,6 @@ require ( github.com/ProtonMail/go-crypto v1.1.0-alpha.0 github.com/YakDriver/go-version v0.1.0 github.com/YakDriver/regexache v0.23.0 - github.com/aws/aws-sdk-go v1.50.26 - github.com/aws/aws-sdk-go-v2 v1.25.2 - github.com/aws/aws-sdk-go-v2/config v1.27.4 - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.15.2 - github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.16.6 - github.com/aws/aws-sdk-go-v2/service/accessanalyzer v1.28.1 - github.com/aws/aws-sdk-go-v2/service/account v1.16.1 - github.com/aws/aws-sdk-go-v2/service/acm v1.25.1 - github.com/aws/aws-sdk-go-v2/service/amp v1.25.1 - github.com/aws/aws-sdk-go-v2/service/appconfig v1.28.1 - github.com/aws/aws-sdk-go-v2/service/appfabric v1.7.1 - github.com/aws/aws-sdk-go-v2/service/appflow v1.41.1 - github.com/aws/aws-sdk-go-v2/service/apprunner v1.28.1 - github.com/aws/aws-sdk-go-v2/service/athena v1.40.1 - github.com/aws/aws-sdk-go-v2/service/auditmanager v1.32.1 - github.com/aws/aws-sdk-go-v2/service/batch v1.33.1 - github.com/aws/aws-sdk-go-v2/service/bedrock v1.7.1 - github.com/aws/aws-sdk-go-v2/service/bedrockagent v1.4.1 - github.com/aws/aws-sdk-go-v2/service/budgets v1.22.1 - github.com/aws/aws-sdk-go-v2/service/chimesdkmediapipelines v1.15.1 - github.com/aws/aws-sdk-go-v2/service/chimesdkvoice v1.14.1 - github.com/aws/aws-sdk-go-v2/service/cleanrooms v1.10.1 - github.com/aws/aws-sdk-go-v2/service/cloud9 v1.24.1 - github.com/aws/aws-sdk-go-v2/service/cloudcontrol v1.18.1 - github.com/aws/aws-sdk-go-v2/service/cloudfront v1.35.1 - github.com/aws/aws-sdk-go-v2/service/cloudfrontkeyvaluestore v1.4.1 - github.com/aws/aws-sdk-go-v2/service/cloudhsmv2 v1.21.1 - github.com/aws/aws-sdk-go-v2/service/cloudsearch v1.22.1 - github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.38.1 - github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.36.1 - github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.34.1 - github.com/aws/aws-sdk-go-v2/service/codeartifact v1.25.1 - github.com/aws/aws-sdk-go-v2/service/codebuild v1.30.1 - github.com/aws/aws-sdk-go-v2/service/codecatalyst v1.12.1 - github.com/aws/aws-sdk-go-v2/service/codecommit v1.22.1 - github.com/aws/aws-sdk-go-v2/service/codedeploy v1.25.1 - github.com/aws/aws-sdk-go-v2/service/codeguruprofiler v1.20.1 - github.com/aws/aws-sdk-go-v2/service/codegurureviewer v1.25.1 - github.com/aws/aws-sdk-go-v2/service/codepipeline v1.26.1 - github.com/aws/aws-sdk-go-v2/service/codestarconnections v1.24.1 - github.com/aws/aws-sdk-go-v2/service/codestarnotifications v1.22.1 - github.com/aws/aws-sdk-go-v2/service/comprehend v1.31.1 - github.com/aws/aws-sdk-go-v2/service/computeoptimizer v1.33.1 - github.com/aws/aws-sdk-go-v2/service/configservice v1.46.1 - github.com/aws/aws-sdk-go-v2/service/connectcases v1.15.1 - github.com/aws/aws-sdk-go-v2/service/controltower v1.13.1 - github.com/aws/aws-sdk-go-v2/service/costoptimizationhub v1.4.1 - github.com/aws/aws-sdk-go-v2/service/customerprofiles v1.36.1 - github.com/aws/aws-sdk-go-v2/service/directoryservice v1.24.1 - github.com/aws/aws-sdk-go-v2/service/docdbelastic v1.8.1 - github.com/aws/aws-sdk-go-v2/service/dynamodb v1.30.1 - github.com/aws/aws-sdk-go-v2/service/ec2 v1.149.1 - github.com/aws/aws-sdk-go-v2/service/ecr v1.27.1 - github.com/aws/aws-sdk-go-v2/service/ecs v1.41.1 - github.com/aws/aws-sdk-go-v2/service/eks v1.40.1 - github.com/aws/aws-sdk-go-v2/service/elasticache v1.37.1 - github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.30.1 - github.com/aws/aws-sdk-go-v2/service/emr v1.39.1 - github.com/aws/aws-sdk-go-v2/service/emrserverless v1.17.1 - github.com/aws/aws-sdk-go-v2/service/evidently v1.19.1 - github.com/aws/aws-sdk-go-v2/service/finspace v1.22.1 - github.com/aws/aws-sdk-go-v2/service/firehose v1.28.1 - github.com/aws/aws-sdk-go-v2/service/fis v1.23.1 - github.com/aws/aws-sdk-go-v2/service/glacier v1.22.1 - github.com/aws/aws-sdk-go-v2/service/groundstation v1.26.1 - github.com/aws/aws-sdk-go-v2/service/healthlake v1.23.1 - github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.1 - github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1 - github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.1 - github.com/aws/aws-sdk-go-v2/service/internetmonitor v1.12.1 - github.com/aws/aws-sdk-go-v2/service/ivschat v1.12.1 - github.com/aws/aws-sdk-go-v2/service/kafka v1.30.1 - github.com/aws/aws-sdk-go-v2/service/kendra v1.49.1 - github.com/aws/aws-sdk-go-v2/service/keyspaces v1.10.1 - github.com/aws/aws-sdk-go-v2/service/kinesis v1.27.1 - github.com/aws/aws-sdk-go-v2/service/lambda v1.53.1 - github.com/aws/aws-sdk-go-v2/service/launchwizard v1.3.1 - github.com/aws/aws-sdk-go-v2/service/lexmodelsv2 v1.42.1 - github.com/aws/aws-sdk-go-v2/service/lightsail v1.36.1 - github.com/aws/aws-sdk-go-v2/service/lookoutmetrics v1.27.1 - github.com/aws/aws-sdk-go-v2/service/m2 v1.12.1 - github.com/aws/aws-sdk-go-v2/service/mediaconnect v1.28.1 - github.com/aws/aws-sdk-go-v2/service/mediaconvert v1.52.1 - github.com/aws/aws-sdk-go-v2/service/medialive v1.48.1 - github.com/aws/aws-sdk-go-v2/service/mediapackage v1.30.1 - github.com/aws/aws-sdk-go-v2/service/mediapackagev2 v1.9.1 - github.com/aws/aws-sdk-go-v2/service/mediastore v1.20.1 - github.com/aws/aws-sdk-go-v2/service/mq v1.22.1 - github.com/aws/aws-sdk-go-v2/service/mwaa v1.26.1 - github.com/aws/aws-sdk-go-v2/service/oam v1.9.1 - github.com/aws/aws-sdk-go-v2/service/opensearchserverless v1.11.1 - github.com/aws/aws-sdk-go-v2/service/osis v1.8.1 - github.com/aws/aws-sdk-go-v2/service/pcaconnectorad v1.5.1 - github.com/aws/aws-sdk-go-v2/service/pipes v1.11.1 - github.com/aws/aws-sdk-go-v2/service/polly v1.39.1 - github.com/aws/aws-sdk-go-v2/service/pricing v1.27.1 - github.com/aws/aws-sdk-go-v2/service/qbusiness v1.4.1 - github.com/aws/aws-sdk-go-v2/service/qldb v1.21.1 - github.com/aws/aws-sdk-go-v2/service/rbin v1.16.1 - github.com/aws/aws-sdk-go-v2/service/rds v1.74.0 - github.com/aws/aws-sdk-go-v2/service/redshift v1.43.1 - github.com/aws/aws-sdk-go-v2/service/redshiftdata v1.25.1 - github.com/aws/aws-sdk-go-v2/service/redshiftserverless v1.17.1 - github.com/aws/aws-sdk-go-v2/service/rekognition v1.39.1 - github.com/aws/aws-sdk-go-v2/service/resourceexplorer2 v1.10.1 - github.com/aws/aws-sdk-go-v2/service/resourcegroups v1.21.1 - github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.21.1 - github.com/aws/aws-sdk-go-v2/service/rolesanywhere v1.8.1 - github.com/aws/aws-sdk-go-v2/service/route53domains v1.23.1 - github.com/aws/aws-sdk-go-v2/service/s3 v1.51.1 - github.com/aws/aws-sdk-go-v2/service/s3control v1.44.1 - github.com/aws/aws-sdk-go-v2/service/scheduler v1.8.1 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.1 - github.com/aws/aws-sdk-go-v2/service/securityhub v1.46.1 - github.com/aws/aws-sdk-go-v2/service/securitylake v1.12.1 - github.com/aws/aws-sdk-go-v2/service/servicecatalogappregistry v1.26.1 - github.com/aws/aws-sdk-go-v2/service/servicequotas v1.21.1 - github.com/aws/aws-sdk-go-v2/service/sesv2 v1.26.1 - github.com/aws/aws-sdk-go-v2/service/shield v1.25.1 - github.com/aws/aws-sdk-go-v2/service/signer v1.22.1 - github.com/aws/aws-sdk-go-v2/service/sns v1.29.1 - github.com/aws/aws-sdk-go-v2/service/sqs v1.31.1 - github.com/aws/aws-sdk-go-v2/service/ssm v1.49.1 - github.com/aws/aws-sdk-go-v2/service/ssmcontacts v1.22.1 - github.com/aws/aws-sdk-go-v2/service/ssmincidents v1.30.1 - github.com/aws/aws-sdk-go-v2/service/ssmsap v1.12.1 - github.com/aws/aws-sdk-go-v2/service/sso v1.20.1 - github.com/aws/aws-sdk-go-v2/service/ssoadmin v1.25.1 - github.com/aws/aws-sdk-go-v2/service/sts v1.28.1 - github.com/aws/aws-sdk-go-v2/service/swf v1.22.1 - github.com/aws/aws-sdk-go-v2/service/synthetics v1.24.1 - github.com/aws/aws-sdk-go-v2/service/timestreamwrite v1.25.1 - github.com/aws/aws-sdk-go-v2/service/transcribe v1.36.1 - github.com/aws/aws-sdk-go-v2/service/transfer v1.43.1 - github.com/aws/aws-sdk-go-v2/service/verifiedpermissions v1.10.1 - github.com/aws/aws-sdk-go-v2/service/vpclattice v1.7.1 - github.com/aws/aws-sdk-go-v2/service/wellarchitected v1.29.1 - github.com/aws/aws-sdk-go-v2/service/workspaces v1.38.1 - github.com/aws/aws-sdk-go-v2/service/xray v1.25.1 github.com/aws/aws-sdk-go v1.50.35 github.com/aws/aws-sdk-go-v2 v1.25.3 github.com/aws/aws-sdk-go-v2/config v1.27.7 @@ -214,6 +75,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/groundstation v1.26.2 github.com/aws/aws-sdk-go-v2/service/healthlake v1.23.2 github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.2 + github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1 github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.2 github.com/aws/aws-sdk-go-v2/service/internetmonitor v1.12.2 github.com/aws/aws-sdk-go-v2/service/ivschat v1.12.2 diff --git a/go.sum b/go.sum index 32420fe588e..61de7e287ba 100644 --- a/go.sum +++ b/go.sum @@ -174,14 +174,10 @@ github.com/aws/aws-sdk-go-v2/service/healthlake v1.23.2 h1:jiLwEWc9JClllIGdG49BS github.com/aws/aws-sdk-go-v2/service/healthlake v1.23.2/go.mod h1:FFus4E9VokPSCw5/KmfcBl5I5XMTVEfVKms0fdPzI6I= github.com/aws/aws-sdk-go-v2/service/iam v1.30.1 h1:sCLZjJpGNMeyhyudAhipabxqwZpP/jAQOvbEdy19t/k= github.com/aws/aws-sdk-go-v2/service/iam v1.30.1/go.mod h1:vc5DmJnsyyX6UpZwIKT2y1hEhzHoGDjONKhDcDwA49g= -github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.1 h1:cMpbBT+CTvA/1OqnthdTpaXuXWFOBalT5RdLhtoeDeE= -github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.1/go.mod h1:N5oCfOlt4oKVFU/HcVYBK3dUn6mxPgSXk5ev87mvfrM= -github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1 h1:5kP0+cOT2ApEUKUMM+zIP/fZpdmKeQa4Jl5iF8eHI9c= -github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1/go.mod h1:JUoAL2dg3oOHOv7/HB6r1z65cn9Fx34hGcMa0C4JjDc= -github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.1 h1:IZBvoT4DceXymN3gd5QfqiskD9WZ511ECL8yyByFtiA= -github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.1/go.mod h1:auZ223/ID3dhv7XU8NbSmOXBDd4acNJ427m/2NN/0Vg= github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.2 h1:1UQL8QlgDvGUwSKWhty8tbgv+QCzs/NAeCWbbuvxLDg= github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.2/go.mod h1:pH/6CBpgeQtIpuM4eDgf+OJDrZU+iG03xjy8vIRcI1k= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1 h1:5kP0+cOT2ApEUKUMM+zIP/fZpdmKeQa4Jl5iF8eHI9c= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.32.1/go.mod h1:JUoAL2dg3oOHOv7/HB6r1z65cn9Fx34hGcMa0C4JjDc= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.2 h1:/Tdn1+AYzUH4WVfDdrKc/JNOC/XP7txBHdVDYkLFlD0= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.2/go.mod h1:VrG1RiAI8qS4txEGSZBRVjsLdLlH9CP2UHPP3inKL9c= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.1 h1:EyBZibRTVAs6ECHZOw5/wlylS9OcTzwyjeQMudmREjE= From de643dfbbc42a3df7e834a9eb956bb7010477c9e Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Mon, 11 Mar 2024 23:03:13 +0100 Subject: [PATCH 021/112] chore: add 'ImageBuilder' to the test name --- internal/service/imagebuilder/lifecycle_policy_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 9311d2518db..7945807b8f5 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -21,7 +21,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func TestAccLifecyclePolicy_basic(t *testing.T) { +func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { ctx := acctest.Context(t) var lifecyclePolicy types.LifecyclePolicy resourceName := "aws_imagebuilder_lifecycle_policy.test" From 98fde5247f11b3b0cedf5a957f33709c00208957 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Mon, 11 Mar 2024 23:05:29 +0100 Subject: [PATCH 022/112] chore: use correct caps in func name --- .../service/imagebuilder/lifecycle_policy.go | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 82d3705436c..da12d972eea 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -665,13 +665,13 @@ func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExcl apiObject := awstypes.LifecyclePolicyDetailExclusionRules{} if !tfObj.AMIs.IsNull() { - var tfList []resourceAMIsData + var tfList []resourceAMISData diags.Append(tfObj.AMIs.ElementsAs(ctx, &tfList, false)...) if diags.HasError() { return nil, diags } - Amis, d := expandPolicyDetailExclusionRulesAmis(ctx, tfList) + Amis, d := expandPolicyDetailExclusionRulesAMIS(ctx, tfList) diags.Append(d...) if diags.HasError() { return nil, diags @@ -686,7 +686,7 @@ func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExcl return &apiObject, diags } -func expandPolicyDetailExclusionRulesAmis(ctx context.Context, tfList []resourceAMIsData) (*awstypes.LifecyclePolicyDetailExclusionRulesAmis, diag.Diagnostics) { +func expandPolicyDetailExclusionRulesAMIS(ctx context.Context, tfList []resourceAMISData) (*awstypes.LifecyclePolicyDetailExclusionRulesAmis, diag.Diagnostics) { var diags diag.Diagnostics if len(tfList) == 0 { @@ -708,7 +708,7 @@ func expandPolicyDetailExclusionRulesAmis(ctx context.Context, tfList []resource return nil, diags } - apiObject.LastLaunched = expandPolicyDetailExclusionRulesAmisLastLaunched(tfList) + apiObject.LastLaunched = expandPolicyDetailExclusionRulesAMISLastLaunched(tfList) } if !tfObj.Regions.IsNull() { @@ -726,7 +726,7 @@ func expandPolicyDetailExclusionRulesAmis(ctx context.Context, tfList []resource return &apiObject, diags } -func expandPolicyDetailExclusionRulesAmisLastLaunched(tfList []resourceLastLaunchedData) *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched { +func expandPolicyDetailExclusionRulesAMISLastLaunched(tfList []resourceLastLaunchedData) *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched { tfObj := tfList[0] apiObject := awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched{} @@ -938,7 +938,7 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmis) (types.List, diag.Diagnostics) { var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceAmisAttrTypes} + elemType := types.ObjectType{AttrTypes: resourceAMISAttrTypes} if apiObject == nil { return types.ListNull(elemType), diags @@ -949,7 +949,7 @@ func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.Lifecycl } if apiObject.LastLaunched != nil { - lastLaunched, d := flattenExclusionRulesAmisLastLaunched(ctx, apiObject.LastLaunched) + lastLaunched, d := flattenExclusionRulesAMISLastLaunched(ctx, apiObject.LastLaunched) diags.Append(d...) obj["last_launched"] = lastLaunched @@ -967,7 +967,7 @@ func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.Lifecycl obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) } - objVal, d := types.ObjectValue(resourceAmisAttrTypes, obj) + objVal, d := types.ObjectValue(resourceAMISAttrTypes, obj) diags.Append(d...) listVal, d := types.ListValue(elemType, []attr.Value{objVal}) @@ -977,7 +977,7 @@ func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.Lifecycl } -func flattenExclusionRulesAmisLastLaunched(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched) (types.List, diag.Diagnostics) { +func flattenExclusionRulesAMISLastLaunched(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched) (types.List, diag.Diagnostics) { var diags diag.Diagnostics elemType := types.ObjectType{AttrTypes: resourceLastLaunchedAttrTypes} @@ -1112,7 +1112,7 @@ type resourceExclusionRulesData struct { TagMap types.Map `tfsdk:"tag_map"` } -type resourceAMIsData struct { +type resourceAMISData struct { IsPublic types.Bool `tfsdk:"is_public"` LastLaunched types.List `tfsdk:"last_launched"` Regions types.List `tfsdk:"regions"` @@ -1150,11 +1150,11 @@ var resourceFilterAttrTypes = map[string]attr.Type{ } var resourceExclusionRulesAttrTypes = map[string]attr.Type{ - "amis": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceAmisAttrTypes}}, + "amis": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceAMISAttrTypes}}, "tag_map": types.MapType{ElemType: types.StringType}, } -var resourceAmisAttrTypes = map[string]attr.Type{ +var resourceAMISAttrTypes = map[string]attr.Type{ "is_public": types.BoolType, "last_launched": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceLastLaunchedAttrTypes}}, "regions": types.ListType{ElemType: types.StringType}, From 1015be48366285675663b1b5cdee3e532dbcde7a Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 09:38:13 +0100 Subject: [PATCH 023/112] chore: use enum.Slice --- internal/service/imagebuilder/wait.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/wait.go b/internal/service/imagebuilder/wait.go index 3ed96553b39..a2384804ddf 100644 --- a/internal/service/imagebuilder/wait.go +++ b/internal/service/imagebuilder/wait.go @@ -23,7 +23,7 @@ func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, im string(awstypes.ImageStatusPending), string(awstypes.ImageStatusTesting), }, - Target: []string{string(awstypes.ImageStatusAvailable)}, + Target: enum.Slice({string(awstypes.ImageStatusAvailable)}), Refresh: statusImage(ctx, conn, imageBuildVersionArn), Timeout: timeout, } From 24659bfeb73c840dcd3a39572307f3e0ac15dcb6 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 09:38:44 +0100 Subject: [PATCH 024/112] chore: fix caps --- internal/service/imagebuilder/lifecycle_policy.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index da12d972eea..feb8b199836 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -916,7 +916,7 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy obj := map[string]attr.Value{} if apiObject.Amis != nil { - amis, d := flattenExclusionRulesAmis(ctx, apiObject.Amis) + amis, d := flattenExclusionRulesAMIS(ctx, apiObject.Amis) diags.Append(d...) obj["amis"] = amis @@ -936,7 +936,7 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy } -func flattenExclusionRulesAmis(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmis) (types.List, diag.Diagnostics) { +func flattenExclusionRulesAMIS(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmis) (types.List, diag.Diagnostics) { var diags diag.Diagnostics elemType := types.ObjectType{AttrTypes: resourceAMISAttrTypes} From d96420085bdaa40ea2b8c6b9f2b6ff7ff08e1195 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 09:41:48 +0100 Subject: [PATCH 025/112] chore: fix dupe import --- internal/service/imagebuilder/image_recipe_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index dbc431a5d6b..f286174d2c6 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -334,7 +334,7 @@ func TestAccImageBuilderImageRecipe_BlockDeviceMappingEBS_volumeTypeGP2(t *testi CheckDestroy: testAccCheckImageRecipeDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(types.EbsVolumeTypeGp2)), + Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(awstypes.EbsVolumeTypeGp2)), Check: resource.ComposeTestCheckFunc( testAccCheckImageRecipeExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "block_device_mapping.#", "1"), @@ -757,7 +757,7 @@ func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc output, err := conn.GetImageRecipe(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { continue } From 1b725d43cfa4cca1d20000dd8075479794da28dd Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 09:43:01 +0100 Subject: [PATCH 026/112] bug: fix incorrect cast --- internal/service/imagebuilder/wait.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/wait.go b/internal/service/imagebuilder/wait.go index a2384804ddf..eb38366cc79 100644 --- a/internal/service/imagebuilder/wait.go +++ b/internal/service/imagebuilder/wait.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" ) // waitImageStatusAvailable waits for an Image to return Available @@ -23,7 +24,7 @@ func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, im string(awstypes.ImageStatusPending), string(awstypes.ImageStatusTesting), }, - Target: enum.Slice({string(awstypes.ImageStatusAvailable)}), + Target: enum.Slice(awstypes.ImageStatusAvailable), Refresh: statusImage(ctx, conn, imageBuildVersionArn), Timeout: timeout, } From 013ff6ab30370b5334c762b68ff5f76ddf3fe306 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 10:41:18 +0100 Subject: [PATCH 027/112] chore: add a role --- GNUmakefile | 2 +- .../imagebuilder/lifecycle_policy_test.go | 25 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/GNUmakefile b/GNUmakefile index e28a1d621d9..66a3e69f90b 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -386,7 +386,7 @@ testacc-lint-fix: ## Fix acceptance test linter findings @echo "Fixing acceptance tests with terrafmt" find $(SVC_DIR) -type f -name '*_test.go' \ | sort -u \ - | xargs -I {} terrafmt fmt --fmtcompat {} + | xargs -I {} ~/go/bin/terrafmt fmt --fmtcompat {} testacc-short: fmtcheck ## Run acceptace tests with the -short flag @echo "Running acceptance tests with -short flag" diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 7945807b8f5..4fb41e6004d 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -97,8 +97,31 @@ func testAccCheckLifecyclePolicyDestroy(ctx context.Context) resource.TestCheckF func testAccLifecyclePolicyConfig_basic(rName string) string { return fmt.Sprintf(` -resource "aws_imagebuilder_lifecycle_policy" "test" { +data "aws_partition" "current" {} + +resource "aws_iam_role" "test" { + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { + Service = "ec2.${data.aws_partition.current.dns_suffix}" + } + Sid = "" + }] + }) name = %[1]q } + +resource "aws_iam_instance_profile" "test" { + name = aws_iam_role.test.name + role = aws_iam_role.test.name + } + +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + execution_role = aws_iam_role.test.arn +} `, rName) } From a794aaa86d5574cf09f36c94130a2c13f1007947 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 10:42:24 +0100 Subject: [PATCH 028/112] chore: fix types --- internal/service/imagebuilder/image_recipe_test.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index f286174d2c6..1def02cb835 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -12,7 +12,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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" @@ -47,7 +46,7 @@ func TestAccImageBuilderImageRecipe_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner"), acctest.CheckResourceAttrRegionalARNAccountID(resourceName, "parent_image", "imagebuilder", "aws", "image/amazon-linux-2-x86/x.x.x"), - resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformLinux)), + resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), ), @@ -334,7 +333,7 @@ func TestAccImageBuilderImageRecipe_BlockDeviceMappingEBS_volumeTypeGP2(t *testi CheckDestroy: testAccCheckImageRecipeDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(awstypes.EbsVolumeTypeGp2)), + Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(types.EbsVolumeTypeGp2)), Check: resource.ComposeTestCheckFunc( testAccCheckImageRecipeExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "block_device_mapping.#", "1"), @@ -757,7 +756,7 @@ func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc output, err := conn.GetImageRecipe(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if errs.IsA[*types.ResourceNotFoundException](err) { continue } From e958a32ade5ea4ce4a934d0322fe4f5bb735d554 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Tue, 12 Mar 2024 13:07:31 +0100 Subject: [PATCH 029/112] fix: ci errors --- .../service/imagebuilder/lifecycle_policy.go | 4 ++-- .../imagebuilder/lifecycle_policy_test.go | 8 ++++---- internal/service/imagebuilder/wait.go | 16 ++++++++-------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index feb8b199836..eb4ab3da7e5 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -546,7 +546,7 @@ func expandPolicyDetails(ctx context.Context, tfList []resourcePolicyDetailsData return nil, diags } - filter, d := expandPolicyDetailFilter(ctx, tfList) + filter, d := expandPolicyDetailFilter(tfList) diags.Append(d...) if diags.HasError() { return nil, diags @@ -623,7 +623,7 @@ func expandPolicyDetailActionIncludeResources(tfList []resourceIncludeResourcesD return &apiObject } -func expandPolicyDetailFilter(ctx context.Context, tfList []resourceFilterData) (*awstypes.LifecyclePolicyDetailFilter, diag.Diagnostics) { +func expandPolicyDetailFilter(tfList []resourceFilterData) (*awstypes.LifecyclePolicyDetailFilter, diag.Diagnostics) { var diags diag.Diagnostics if len(tfList) == 0 { diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 4fb41e6004d..07437d3a897 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -115,10 +115,10 @@ resource "aws_iam_role" "test" { } resource "aws_iam_instance_profile" "test" { - name = aws_iam_role.test.name - role = aws_iam_role.test.name - } - + name = aws_iam_role.test.name + role = aws_iam_role.test.name +} + resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn diff --git a/internal/service/imagebuilder/wait.go b/internal/service/imagebuilder/wait.go index eb38366cc79..cc39a9c0bb8 100644 --- a/internal/service/imagebuilder/wait.go +++ b/internal/service/imagebuilder/wait.go @@ -16,14 +16,14 @@ import ( // waitImageStatusAvailable waits for an Image to return Available func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string, timeout time.Duration) (*awstypes.Image, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ - string(awstypes.ImageStatusBuilding), - string(awstypes.ImageStatusCreating), - string(awstypes.ImageStatusDistributing), - string(awstypes.ImageStatusIntegrating), - string(awstypes.ImageStatusPending), - string(awstypes.ImageStatusTesting), - }, + Pending: enum.Slice( + awstypes.ImageStatusBuilding, + awstypes.ImageStatusCreating, + awstypes.ImageStatusDistributing, + awstypes.ImageStatusIntegrating, + awstypes.ImageStatusPending, + awstypes.ImageStatusTesting, + ), Target: enum.Slice(awstypes.ImageStatusAvailable), Refresh: statusImage(ctx, conn, imageBuildVersionArn), Timeout: timeout, From c4a79aecf16842d1cfc7fe5e963e102d6eb35ce2 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 15 Mar 2024 21:22:41 +0100 Subject: [PATCH 030/112] feat: fix format and redundant conversions --- internal/service/imagebuilder/image_recipe.go | 18 +++---------- .../service/imagebuilder/image_recipe_test.go | 2 +- .../service/imagebuilder/lifecycle_policy.go | 25 +++---------------- 3 files changed, 9 insertions(+), 36 deletions(-) diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index cdb41187654..bd092e28520 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -526,12 +526,8 @@ func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *aw return apiObject } -func expandInstanceBlockDeviceMapping(tfMap map[string]interface{}) *awstypes.InstanceBlockDeviceMapping { - if tfMap == nil { - return nil - } - - apiObject := &awstypes.InstanceBlockDeviceMapping{} +func expandInstanceBlockDeviceMapping(tfMap map[string]interface{}) awstypes.InstanceBlockDeviceMapping { + apiObject := awstypes.InstanceBlockDeviceMapping{} if v, ok := tfMap["device_name"].(string); ok && v != "" { apiObject.DeviceName = aws.String(v) @@ -566,13 +562,7 @@ func expandInstanceBlockDeviceMappings(tfList []interface{}) []awstypes.Instance continue } - apiObject := expandInstanceBlockDeviceMapping(tfMap) - - if apiObject == nil { - continue - } - - apiObjects = append(apiObjects, *apiObject) + apiObjects = append(apiObjects, expandInstanceBlockDeviceMapping(tfMap)) } return apiObjects @@ -685,7 +675,7 @@ func flattenEBSInstanceBlockDeviceSpecification(apiObject *awstypes.EbsInstanceB tfMap["volume_size"] = aws.ToInt32(v) } - tfMap["volume_type"] = awstypes.EbsVolumeType(apiObject.VolumeType) + tfMap["volume_type"] = apiObject.VolumeType return tfMap } diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index 1def02cb835..17eb65241ec 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -756,7 +756,7 @@ func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc output, err := conn.GetImageRecipe(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, "ResourceNotFoundException", "cannot be found") { continue } diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index eb4ab3da7e5..ff85362c01c 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -396,7 +396,6 @@ func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.Updat !plan.ResourceSelection.Equal(state.ResourceSelection) || !plan.ResourceType.Equal(state.ResourceType) || !plan.Status.Equal(state.Status) { - in := &imagebuilder.UpdateLifecyclePolicyInput{ ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), @@ -546,12 +545,7 @@ func expandPolicyDetails(ctx context.Context, tfList []resourcePolicyDetailsData return nil, diags } - filter, d := expandPolicyDetailFilter(tfList) - diags.Append(d...) - if diags.HasError() { - return nil, diags - } - apiObject.Filter = filter + apiObject.Filter = expandPolicyDetailFilter(tfList) } if !policyDetail.ExclusionRules.IsNull() { @@ -623,11 +617,9 @@ func expandPolicyDetailActionIncludeResources(tfList []resourceIncludeResourcesD return &apiObject } -func expandPolicyDetailFilter(tfList []resourceFilterData) (*awstypes.LifecyclePolicyDetailFilter, diag.Diagnostics) { - var diags diag.Diagnostics - +func expandPolicyDetailFilter(tfList []resourceFilterData) *awstypes.LifecyclePolicyDetailFilter { if len(tfList) == 0 { - return nil, diags + return nil } tfObj := tfList[0] @@ -650,7 +642,7 @@ func expandPolicyDetailFilter(tfList []resourceFilterData) (*awstypes.LifecycleP apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Type.ValueString()) } - return &apiObject, diags + return &apiObject } func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExclusionRulesData) (*awstypes.LifecyclePolicyDetailExclusionRules, diag.Diagnostics) { @@ -784,7 +776,6 @@ func expandResourceSelectionRecipes(tfList []resourceRecipesData) []awstypes.Lif } apiResult = append(apiResult, apiObject) - } return apiResult } @@ -853,7 +844,6 @@ func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolic diags.Append(d...) return listVal, diags - } func flattenIncludeResources(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailActionIncludeResources) (types.List, diag.Diagnostics) { @@ -877,7 +867,6 @@ func flattenIncludeResources(ctx context.Context, apiObject *awstypes.LifecycleP diags.Append(d...) return listVal, diags - } func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailFilter) (types.List, diag.Diagnostics) { @@ -902,7 +891,6 @@ func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolic diags.Append(d...) return listVal, diags - } func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRules) (types.List, diag.Diagnostics) { @@ -933,7 +921,6 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy diags.Append(d...) return listVal, diags - } func flattenExclusionRulesAMIS(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmis) (types.List, diag.Diagnostics) { @@ -974,7 +961,6 @@ func flattenExclusionRulesAMIS(ctx context.Context, apiObject *awstypes.Lifecycl diags.Append(d...) return listVal, diags - } func flattenExclusionRulesAMISLastLaunched(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched) (types.List, diag.Diagnostics) { @@ -997,7 +983,6 @@ func flattenExclusionRulesAMISLastLaunched(ctx context.Context, apiObject *awsty diags.Append(d...) return listVal, diags - } func flattenResourceSelection(ctx context.Context, apiObject *awstypes.LifecyclePolicyResourceSelection) (types.List, diag.Diagnostics) { @@ -1028,7 +1013,6 @@ func flattenResourceSelection(ctx context.Context, apiObject *awstypes.Lifecycle diags.Append(d...) return listVal, diags - } func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.LifecyclePolicyResourceSelectionRecipe) (types.Set, diag.Diagnostics) { @@ -1058,7 +1042,6 @@ func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.L diags.Append(d...) return listVal, diags - } type resourceLifecyclePolicyData struct { From cab8852bca65c7a4d2ff6733cab527e85bb71b35 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 15 Mar 2024 21:46:38 +0100 Subject: [PATCH 031/112] feat: fixed resource not found exception --- internal/service/imagebuilder/component_test.go | 6 ++++-- internal/service/imagebuilder/consts.go | 2 ++ internal/service/imagebuilder/container_recipe_test.go | 2 +- .../service/imagebuilder/distribution_configuration_test.go | 3 +-- internal/service/imagebuilder/image_pipeline_test.go | 2 +- internal/service/imagebuilder/image_recipe_test.go | 2 +- internal/service/imagebuilder/image_test.go | 2 +- .../imagebuilder/infrastructure_configuration_test.go | 3 +-- internal/service/imagebuilder/workflow_test.go | 2 +- 9 files changed, 13 insertions(+), 11 deletions(-) diff --git a/internal/service/imagebuilder/component_test.go b/internal/service/imagebuilder/component_test.go index a74d421bb06..d7963bcac58 100644 --- a/internal/service/imagebuilder/component_test.go +++ b/internal/service/imagebuilder/component_test.go @@ -315,9 +315,11 @@ func testAccCheckComponentDestroy(ctx context.Context) resource.TestCheckFunc { } output, err := conn.GetComponent(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { - return nil + + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + continue } + if err != nil { return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, "tfimagebuilder", rs.Primary.ID, err) } diff --git a/internal/service/imagebuilder/consts.go b/internal/service/imagebuilder/consts.go index 1d85561bd79..7e63a79494d 100644 --- a/internal/service/imagebuilder/consts.go +++ b/internal/service/imagebuilder/consts.go @@ -9,4 +9,6 @@ import ( const ( propagationTimeout = 2 * time.Minute + + ResourceNotFoundException = "ResourceNotFoundException" ) diff --git a/internal/service/imagebuilder/container_recipe_test.go b/internal/service/imagebuilder/container_recipe_test.go index 8679d625a2b..dd5e2c518e6 100644 --- a/internal/service/imagebuilder/container_recipe_test.go +++ b/internal/service/imagebuilder/container_recipe_test.go @@ -710,7 +710,7 @@ func testAccCheckContainerRecipeDestroy(ctx context.Context) resource.TestCheckF output, err := conn.GetContainerRecipe(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } diff --git a/internal/service/imagebuilder/distribution_configuration_test.go b/internal/service/imagebuilder/distribution_configuration_test.go index b87e98154bf..50b9561c76f 100644 --- a/internal/service/imagebuilder/distribution_configuration_test.go +++ b/internal/service/imagebuilder/distribution_configuration_test.go @@ -10,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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" @@ -928,7 +927,7 @@ func testAccCheckDistributionConfigurationDestroy(ctx context.Context) resource. output, err := conn.GetDistributionConfiguration(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } diff --git a/internal/service/imagebuilder/image_pipeline_test.go b/internal/service/imagebuilder/image_pipeline_test.go index 2d4191bbfef..893ec52bacd 100644 --- a/internal/service/imagebuilder/image_pipeline_test.go +++ b/internal/service/imagebuilder/image_pipeline_test.go @@ -660,7 +660,7 @@ func testAccCheckImagePipelineDestroy(ctx context.Context) resource.TestCheckFun output, err := conn.GetImagePipeline(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index 17eb65241ec..280a87bf841 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -756,7 +756,7 @@ func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc output, err := conn.GetImageRecipe(ctx, input) - if errs.MessageContains(err, "ResourceNotFoundException", "cannot be found") { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } diff --git a/internal/service/imagebuilder/image_test.go b/internal/service/imagebuilder/image_test.go index 1d1ac32b868..a491d61622a 100644 --- a/internal/service/imagebuilder/image_test.go +++ b/internal/service/imagebuilder/image_test.go @@ -336,7 +336,7 @@ func testAccCheckImageDestroy(ctx context.Context) resource.TestCheckFunc { output, err := conn.GetImage(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } diff --git a/internal/service/imagebuilder/infrastructure_configuration_test.go b/internal/service/imagebuilder/infrastructure_configuration_test.go index c79063ec708..abd51477546 100644 --- a/internal/service/imagebuilder/infrastructure_configuration_test.go +++ b/internal/service/imagebuilder/infrastructure_configuration_test.go @@ -10,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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" @@ -594,7 +593,7 @@ func testAccCheckInfrastructureConfigurationDestroy(ctx context.Context) resourc output, err := conn.GetInfrastructureConfiguration(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } diff --git a/internal/service/imagebuilder/workflow_test.go b/internal/service/imagebuilder/workflow_test.go index ca4ed6cf27c..b1175a73c30 100644 --- a/internal/service/imagebuilder/workflow_test.go +++ b/internal/service/imagebuilder/workflow_test.go @@ -253,7 +253,7 @@ func testAccCheckWorkflowDestroy(ctx context.Context) resource.TestCheckFunc { output, err := conn.GetWorkflow(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { continue } From 436daf54cf7af6afd49168b6807e5e99b4c2b7cb Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 21:50:42 +0100 Subject: [PATCH 032/112] Create imagebuilder_lifecycle_policy.html.markdown --- ...magebuilder_lifecycle_policy.html.markdown | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 website/docs/r/imagebuilder_lifecycle_policy.html.markdown diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown new file mode 100644 index 00000000000..03ea3595866 --- /dev/null +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -0,0 +1,138 @@ +--- +subcategory: "EC2 Image Builder" +layout: "aws" +page_title: "AWS: aws_imagebuilder_lifecycle_policy" +description: |- + Manages an Image Builder Lifecycle Policy +--- + +# Resource: aws_imagebuilder_lifecycle_policy + +Manages an Image Builder Lifecycle Policy. + +## Example Usage + +```terraform +resource "aws_imagebuilder_lifecycle_policy" "example" { +} +``` + +## Argument Reference + +The following arguments are required: + +* `name` - (Required) The name of the lifecycle policy to create. +* `resource_type` - (Required) The type of Image Builder resource that the lifecycle policy applies to. +* `execution_role` - (Required) The name or Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. +* `policy_details` - (Required) Configuration block with policy details. Detailed below. +* `resource_selection` - (Required) Selection criteria for the resources that the lifecycle policy applies to. Detailed below. + +The following arguments are optional: + +* `description` - (Optional) description for the lifecycle policy. +* `tags` - (Optional) Key-value map of resource tags to assign to the configuration. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/ + +### policy_details + +The following arguments are required: + +* `action` - (Required) Configuration details for the policy action. +* `filter` - (Required) Specifies the resources that the lifecycle policy applies to. + +The following arguments are optional: + +* `exclusion_rules` - (Optional) Additional rules to specify resources that should be exempt from policy actions. + +### action + +The following arguments are required: + +* `type` - (Required) Specifies the lifecycle action to take. + +The following arguments are optional: + +* `include_resources` - (Optional) Specifies the resources that the lifecycle policy applies to. Detailed below. + +### include_resources + +The following arguments are optional: + +* `amis` - (Optional) Specifies whether the lifecycle action should apply to distributed AMIs. +* `containers` - (Optional) Specifies whether the lifecycle action should apply to distributed containers. +* `snapshots` - (Optional) Specifies whether the lifecycle action should apply to snapshots associated with distributed AMIs. + +### filter + +The following arguments are required: + +* `type` - (Required) Filter resources based on either age or count. +* `value` - (Required) The number of units for the time period or for the count. For example, a value of 6 might refer to six months or six AMIs. + +The following arguments are optional: + +* `retain_at_least` - (Optional) For age-based filters, this is the number of resources to keep on hand after the lifecycle DELETE action is applied. Impacted resources are only deleted if you have more than this number of resources. If you have fewer resources than this number, the impacted resource is not deleted. +* `unit` - (Optional) Defines the unit of time that the lifecycle policy uses to determine impacted resources. This is required for age-based rules. + +### exclusion_rules + +The following arguments are optional: + +* `amis` - (Optional) Lists configuration values that apply to AMIs that Image Builder should exclude from the lifecycle action. Detailed below. +* `tag_map` - (Optional) Contains a list of tags that Image Builder uses to skip lifecycle actions for Image Builder image resources that have them. + +### amis + +The following arguments are optional: + +* `is_public` - (Optional) Configures whether public AMIs are excluded from the lifecycle action. +* `last_launched` - (Optional) Specifies configuration details for Image Builder to exclude the most recent resources from lifecycle actions. Detailed below. +* `regions` - (Optional) Configures AWS Regions that are excluded from the lifecycle action. +* `shared_accounts` - Specifies AWS accounts whose resources are excluded from the lifecycle action. +* `tag_map` - (Optional) Lists tags that should be excluded from lifecycle actions for the AMIs that have them. + +### last_launched + +The following arguments are required: + +* `unit` - (Required) Defines the unit of time that the lifecycle policy uses to calculate elapsed time since the last instance launched from the AMI. For example: days, weeks, months, or years. +* `value` - (Required) The integer number of units for the time period. For example 6 (months). + +### resource_selection + +The following arguments are optional: + +* `recipes` - (Optional) A list of recipes that are used as selection criteria for the output images that the lifecycle policy applies to. Detailed below. +* `tag_map` - (Optional) A list of tags that are used as selection criteria for the Image Builder image resources that the lifecycle policy applies to. + +### recipes + +The following arguments are required: + +* `name` - (Required) The name of an Image Builder recipe that the lifecycle policy uses for resource selection. +* `semantic_version` - (Required) The version of the Image Builder recipe specified by the name field. + +## Attribute Reference + +This resource exports the following attributes in addition to the arguments above: + +* `id` - Amazon Resource Name (ARN) of the lifecycle policy. +* `arn` - Amazon Resource Name (ARN) of the lifecycle policy. +* `status` - The status of the lifecycle policy. +* `tags_all` - A map of tags assigned to the resource, including those inherited from the provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block). + +## Import + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import `aws_imagebuilder_lifecycle_policy` using the Amazon Resource Name (ARN). For example: + +```terraform +import { + to = aws_imagebuilder_lifecycle_policy.example + id = "arn:aws:imagebuilder:us-east-1:123456789012:lifecycle-policy/example" +} +``` + +Using `terraform import`, import `aws_imagebuilder_lifecycle_policy` using the Amazon Resource Name (ARN). For example: + +```console +% terraform import aws_imagebuilder_lifecycle_policy.example arn:aws:imagebuilder:us-east-1:123456789012:lifecycle-policy/example +``` From 92a5e532a48c0adb4d797d1fe07f314b4357bf70 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 21:54:44 +0100 Subject: [PATCH 033/112] chore: add 'resource_type' and 'policy_details' to test --- internal/service/imagebuilder/lifecycle_policy_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 07437d3a897..71286c26922 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -122,6 +122,16 @@ resource "aws_iam_instance_profile" "test" { resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = "DELETE" + } + filter { + ype = "AGE" + value = 6 + } + } } `, rName) } From 1087365984e7b1ff1b6280147cc083ca156f7474 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 22:54:22 +0100 Subject: [PATCH 034/112] chore: lint acc --- .../imagebuilder/lifecycle_policy_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 71286c26922..d7ac5cc1c93 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -122,15 +122,15 @@ resource "aws_iam_instance_profile" "test" { resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn - resource_type = "AMI_IMAGE" + resource_type = "AMI_IMAGE" policy_details { - action { - type = "DELETE" - } - filter { - ype = "AGE" - value = 6 - } + action { + type = "DELETE" + } + filter { + ype = "AGE" + value = 6 + } } } `, rName) From 68e7856dcf3695d225e665b11cfa71d0c3a9aaf7 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 22:54:45 +0100 Subject: [PATCH 035/112] chore: fix typo --- internal/service/imagebuilder/lifecycle_policy_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index d7ac5cc1c93..9420ba8e688 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -128,7 +128,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { type = "DELETE" } filter { - ype = "AGE" + type = "AGE" value = 6 } } From df91a7862e2cd9ded30bb1855fc43f4527ffa37e Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 22:58:43 +0100 Subject: [PATCH 036/112] chore: set tags/tagsall in struct --- internal/service/imagebuilder/lifecycle_policy.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index ff85362c01c..20138e14e04 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -279,7 +279,7 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat Name: aws.String(plan.Name.ValueString()), ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), - //Tags: getTagsIn(ctx), + Tags: getTagsIn(ctx), } if !plan.Description.IsNull() { @@ -1054,6 +1054,8 @@ type resourceLifecyclePolicyData struct { Status types.String `tfsdk:"status"` PolicyDetails types.Set `tfsdk:"policy_details"` ResourceSelection types.List `tfsdk:"resource_selection"` + Tags types.Map `tfsdk:"tags"` + TagsAll types.Map `tfsdk:"tags_all"` } type resourcePolicyDetailsData struct { From 3b52dc56f92af3b87db5e7aa063ea440c3dcd095 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 23:01:02 +0100 Subject: [PATCH 037/112] chore: set 'ARN' to string type --- internal/service/imagebuilder/lifecycle_policy.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 20138e14e04..ca10e5dbd01 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -28,7 +28,6 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/framework" "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" - fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" @@ -333,7 +332,7 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat } plan.ID = flex.StringToFramework(ctx, out.LifecyclePolicyArn) - plan.ARN = flex.StringToFrameworkARN(ctx, out.LifecyclePolicyArn) + plan.ARN = flex.StringToFramework(ctx, out.LifecyclePolicyArn) resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) } @@ -360,7 +359,7 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq return } - state.ARN = flex.StringToFrameworkARN(ctx, out.Arn) + state.ARN = flex.StringToFramework(ctx, out.Arn) state.ID = flex.StringToFramework(ctx, out.Arn) state.Description = flex.StringToFramework(ctx, out.Description) state.ExecutionRole = flex.StringToFramework(ctx, out.ExecutionRole) @@ -1046,7 +1045,7 @@ func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.L type resourceLifecyclePolicyData struct { ID types.String `tfsdk:"id"` - ARN fwtypes.ARN `tfsdk:"arn"` + ARN types.String `tfsdk:"arn"` Description types.String `tfsdk:"description"` Name types.String `tfsdk:"name"` ExecutionRole types.String `tfsdk:"execution_role"` From fa45387d510dae51288c8294cf5256a8877112a0 Mon Sep 17 00:00:00 2001 From: Bruno Schaatsbergen Date: Sat, 16 Mar 2024 23:01:34 +0100 Subject: [PATCH 038/112] chore: revert temp makefile change --- GNUmakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GNUmakefile b/GNUmakefile index 66a3e69f90b..e28a1d621d9 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -386,7 +386,7 @@ testacc-lint-fix: ## Fix acceptance test linter findings @echo "Fixing acceptance tests with terrafmt" find $(SVC_DIR) -type f -name '*_test.go' \ | sort -u \ - | xargs -I {} ~/go/bin/terrafmt fmt --fmtcompat {} + | xargs -I {} terrafmt fmt --fmtcompat {} testacc-short: fmtcheck ## Run acceptace tests with the -short flag @echo "Running acceptance tests with -short flag" From 4dde3c6b2d8b5da3867de4b21358190145885145 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Mon, 25 Mar 2024 21:59:27 +0100 Subject: [PATCH 039/112] fix: resource not found exceptions --- internal/service/imagebuilder/component.go | 5 ++--- internal/service/imagebuilder/container_recipe.go | 5 ++--- internal/service/imagebuilder/distribution_configuration.go | 5 ++--- internal/service/imagebuilder/image.go | 2 +- internal/service/imagebuilder/image_pipeline.go | 5 ++--- internal/service/imagebuilder/image_recipe.go | 5 ++--- .../service/imagebuilder/infrastructure_configuration.go | 5 ++--- 7 files changed, 13 insertions(+), 19 deletions(-) diff --git a/internal/service/imagebuilder/component.go b/internal/service/imagebuilder/component.go index ea7d304ce0f..2afac174c13 100644 --- a/internal/service/imagebuilder/component.go +++ b/internal/service/imagebuilder/component.go @@ -10,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -202,7 +201,7 @@ func resourceComponentRead(ctx context.Context, d *schema.ResourceData, meta int output, err := conn.GetComponent(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Component (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -262,7 +261,7 @@ func resourceComponentDelete(ctx context.Context, d *schema.ResourceData, meta i _, err := conn.DeleteComponent(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } diff --git a/internal/service/imagebuilder/container_recipe.go b/internal/service/imagebuilder/container_recipe.go index 6c4c2a88262..119d92e2527 100644 --- a/internal/service/imagebuilder/container_recipe.go +++ b/internal/service/imagebuilder/container_recipe.go @@ -11,7 +11,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -372,7 +371,7 @@ func resourceContainerRecipeRead(ctx context.Context, d *schema.ResourceData, me output, err := conn.GetContainerRecipe(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Container Recipe (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -435,7 +434,7 @@ func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, _, err := conn.DeleteContainerRecipe(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 8d46968269d..50997b74f45 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -11,7 +11,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -340,7 +339,7 @@ func resourceDistributionConfigurationRead(ctx context.Context, d *schema.Resour output, err := conn.GetDistributionConfiguration(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Distribution Configuration (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -406,7 +405,7 @@ func resourceDistributionConfigurationDelete(ctx context.Context, d *schema.Reso _, err := conn.DeleteDistributionConfiguration(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index fcd8a793c50..ac72b99329b 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -367,7 +367,7 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, meta inter _, err := conn.DeleteImage(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } diff --git a/internal/service/imagebuilder/image_pipeline.go b/internal/service/imagebuilder/image_pipeline.go index 5acf66dd53f..91d640c9ac4 100644 --- a/internal/service/imagebuilder/image_pipeline.go +++ b/internal/service/imagebuilder/image_pipeline.go @@ -11,7 +11,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -277,7 +276,7 @@ func resourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta output, err := conn.GetImagePipeline(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Image Pipeline (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -404,7 +403,7 @@ func resourceImagePipelineDelete(ctx context.Context, d *schema.ResourceData, me _, err := conn.DeleteImagePipeline(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index bd092e28520..d54beeac042 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -12,7 +12,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -326,7 +325,7 @@ func resourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta i output, err := conn.GetImageRecipe(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Image Recipe (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -383,7 +382,7 @@ func resourceImageRecipeDelete(ctx context.Context, d *schema.ResourceData, meta _, err := conn.DeleteImageRecipe(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } diff --git a/internal/service/imagebuilder/infrastructure_configuration.go b/internal/service/imagebuilder/infrastructure_configuration.go index 44afaf0672c..0512773d3b2 100644 --- a/internal/service/imagebuilder/infrastructure_configuration.go +++ b/internal/service/imagebuilder/infrastructure_configuration.go @@ -10,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -253,7 +252,7 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso output, err := conn.GetInfrastructureConfiguration(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Infrastructure Configuration (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -401,7 +400,7 @@ func resourceInfrastructureConfigurationDelete(ctx context.Context, d *schema.Re _, err := conn.DeleteInfrastructureConfiguration(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } From 40d381521bdb1d415a6d5b46e7dd6134f60b0fa0 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Tue, 26 Mar 2024 13:23:53 +0100 Subject: [PATCH 040/112] fix: workflow notfound exception --- internal/service/imagebuilder/workflow.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/internal/service/imagebuilder/workflow.go b/internal/service/imagebuilder/workflow.go index b825e62e30c..711f6a4b8df 100644 --- a/internal/service/imagebuilder/workflow.go +++ b/internal/service/imagebuilder/workflow.go @@ -11,7 +11,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -165,7 +164,7 @@ func resourceWorkflowRead(ctx context.Context, d *schema.ResourceData, meta inte output, err := conn.GetWorkflow(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Workflow (%s) not found, removing from state", d.Id()) d.SetId("") return diags @@ -212,7 +211,7 @@ func resourceWorkflowDelete(ctx context.Context, d *schema.ResourceData, meta in _, err := conn.DeleteWorkflow(ctx, input) - if errs.IsA[*types.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return diags } From 61c03485d610d2b7f3dbd79b2842b27b2e66e950 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Tue, 26 Mar 2024 14:53:18 +0100 Subject: [PATCH 041/112] fix: fix schema and test case --- internal/service/imagebuilder/lifecycle_policy.go | 1 + .../service/imagebuilder/lifecycle_policy_test.go | 14 +++++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index ca10e5dbd01..edbedaf9f36 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -229,6 +229,7 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, "resource_selection": schema.ListNestedBlock{ Validators: []validator.List{ + listvalidator.IsRequired(), listvalidator.SizeAtMost(1), }, NestedObject: schema.NestedBlockObject{ diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 9420ba8e688..1d88feaf752 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -99,6 +99,10 @@ func testAccLifecyclePolicyConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} +data "aws_iam_policy" "EC2ImageBuilderLifecycleExecutionPolicy" { + arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/EC2ImageBuilderLifecycleExecutionPolicy" +} + resource "aws_iam_role" "test" { assume_role_policy = jsonencode({ Version = "2012-10-17" @@ -106,17 +110,16 @@ resource "aws_iam_role" "test" { Action = "sts:AssumeRole" Effect = "Allow" Principal = { - Service = "ec2.${data.aws_partition.current.dns_suffix}" + Service = "imagebuilder.${data.aws_partition.current.dns_suffix}" } - Sid = "" }] }) name = %[1]q } -resource "aws_iam_instance_profile" "test" { - name = aws_iam_role.test.name - role = aws_iam_role.test.name +resource "aws_iam_role_policy_attachment" "test" { + role = "${aws_iam_role.test.name}" + policy_arn = "${data.aws_iam_policy.EC2ImageBuilderLifecycleExecutionPolicy.arn}" } resource "aws_imagebuilder_lifecycle_policy" "test" { @@ -132,6 +135,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { value = 6 } } + resource_selection {} } `, rName) } From 33462feb1493230dac97f054119da4ac4a0b0df0 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Tue, 26 Mar 2024 21:56:59 +0100 Subject: [PATCH 042/112] fix: unit argument and computed arguments --- internal/service/imagebuilder/lifecycle_policy.go | 10 ++++++---- internal/service/imagebuilder/lifecycle_policy_test.go | 7 ++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index edbedaf9f36..bf3722ec039 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -82,7 +82,6 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, "status": schema.StringAttribute{ Optional: true, - Computed: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.UseStateForUnknown(), }, @@ -278,7 +277,6 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), Name: aws.String(plan.Name.ValueString()), ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), - Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), Tags: getTagsIn(ctx), } @@ -316,6 +314,10 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat in.ResourceSelection = resourceSelection } + if !plan.Status.IsNull() { + in.Status = awstypes.LifecyclePolicyStatus(plan.Status.ValueString()) + } + out, err := conn.CreateLifecyclePolicy(ctx, in) if err != nil { resp.Diagnostics.AddError( @@ -495,7 +497,7 @@ func findLifecyclePolicyByARN(ctx context.Context, conn *imagebuilder.Client, ar out, err := conn.GetLifecyclePolicy(ctx, in) if err != nil { - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return nil, &retry.NotFoundError{ LastError: err, LastRequest: in, @@ -639,7 +641,7 @@ func expandPolicyDetailFilter(tfList []resourceFilterData) *awstypes.LifecyclePo } if !tfObj.Unit.IsNull() { - apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Type.ValueString()) + apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Unit.ValueString()) } return &apiObject diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 1d88feaf752..1a4ba00419e 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -133,9 +133,14 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { filter { type = "AGE" value = 6 + unit = "YEARS" + } + } + resource_selection { + tag_map = { + "key" = "value" } } - resource_selection {} } `, rName) } From 619e2e24a24cd4fa15ce0265d6379532e2b67945 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Thu, 4 Apr 2024 00:15:51 +0200 Subject: [PATCH 043/112] feat: fix arguments in lifecycle policy test --- .../service/imagebuilder/lifecycle_policy.go | 102 ++++++++---------- .../imagebuilder/lifecycle_policy_test.go | 10 +- 2 files changed, 48 insertions(+), 64 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index bf3722ec039..7e9579341f5 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -82,6 +82,7 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, "status": schema.StringAttribute{ Optional: true, + Computed: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.UseStateForUnknown(), }, @@ -337,6 +338,19 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat plan.ID = flex.StringToFramework(ctx, out.LifecyclePolicyArn) plan.ARN = flex.StringToFramework(ctx, out.LifecyclePolicyArn) + // Read to retrieve computed arguments not part of the create response + readOut, err := findLifecyclePolicyByARN(ctx, conn, plan.ARN.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), err), + err.Error(), + ) + return + } + + plan.Status = flex.StringValueToFramework(ctx, readOut.Status) + plan.ResourceType = flex.StringValueToFramework(ctx, readOut.ResourceType) + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) } @@ -349,7 +363,7 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq return } - out, err := findLifecyclePolicyByARN(ctx, conn, state.ID.String()) + out, err := findLifecyclePolicyByARN(ctx, conn, state.ID.ValueString()) if tfresource.NotFound(err) { resp.State.RemoveResource(ctx) @@ -580,7 +594,9 @@ func expandPolicyDetailAction(ctx context.Context, tfList []resourceActionData) tfObj := tfList[0] - apiObject := awstypes.LifecyclePolicyDetailAction{} + apiObject := awstypes.LifecyclePolicyDetailAction{ + Type: awstypes.LifecyclePolicyDetailActionType(tfObj.Type.ValueString()), + } if !tfObj.IncludeResources.IsNull() { var tfList []resourceIncludeResourcesData @@ -592,10 +608,6 @@ func expandPolicyDetailAction(ctx context.Context, tfList []resourceActionData) apiObject.IncludeResources = expandPolicyDetailActionIncludeResources(tfList) } - if !tfObj.Type.IsNull() { - apiObject.Type = awstypes.LifecyclePolicyDetailActionType(tfObj.Type.ValueString()) - } - return &apiObject, diags } @@ -784,7 +796,7 @@ func expandResourceSelectionRecipes(tfList []resourceRecipesData) []awstypes.Lif func flattenPolicyDetails(ctx context.Context, apiObject []awstypes.LifecyclePolicyDetail) (types.Set, diag.Diagnostics) { var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceActionAttrTypes} + elemType := types.ObjectType{AttrTypes: resourcePolicyDetailAttrTypes} if apiObject == nil { return types.SetNull(elemType), diags @@ -828,15 +840,12 @@ func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolic return types.ListNull(elemType), diags } - obj := map[string]attr.Value{ - "type": flex.StringValueToFramework(ctx, apiObject.Type), - } - - if apiObject.IncludeResources != nil { - includeResources, d := flattenIncludeResources(ctx, apiObject.IncludeResources) - diags.Append(d...) + includeResources, d := flattenIncludeResources(ctx, apiObject.IncludeResources) + diags.Append(d...) - obj["include_resources"] = includeResources + obj := map[string]attr.Value{ + "include_resources": includeResources, + "type": flex.StringValueToFramework(ctx, apiObject.Type), } objVal, d := types.ObjectValue(resourceActionAttrTypes, obj) @@ -903,17 +912,12 @@ func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.Lifecy return types.ListNull(elemType), diags } - obj := map[string]attr.Value{} - - if apiObject.Amis != nil { - amis, d := flattenExclusionRulesAMIS(ctx, apiObject.Amis) - diags.Append(d...) - - obj["amis"] = amis - } + amis, d := flattenExclusionRulesAMIS(ctx, apiObject.Amis) + diags.Append(d...) - if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + obj := map[string]attr.Value{ + "amis": amis, + "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), } objVal, d := types.ObjectValue(resourceExclusionRulesAttrTypes, obj) @@ -933,27 +937,15 @@ func flattenExclusionRulesAMIS(ctx context.Context, apiObject *awstypes.Lifecycl return types.ListNull(elemType), diags } - obj := map[string]attr.Value{ - "is_public": flex.BoolToFramework(ctx, &apiObject.IsPublic), - } - - if apiObject.LastLaunched != nil { - lastLaunched, d := flattenExclusionRulesAMISLastLaunched(ctx, apiObject.LastLaunched) - diags.Append(d...) - - obj["last_launched"] = lastLaunched - } - - if apiObject.Regions != nil { - obj["regions"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions) - } - - if apiObject.SharedAccounts != nil { - obj["shared_accounts"] = flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts) - } + lastLaunched, d := flattenExclusionRulesAMISLastLaunched(ctx, apiObject.LastLaunched) + diags.Append(d...) - if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + obj := map[string]attr.Value{ + "is_public": flex.BoolToFramework(ctx, &apiObject.IsPublic), + "regions": flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions), + "shared_accounts": flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts), + "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), + "last_launched": lastLaunched, } objVal, d := types.ObjectValue(resourceAMISAttrTypes, obj) @@ -995,17 +987,12 @@ func flattenResourceSelection(ctx context.Context, apiObject *awstypes.Lifecycle return types.ListNull(elemType), diags } - obj := map[string]attr.Value{} - - if apiObject.Recipes != nil { - recipes, d := flattenResourceSelectionRecipes(ctx, apiObject.Recipes) - diags.Append(d...) - - obj["recipes"] = recipes - } + recipes, d := flattenResourceSelectionRecipes(ctx, apiObject.Recipes) + diags.Append(d...) - if apiObject.TagMap != nil { - obj["tag_map"] = flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap) + obj := map[string]attr.Value{ + "recipes": recipes, + "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), } objVal, d := types.ObjectValue(resourceResourceSelectionAttrTypes, obj) @@ -1028,7 +1015,6 @@ func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.L result := []attr.Value{} for _, recipe := range apiObject { - obj := map[string]attr.Value{ "name": flex.StringToFramework(ctx, recipe.Name), "semantic_version": flex.StringToFramework(ctx, recipe.SemanticVersion), @@ -1040,10 +1026,10 @@ func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.L result = append(result, objVal) } - listVal, d := types.SetValue(elemType, result) + setVal, d := types.SetValue(elemType, result) diags.Append(d...) - return listVal, diags + return setVal, diags } type resourceLifecyclePolicyData struct { diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 1a4ba00419e..6ae8b51f2c0 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -99,10 +99,6 @@ func testAccLifecyclePolicyConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} -data "aws_iam_policy" "EC2ImageBuilderLifecycleExecutionPolicy" { - arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/EC2ImageBuilderLifecycleExecutionPolicy" -} - resource "aws_iam_role" "test" { assume_role_policy = jsonencode({ Version = "2012-10-17" @@ -118,8 +114,8 @@ resource "aws_iam_role" "test" { } resource "aws_iam_role_policy_attachment" "test" { - role = "${aws_iam_role.test.name}" - policy_arn = "${data.aws_iam_policy.EC2ImageBuilderLifecycleExecutionPolicy.arn}" + policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/EC2ImageBuilderLifecycleExecutionPolicy" + role = aws_iam_role.test.name } resource "aws_imagebuilder_lifecycle_policy" "test" { @@ -141,6 +137,8 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { "key" = "value" } } + + depends_on = [aws_iam_role_policy_attachment.test] } `, rName) } From 24881e5944bf04d7f04d82be76986a9aabe65821 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Fri, 5 Apr 2024 16:26:21 +0200 Subject: [PATCH 044/112] feat: added retry for iam propagation period --- internal/service/imagebuilder/consts.go | 3 +- .../service/imagebuilder/lifecycle_policy.go | 30 +++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/internal/service/imagebuilder/consts.go b/internal/service/imagebuilder/consts.go index 7e63a79494d..dcd2f1ad7e6 100644 --- a/internal/service/imagebuilder/consts.go +++ b/internal/service/imagebuilder/consts.go @@ -10,5 +10,6 @@ import ( const ( propagationTimeout = 2 * time.Minute - ResourceNotFoundException = "ResourceNotFoundException" + ResourceNotFoundException = "ResourceNotFoundException" + InvalidParameterValueException = "InvalidParameterValueException" ) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 7e9579341f5..04b39de3a9b 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -319,7 +319,20 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat in.Status = awstypes.LifecyclePolicyStatus(plan.Status.ValueString()) } - out, err := conn.CreateLifecyclePolicy(ctx, in) + // Include retry handling to allow for IAM propagation + var out *imagebuilder.CreateLifecyclePolicyOutput + err := tfresource.Retry(ctx, propagationTimeout, func() *retry.RetryError { + var err error + out, err = conn.CreateLifecyclePolicy(ctx, in) + if err != nil { + if errs.MessageContains(err, InvalidParameterValueException, "The provided role does not exist or does not have sufficient permissions") { + return retry.RetryableError(err) + } + return retry.NonRetryableError(err) + } + return nil + }) + if err != nil { resp.Diagnostics.AddError( create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), err), @@ -452,7 +465,20 @@ func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.Updat in.ResourceSelection = resourceSelection } - out, err := conn.UpdateLifecyclePolicy(ctx, in) + // Include retry handling to allow for IAM propagation + var out *imagebuilder.UpdateLifecyclePolicyOutput + err := tfresource.Retry(ctx, propagationTimeout, func() *retry.RetryError { + var err error + out, err = conn.UpdateLifecyclePolicy(ctx, in) + if err != nil { + if errs.MessageContains(err, InvalidParameterValueException, "The provided role does not exist or does not have sufficient permissions") { + return retry.RetryableError(err) + } + return retry.NonRetryableError(err) + } + return nil + }) + if err != nil { resp.Diagnostics.AddError( create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionUpdating, ResNameLifecyclePolicy, plan.ID.String(), err), From 58996108a8d0b51cde06d604227c6408612cf06d Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 6 Apr 2024 12:40:06 +0200 Subject: [PATCH 045/112] fix: dependencies --- go.mod | 1 + go.sum | 2 ++ 2 files changed, 3 insertions(+) diff --git a/go.mod b/go.mod index 8c3fc696a28..ebcecd1bb28 100644 --- a/go.mod +++ b/go.mod @@ -87,6 +87,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/healthlake v1.23.4 github.com/aws/aws-sdk-go-v2/service/iam v1.31.4 github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.5 + github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.33.3 github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.4 github.com/aws/aws-sdk-go-v2/service/internetmonitor v1.13.0 github.com/aws/aws-sdk-go-v2/service/ivschat v1.12.5 diff --git a/go.sum b/go.sum index 1bbe0c12522..de8f2b6f7c7 100644 --- a/go.sum +++ b/go.sum @@ -194,6 +194,8 @@ github.com/aws/aws-sdk-go-v2/service/iam v1.31.4 h1:eVm30ZIDv//r6Aogat9I88b5YX1x github.com/aws/aws-sdk-go-v2/service/iam v1.31.4/go.mod h1:aXWImQV0uTW35LM0A/T4wEg6R1/ReXUu4SM6/lUHYK0= github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.5 h1:c8V6kd9z0D/YpFr+HD9rrYOexzbbNetekj1pZYF01RM= github.com/aws/aws-sdk-go-v2/service/identitystore v1.23.5/go.mod h1:E2IkFljjGHI/JW/+Jrav9K5hRtR4HNFHrcXTK4n0tws= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.33.3 h1:fvLAeCBbkBDMYGR4qXCKtuKHhvZW/J5MQ7dnnFbBRyA= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.33.3/go.mod h1:DYoBHNyo4HJBs+ODwXLgQ4j1GutSg1JfSIJNBJfpwgE= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.4 h1:0cHc8syoJJUzP5N2d6Hhtj3sUIBYUpFYW/p6q91ISko= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.24.4/go.mod h1:tyMGN8hc2UtH6e6y6phOqN/O/L68Q8YYKZG2Ydsk3UI= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.2 h1:Ji0DY1xUsUr3I8cHps0G+XM3WWU16lP6yG8qu1GAZAs= From 3fe16034f8beac18f794caa7631c799f510b512b Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 6 Apr 2024 23:08:28 +0200 Subject: [PATCH 046/112] feat: added tag test --- .../service/imagebuilder/lifecycle_policy.go | 3 + .../imagebuilder/lifecycle_policy_test.go | 134 ++++++++++++++++-- .../imagebuilder/service_package_gen.go | 3 + 3 files changed, 130 insertions(+), 10 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 04b39de3a9b..19aef3015c0 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -34,6 +34,7 @@ import ( ) // @FrameworkResource(name="Lifecycle Policy") +// @Tags(identifierAttribute="id") func newResourceLifecyclePolicy(_ context.Context) (resource.ResourceWithConfigure, error) { return &resourceLifecyclePolicy{}, nil } @@ -406,6 +407,8 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq state.ResourceType = flex.StringValueToFramework(ctx, out.ResourceType) state.Status = flex.StringValueToFramework(ctx, out.Status) + setTagsOut(ctx, out.Tags) + resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 6ae8b51f2c0..aa6b160608d 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -9,7 +9,6 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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,20 +22,19 @@ import ( func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { ctx := acctest.Context(t) - var lifecyclePolicy types.LifecyclePolicy resourceName := "aws_imagebuilder_lifecycle_policy.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, - ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilder), + ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), Steps: []resource.TestStep{ { Config: testAccLifecyclePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckLifecyclePolicyExists(ctx, resourceName, &lifecyclePolicy), + testAccCheckLifecyclePolicyExists(ctx, resourceName), ), }, { @@ -48,7 +46,52 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { }) } -func testAccCheckLifecyclePolicyExists(ctx context.Context, name string, lifecyclePolicy *types.LifecyclePolicy) resource.TestCheckFunc { +func TestAccImageBuilderLifecyclePolicy_tags(t *testing.T) { + ctx := acctest.Context(t) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_imagebuilder_lifecycle_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(ctx, t) }, + ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccLifecyclePolicyConfig_tags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccLifecyclePolicyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccLifecyclePolicyConfig_tags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckLifecyclePolicyExists(ctx context.Context, name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -60,13 +103,11 @@ func testAccCheckLifecyclePolicyExists(ctx context.Context, name string, lifecyc } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - resp, err := tfimagebuilder.FindLifecyclePolicyByARN(ctx, conn, rs.Primary.ID) + _, err := tfimagebuilder.FindLifecyclePolicyByARN(ctx, conn, rs.Primary.ID) if err != nil { return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, err) } - *lifecyclePolicy = *resp - return nil } } @@ -95,7 +136,7 @@ func testAccCheckLifecyclePolicyDestroy(ctx context.Context) resource.TestCheckF } } -func testAccLifecyclePolicyConfig_basic(rName string) string { +func testAccLifecyclePolicyBaseConfig(rName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} @@ -117,7 +158,13 @@ resource "aws_iam_role_policy_attachment" "test" { policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/EC2ImageBuilderLifecycleExecutionPolicy" role = aws_iam_role.test.name } +`, rName) +} +func testAccLifecyclePolicyConfig_basic(rName string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn @@ -140,5 +187,72 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { depends_on = [aws_iam_role_policy_attachment.test] } -`, rName) +`, rName)) +} + +func testAccLifecyclePolicyConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + fmt.Sprintf(` +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = "DELETE" + } + filter { + type = "AGE" + value = 6 + unit = "YEARS" + } + } + resource_selection { + tag_map = { + "key" = "value" + } + } + + tags = { + %[2]q = %[3]q + } + + depends_on = [aws_iam_role_policy_attachment.test] +} +`, rName, tagKey1, tagValue1)) +} + +func testAccLifecyclePolicyConfig_tags2(rName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + fmt.Sprintf(` +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = "DELETE" + } + filter { + type = "AGE" + value = 6 + unit = "YEARS" + } + } + resource_selection { + tag_map = { + "key" = "value" + } + } + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } + + depends_on = [aws_iam_role_policy_attachment.test] +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index e7968590a45..983b97a3bc0 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -23,6 +23,9 @@ func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.Servic { Factory: newResourceLifecyclePolicy, Name: "Lifecycle Policy", + Tags: &types.ServicePackageResourceTags{ + IdentifierAttribute: "id", + }, }, } } From 2ecba2ad99daf711cd9b771a551405d6d446fb8a Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 13 Apr 2024 00:00:36 +0200 Subject: [PATCH 047/112] feat: added disappears test --- internal/service/imagebuilder/export_tests.go | 1 - .../service/imagebuilder/lifecycle_policy.go | 8 +++--- .../imagebuilder/lifecycle_policy_test.go | 25 +++++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 135738a6880..017cee974c8 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -4,7 +4,6 @@ package imagebuilder // Exports for use in tests only. - var ( ResourceLifecyclePolicy = newResourceLifecyclePolicy diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 19aef3015c0..0239e85b823 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -381,6 +381,7 @@ func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadReq if tfresource.NotFound(err) { resp.State.RemoveResource(ctx) + return } if err != nil { resp.Diagnostics.AddError( @@ -513,15 +514,16 @@ func (r *resourceLifecyclePolicy) Delete(ctx context.Context, req resource.Delet _, err := conn.DeleteLifecyclePolicy(ctx, &imagebuilder.DeleteLifecyclePolicyInput{ LifecyclePolicyArn: aws.String(state.ID.ValueString()), }) + if err != nil { - var nfe *awstypes.ResourceNotFoundException - if errors.As(err, &nfe) { + if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { return } resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionDeleting, ResNameLifecyclePolicy, state.Name.String(), nil), + create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionDeleting, ResNameLifecyclePolicy, state.ID.String(), nil), err.Error(), ) + return } } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index aa6b160608d..1fc237284c9 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -35,6 +35,8 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { Config: testAccLifecyclePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "resource_type", "AMI_IMAGE"), ), }, { @@ -91,6 +93,29 @@ func TestAccImageBuilderLifecyclePolicy_tags(t *testing.T) { }) } +func TestAccImageBuilderLifecyclePolicy_disappears(t *testing.T) { + ctx := acctest.Context(t) + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + resourceName := "aws_imagebuilder_lifecycle_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(ctx, t) }, + ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccLifecyclePolicyConfig_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + acctest.CheckFrameworkResourceDisappears(ctx, acctest.Provider, tfimagebuilder.ResourceLifecyclePolicy, resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckLifecyclePolicyExists(ctx context.Context, name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] From f6b24086c3b31a6b2b57bffbd7f6e8d16fe56bc3 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 13 Apr 2024 12:37:29 +0200 Subject: [PATCH 048/112] feat: expanded basic test validation --- .../imagebuilder/lifecycle_policy_test.go | 26 ++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 1fc237284c9..6256b19e644 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -35,7 +35,22 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { Config: testAccLifecyclePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), + acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "imagebuilder", fmt.Sprintf("lifecycle-policy/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "description", "Used for setting lifecycle policies"), + resource.TestCheckResourceAttrSet(resourceName, "execution_role"), resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DELETE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "AGE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "10"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", "YEARS"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.%", "2"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key1", "value1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key2", "value2"), resource.TestCheckResourceAttr(resourceName, "resource_type", "AMI_IMAGE"), ), }, @@ -192,6 +207,7 @@ func testAccLifecyclePolicyConfig_basic(rName string) string { fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q + description = "Used for setting lifecycle policies" execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" policy_details { @@ -199,14 +215,16 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { type = "DELETE" } filter { - type = "AGE" - value = 6 - unit = "YEARS" + type = "AGE" + value = 6 + retain_at_least = 10 + unit = "YEARS" } } resource_selection { tag_map = { - "key" = "value" + "key1" = "value1" + "key2" = "value2" } } From 13ccfe53fd5e3598ea2d53d42ae1c2f482dc59e3 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sat, 13 Apr 2024 13:20:16 +0200 Subject: [PATCH 049/112] feat: added policyDetails test and fix update handler --- .../service/imagebuilder/lifecycle_policy.go | 13 ++- .../imagebuilder/lifecycle_policy_test.go | 108 ++++++++++++++++++ 2 files changed, 115 insertions(+), 6 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 0239e85b823..113c8de287a 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -430,16 +430,17 @@ func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.Updat !plan.ResourceType.Equal(state.ResourceType) || !plan.Status.Equal(state.Status) { in := &imagebuilder.UpdateLifecyclePolicyInput{ - ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), - ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), - Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), + LifecyclePolicyArn: aws.String(plan.ID.ValueString()), + ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), + ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), + Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), } - if !plan.Description.Equal(state.Description) { + if !plan.Description.IsNull() { in.Description = aws.String(plan.Description.ValueString()) } - if !plan.PolicyDetails.Equal(state.PolicyDetails) { + if !plan.PolicyDetails.IsNull() { var tfList []resourcePolicyDetailsData resp.Diagnostics.Append(plan.PolicyDetails.ElementsAs(ctx, &tfList, false)...) if resp.Diagnostics.HasError() { @@ -454,7 +455,7 @@ func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.Updat in.PolicyDetails = policyDetails } - if !plan.ResourceSelection.Equal(state.ResourceSelection) { + if !plan.ResourceSelection.IsNull() { var tfList []resourceResourceSelectionData resp.Diagnostics.Append(plan.ResourceSelection.ElementsAs(ctx, &tfList, false)...) if resp.Diagnostics.HasError() { diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 6256b19e644..060a4e57461 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -63,6 +63,52 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { }) } +func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { + ctx := acctest.Context(t) + resourceName := "aws_imagebuilder_lifecycle_policy.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(ctx, t) }, + ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccLifecyclePolicyConfig_policyDetails(rName, "DISABLE", "AGE", "6", "5"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DISABLE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "AGE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "5"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", "YEARS"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, "DELETE", "COUNT", "10"), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DELETE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "COUNT"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "10"), + ), + }, + }, + }) +} + func TestAccImageBuilderLifecyclePolicy_tags(t *testing.T) { ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -233,6 +279,68 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { `, rName)) } +func testAccLifecyclePolicyConfig_policyDetails(rName, actionType, filterType, filterValue, retainAtLeast string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + fmt.Sprintf(` +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + description = "Used for setting lifecycle policies" + execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = %[2]q + } + filter { + type = %[3]q + value = %[4]q + retain_at_least = %[5]q + unit = "YEARS" + } + } + resource_selection { + tag_map = { + "key1" = "value1" + "key2" = "value2" + } + } + + depends_on = [aws_iam_role_policy_attachment.test] +} +`, rName, actionType, filterType, filterValue, retainAtLeast)) +} + +func testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, actionType, filterType, filterValue string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + fmt.Sprintf(` +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + description = "Used for setting lifecycle policies" + execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = %[2]q + } + filter { + type = %[3]q + value = %[4]q + } + } + resource_selection { + tag_map = { + "key1" = "value1" + "key2" = "value2" + } + } + + depends_on = [aws_iam_role_policy_attachment.test] +} +`, rName, actionType, filterType, filterValue)) +} + func testAccLifecyclePolicyConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { return acctest.ConfigCompose( testAccLifecyclePolicyBaseConfig(rName), From 27ba412d7f8a2195d929af4408b761883819f380 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 13:39:26 +0200 Subject: [PATCH 050/112] feat: expand policyDetails test and several fixes in amis --- .../service/imagebuilder/lifecycle_policy.go | 47 ++++++----- .../imagebuilder/lifecycle_policy_test.go | 82 ++++++++++++++++--- 2 files changed, 97 insertions(+), 32 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 113c8de287a..d1b9d9fc13a 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -17,6 +17,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/schema/validator" @@ -125,12 +126,24 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem Attributes: map[string]schema.Attribute{ "amis": schema.BoolAttribute{ Optional: true, + Computed: true, + PlanModifiers: []planmodifier.Bool{ + boolplanmodifier.UseStateForUnknown(), + }, }, "containers": schema.BoolAttribute{ Optional: true, + Computed: true, + PlanModifiers: []planmodifier.Bool{ + boolplanmodifier.UseStateForUnknown(), + }, }, "snapshots": schema.BoolAttribute{ Optional: true, + Computed: true, + PlanModifiers: []planmodifier.Bool{ + boolplanmodifier.UseStateForUnknown(), + }, }, }, }, @@ -365,6 +378,10 @@ func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.Creat plan.Status = flex.StringValueToFramework(ctx, readOut.Status) plan.ResourceType = flex.StringValueToFramework(ctx, readOut.ResourceType) + policyDetails, d := flattenPolicyDetails(ctx, readOut.PolicyDetails) + resp.Diagnostics.Append(d...) + plan.PolicyDetails = policyDetails + resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) } @@ -646,18 +663,10 @@ func expandPolicyDetailAction(ctx context.Context, tfList []resourceActionData) func expandPolicyDetailActionIncludeResources(tfList []resourceIncludeResourcesData) *awstypes.LifecyclePolicyDetailActionIncludeResources { tfObj := tfList[0] - apiObject := awstypes.LifecyclePolicyDetailActionIncludeResources{} - - if !tfObj.Amis.IsNull() { - apiObject.Amis = aws.ToBool(tfObj.Amis.ValueBoolPointer()) - } - - if !tfObj.Containers.IsNull() { - apiObject.Containers = aws.ToBool(tfObj.Containers.ValueBoolPointer()) - } - - if !tfObj.Snapshots.IsNull() { - apiObject.Snapshots = aws.ToBool(tfObj.Snapshots.ValueBoolPointer()) + apiObject := awstypes.LifecyclePolicyDetailActionIncludeResources{ + Amis: tfObj.Amis.ValueBool(), + Containers: tfObj.Containers.ValueBool(), + Snapshots: tfObj.Snapshots.ValueBool(), } return &apiObject @@ -750,11 +759,11 @@ func expandPolicyDetailExclusionRulesAMIS(ctx context.Context, tfList []resource } if !tfObj.Regions.IsNull() { - apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.LastLaunched) + apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.Regions) } if !tfObj.SharedAccounts.IsNull() { - apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.SharedAccounts) + apiObject.SharedAccounts = flex.ExpandFrameworkStringValueList(ctx, tfObj.SharedAccounts) } if !tfObj.TagMap.IsNull() { @@ -898,9 +907,9 @@ func flattenIncludeResources(ctx context.Context, apiObject *awstypes.LifecycleP } obj := map[string]attr.Value{ - "amis": flex.BoolToFramework(ctx, &apiObject.Amis), - "containers": flex.BoolToFramework(ctx, &apiObject.Containers), - "snapshots": flex.BoolToFramework(ctx, &apiObject.Snapshots), + "amis": flex.BoolToFramework(ctx, aws.Bool(apiObject.Amis)), + "containers": flex.BoolToFramework(ctx, aws.Bool(apiObject.Containers)), + "snapshots": flex.BoolToFramework(ctx, aws.Bool(apiObject.Snapshots)), } objVal, d := types.ObjectValue(resourceIncludeResourcesAttrTypes, obj) @@ -973,7 +982,7 @@ func flattenExclusionRulesAMIS(ctx context.Context, apiObject *awstypes.Lifecycl diags.Append(d...) obj := map[string]attr.Value{ - "is_public": flex.BoolToFramework(ctx, &apiObject.IsPublic), + "is_public": flex.BoolToFramework(ctx, aws.Bool(apiObject.IsPublic)), "regions": flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions), "shared_accounts": flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts), "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), @@ -1113,7 +1122,7 @@ type resourceFilterData struct { } type resourceExclusionRulesData struct { - AMIs types.List `tfsdk:"ami"` + AMIs types.List `tfsdk:"amis"` TagMap types.Map `tfsdk:"tag_map"` } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 060a4e57461..74ba78f3ae8 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -75,12 +75,22 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccLifecyclePolicyConfig_policyDetails(rName, "DISABLE", "AGE", "6", "5"), + Config: testAccLifecyclePolicyConfig_policyDetails(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DISABLE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", "true"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", "false"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", "DAYS"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", "value1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "AGE"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), @@ -94,12 +104,25 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, "DELETE", "COUNT", "10"), + Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, acctest.Region()), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DELETE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", "true"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.snapshots", "true"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", "true"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.regions.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", "WEEKS"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "2"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", "2"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", "value1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key2", "value2"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "COUNT"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "10"), @@ -279,7 +302,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { `, rName)) } -func testAccLifecyclePolicyConfig_policyDetails(rName, actionType, filterType, filterValue, retainAtLeast string) string { +func testAccLifecyclePolicyConfig_policyDetails(rName string) string { return acctest.ConfigCompose( testAccLifecyclePolicyBaseConfig(rName), fmt.Sprintf(` @@ -290,12 +313,27 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { resource_type = "AMI_IMAGE" policy_details { action { - type = %[2]q + type = "DISABLE" + include_resources { + amis = true + } + } + exclusion_rules { + amis { + is_public = false + last_launched { + unit = "DAYS" + value = 7 + } + tag_map = { + "key1" = "value1" + } + } } filter { - type = %[3]q - value = %[4]q - retain_at_least = %[5]q + type = "AGE" + value = "6" + retain_at_least = "5" unit = "YEARS" } } @@ -308,10 +346,10 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { depends_on = [aws_iam_role_policy_attachment.test] } -`, rName, actionType, filterType, filterValue, retainAtLeast)) +`, rName)) } -func testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, actionType, filterType, filterValue string) string { +func testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, region string) string { return acctest.ConfigCompose( testAccLifecyclePolicyBaseConfig(rName), fmt.Sprintf(` @@ -322,11 +360,29 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { resource_type = "AMI_IMAGE" policy_details { action { - type = %[2]q + type = "DELETE" + include_resources { + amis = true + snapshots = true + } + } + exclusion_rules { + amis { + is_public = true + regions = [%[2]q] + last_launched { + unit = "WEEKS" + value = 2 + } + tag_map = { + "key1" = "value1" + "key2" = "value2" + } + } } filter { - type = %[3]q - value = %[4]q + type = "COUNT" + value = "10" } } resource_selection { @@ -338,7 +394,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { depends_on = [aws_iam_role_policy_attachment.test] } -`, rName, actionType, filterType, filterValue)) +`, rName, region)) } func testAccLifecyclePolicyConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { From f21e40745e24442e08ddba58dedfa6fac1d0bc99 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 15:58:49 +0200 Subject: [PATCH 051/112] chore: fmt --- .../imagebuilder/lifecycle_policy_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 74ba78f3ae8..e3d310de377 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -325,9 +325,9 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { unit = "DAYS" value = 7 } - tag_map = { - "key1" = "value1" - } + tag_map = { + "key1" = "value1" + } } } filter { @@ -369,15 +369,15 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { exclusion_rules { amis { is_public = true - regions = [%[2]q] + regions = [%[2]q] last_launched { unit = "WEEKS" value = 2 } - tag_map = { - "key1" = "value1" - "key2" = "value2" - } + tag_map = { + "key1" = "value1" + "key2" = "value2" + } } } filter { From 6cb143ae216b4f0464c96ac0c09400b9c9426819 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 16:27:27 +0200 Subject: [PATCH 052/112] feat: added resourceSelection test scenario and validation --- .../service/imagebuilder/lifecycle_policy.go | 2 +- .../imagebuilder/lifecycle_policy_test.go | 160 +++++++++++++++++- 2 files changed, 157 insertions(+), 5 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index d1b9d9fc13a..e901333e9ee 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -824,7 +824,7 @@ func expandResourceSelectionRecipes(tfList []resourceRecipesData) []awstypes.Lif apiObject := awstypes.LifecyclePolicyResourceSelectionRecipe{} if !tfObj.Name.IsNull() { - apiObject.SemanticVersion = aws.String(tfObj.Name.ValueString()) + apiObject.Name = aws.String(tfObj.Name.ValueString()) } if !tfObj.SemanticVersion.IsNull() { apiObject.SemanticVersion = aws.String(tfObj.SemanticVersion.ValueString()) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index e3d310de377..167a91abd98 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -104,7 +104,7 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, acctest.Region()), + Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), @@ -132,6 +132,46 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { }) } +func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { + ctx := acctest.Context(t) + resourceName := "aws_imagebuilder_lifecycle_policy.test" + rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(ctx, t) }, + ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, + CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), + Steps: []resource.TestStep{ + { + Config: testAccLifecyclePolicyConfig_resourceSelection(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.name", rName), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.semantic_version", "1.0.0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccLifecyclePolicyConfig_resourceSelectionUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckLifecyclePolicyExists(ctx, resourceName), + resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.name", rName), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.semantic_version", "2.0.0"), + ), + }, + }, + }) +} + func TestAccImageBuilderLifecyclePolicy_tags(t *testing.T) { ctx := acctest.Context(t) rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -247,6 +287,8 @@ func testAccCheckLifecyclePolicyDestroy(ctx context.Context) resource.TestCheckF func testAccLifecyclePolicyBaseConfig(rName string) string { return fmt.Sprintf(` +data "aws_region" "current" {} + data "aws_partition" "current" {} resource "aws_iam_role" "test" { @@ -270,6 +312,30 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } +func testAccLifecyclePolicyBaseConfigComponent(rName string) string { + return fmt.Sprintf(` +resource "aws_imagebuilder_component" "test" { + data = yamlencode({ + phases = [{ + name = "build" + steps = [{ + action = "ExecuteBash" + inputs = { + commands = ["echo 'hello world'"] + } + name = "example" + onFailure = "Continue" + }] + }] + schemaVersion = 1.0 + }) + name = %[1]q + platform = "Linux" + version = "1.0.0" + } + `, rName) +} + func testAccLifecyclePolicyConfig_basic(rName string) string { return acctest.ConfigCompose( testAccLifecyclePolicyBaseConfig(rName), @@ -349,7 +415,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { `, rName)) } -func testAccLifecyclePolicyConfig_policyDetailsUpdated(rName, region string) string { +func testAccLifecyclePolicyConfig_policyDetailsUpdated(rName string) string { return acctest.ConfigCompose( testAccLifecyclePolicyBaseConfig(rName), fmt.Sprintf(` @@ -369,7 +435,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { exclusion_rules { amis { is_public = true - regions = [%[2]q] + regions = ["${data.aws_region.current.name}"] last_launched { unit = "WEEKS" value = 2 @@ -394,7 +460,93 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { depends_on = [aws_iam_role_policy_attachment.test] } -`, rName, region)) +`, rName)) +} + +func testAccLifecyclePolicyConfig_resourceSelection(rName string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + testAccLifecyclePolicyBaseConfigComponent(rName), + fmt.Sprintf(` +resource "aws_imagebuilder_image_recipe" "test" { + component { + component_arn = aws_imagebuilder_component.test.arn + } + + name = %[1]q + parent_image = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:image/amazon-linux-2-x86/x.x.x" + version = "1.0.0" +} + +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + description = "Used for setting lifecycle policies" + execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = "DELETE" + } + filter { + type = "AGE" + value = 6 + retain_at_least = 10 + unit = "YEARS" + } + } + resource_selection { + recipes { + name = aws_imagebuilder_image_recipe.test.name + semantic_version = aws_imagebuilder_image_recipe.test.version + } + } + + depends_on = [aws_iam_role_policy_attachment.test] +} +`, rName)) +} + +func testAccLifecyclePolicyConfig_resourceSelectionUpdated(rName string) string { + return acctest.ConfigCompose( + testAccLifecyclePolicyBaseConfig(rName), + testAccLifecyclePolicyBaseConfigComponent(rName), + fmt.Sprintf(` +resource "aws_imagebuilder_image_recipe" "test" { + component { + component_arn = aws_imagebuilder_component.test.arn + } + + name = %[1]q + parent_image = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:image/amazon-linux-2-x86/x.x.x" + version = "2.0.0" +} + +resource "aws_imagebuilder_lifecycle_policy" "test" { + name = %[1]q + description = "Used for setting lifecycle policies" + execution_role = aws_iam_role.test.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = "DELETE" + } + filter { + type = "AGE" + value = 6 + retain_at_least = 10 + unit = "YEARS" + } + } + resource_selection { + recipes { + name = aws_imagebuilder_image_recipe.test.name + semantic_version = aws_imagebuilder_image_recipe.test.version + } + } + + depends_on = [aws_iam_role_policy_attachment.test] +} +`, rName)) } func testAccLifecyclePolicyConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { From de3510f227c9fb68bb0b6b46714b0cf5963804bb Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 16:28:16 +0200 Subject: [PATCH 053/112] chore: fmt --- .../imagebuilder/lifecycle_policy_test.go | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 167a91abd98..5b991073547 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -315,24 +315,24 @@ resource "aws_iam_role_policy_attachment" "test" { func testAccLifecyclePolicyBaseConfigComponent(rName string) string { return fmt.Sprintf(` resource "aws_imagebuilder_component" "test" { - data = yamlencode({ - phases = [{ - name = "build" - steps = [{ - action = "ExecuteBash" - inputs = { - commands = ["echo 'hello world'"] - } - name = "example" - onFailure = "Continue" - }] - }] - schemaVersion = 1.0 - }) - name = %[1]q - platform = "Linux" - version = "1.0.0" - } + data = yamlencode({ + phases = [{ + name = "build" + steps = [{ + action = "ExecuteBash" + inputs = { + commands = ["echo 'hello world'"] + } + name = "example" + onFailure = "Continue" + }] + }] + schemaVersion = 1.0 + }) + name = %[1]q + platform = "Linux" + version = "1.0.0" +} `, rName) } From 1d2ff7e006ac30f0f2cea80413c654d65fd5ccfa Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 16:44:08 +0200 Subject: [PATCH 054/112] docs: added full example and specified acceptable values where appropriate --- ...magebuilder_lifecycle_policy.html.markdown | 60 ++++++++++++++++--- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index 03ea3595866..526edb5b0ee 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -13,7 +13,53 @@ Manages an Image Builder Lifecycle Policy. ## Example Usage ```terraform +data "aws_region" "current" {} + +data "aws_partition" "current" {} + +resource "aws_iam_role" "example" { + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { + Service = "imagebuilder.${data.aws_partition.current.dns_suffix}" + } + }] + }) + name = "example" +} + +resource "aws_iam_role_policy_attachment" "example" { + policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/EC2ImageBuilderLifecycleExecutionPolicy" + role = aws_iam_role.example.name +} + resource "aws_imagebuilder_lifecycle_policy" "example" { + name = "name" + description = "Example description" + execution_role = aws_iam_role.example.arn + resource_type = "AMI_IMAGE" + policy_details { + action { + type = "DELETE" + } + filter { + type = "AGE" + value = 6 + retain_at_least = 10 + unit = "YEARS" + } + } + resource_selection { + tag_map = { + "key1" = "value1" + "key2" = "value2" + } + } + + depends_on = [aws_iam_role_policy_attachment.example] } ``` @@ -22,15 +68,15 @@ resource "aws_imagebuilder_lifecycle_policy" "example" { The following arguments are required: * `name` - (Required) The name of the lifecycle policy to create. -* `resource_type` - (Required) The type of Image Builder resource that the lifecycle policy applies to. -* `execution_role` - (Required) The name or Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. +* `resource_type` - (Required) The type of Image Builder resource that the lifecycle policy applies to. Valid values: `AMI_IMAGE` or `CONTAINER_IMAGE`. +* `execution_role` - (Required) The name or Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. More information about this role can be found [`here`](https://docs.aws.amazon.com/imagebuilder/latest/userguide/image-lifecycle-prerequisites.html#image-lifecycle-prereq-role). * `policy_details` - (Required) Configuration block with policy details. Detailed below. * `resource_selection` - (Required) Selection criteria for the resources that the lifecycle policy applies to. Detailed below. The following arguments are optional: * `description` - (Optional) description for the lifecycle policy. -* `tags` - (Optional) Key-value map of resource tags to assign to the configuration. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/ +* `tags` - (Optional) Key-value map of resource tags for the Image Builder Image. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ### policy_details @@ -47,7 +93,7 @@ The following arguments are optional: The following arguments are required: -* `type` - (Required) Specifies the lifecycle action to take. +* `type` - (Required) Specifies the lifecycle action to take. Valid values: `DELETE`, `DEPRECATE` or `DISABLE`. The following arguments are optional: @@ -65,13 +111,13 @@ The following arguments are optional: The following arguments are required: -* `type` - (Required) Filter resources based on either age or count. +* `type` - (Required) Filter resources based on either age or count. Valid values: `AGE` or `COUNT`. * `value` - (Required) The number of units for the time period or for the count. For example, a value of 6 might refer to six months or six AMIs. The following arguments are optional: * `retain_at_least` - (Optional) For age-based filters, this is the number of resources to keep on hand after the lifecycle DELETE action is applied. Impacted resources are only deleted if you have more than this number of resources. If you have fewer resources than this number, the impacted resource is not deleted. -* `unit` - (Optional) Defines the unit of time that the lifecycle policy uses to determine impacted resources. This is required for age-based rules. +* `unit` - (Optional) Defines the unit of time that the lifecycle policy uses to determine impacted resources. This is required for age-based rules. Valid values: `DAYS`, `WEEKS`, `MONTHS` or `YEARS`. ### exclusion_rules @@ -94,7 +140,7 @@ The following arguments are optional: The following arguments are required: -* `unit` - (Required) Defines the unit of time that the lifecycle policy uses to calculate elapsed time since the last instance launched from the AMI. For example: days, weeks, months, or years. +* `unit` - (Required) Defines the unit of time that the lifecycle policy uses to calculate elapsed time since the last instance launched from the AMI. For example: days, weeks, months, or years. Valid values: `DAYS`, `WEEKS`, `MONTHS` or `YEARS`. * `value` - (Required) The integer number of units for the time period. For example 6 (months). ### resource_selection From 0b9072f5fd745bd0a95081b31de89fb2e158585c Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 16:47:06 +0200 Subject: [PATCH 055/112] docs: fix resource reference --- website/docs/r/imagebuilder_lifecycle_policy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index 526edb5b0ee..9f0a097e679 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -76,7 +76,7 @@ The following arguments are required: The following arguments are optional: * `description` - (Optional) description for the lifecycle policy. -* `tags` - (Optional) Key-value map of resource tags for the Image Builder Image. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. +* `tags` - (Optional) Key-value map of resource tags for the Image Builder Lifecycle Policy . If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ### policy_details From c204a15166422508820f8b4fbeb436ddaadf1cbd Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 16:47:14 +0200 Subject: [PATCH 056/112] docs: fmt --- website/docs/r/imagebuilder_lifecycle_policy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index 9f0a097e679..d24c712ff66 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -76,7 +76,7 @@ The following arguments are required: The following arguments are optional: * `description` - (Optional) description for the lifecycle policy. -* `tags` - (Optional) Key-value map of resource tags for the Image Builder Lifecycle Policy . If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. +* `tags` - (Optional) Key-value map of resource tags for the Image Builder Lifecycle Policy. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. ### policy_details From 45b505785c260b92a527aa55399b0de915afd105 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 17:05:13 +0200 Subject: [PATCH 057/112] feat: removed const EBSVolumeTypeGP3 due to swap to sdkv2 --- internal/service/imagebuilder/id.go | 10 ---------- internal/service/imagebuilder/image_recipe_test.go | 12 ++++++------ 2 files changed, 6 insertions(+), 16 deletions(-) delete mode 100644 internal/service/imagebuilder/id.go diff --git a/internal/service/imagebuilder/id.go b/internal/service/imagebuilder/id.go deleted file mode 100644 index 7941a7dd559..00000000000 --- a/internal/service/imagebuilder/id.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package imagebuilder - -const ( - // Missing from upstream aws-sdk-go. - // https://github.com/aws/aws-sdk-go/issues/3751. - EBSVolumeTypeGP3 = "gp3" -) diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index 2187b41afc8..81f09b2c44d 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -11,7 +11,7 @@ import ( "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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" @@ -46,7 +46,7 @@ func TestAccImageBuilderImageRecipe_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), acctest.CheckResourceAttrAccountID(resourceName, "owner"), acctest.CheckResourceAttrRegionalARNAccountID(resourceName, "parent_image", "imagebuilder", "aws", "image/amazon-linux-2-x86/x.x.x"), - resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), + resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), ), @@ -333,12 +333,12 @@ func TestAccImageBuilderImageRecipe_BlockDeviceMappingEBS_volumeTypeGP2(t *testi CheckDestroy: testAccCheckImageRecipeDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(types.EbsVolumeTypeGp2)), + Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(awstypes.EbsVolumeTypeGp2)), Check: resource.ComposeTestCheckFunc( testAccCheckImageRecipeExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "block_device_mapping.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "block_device_mapping.*", map[string]string{ - "ebs.0.volume_type": string(types.EbsVolumeTypeGp2), + "ebs.0.volume_type": string(awstypes.EbsVolumeTypeGp2), }), ), }, @@ -363,12 +363,12 @@ func TestAccImageBuilderImageRecipe_BlockDeviceMappingEBS_volumeTypeGP3(t *testi CheckDestroy: testAccCheckImageRecipeDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, tfimagebuilder.EBSVolumeTypeGP3), + Config: testAccImageRecipeConfig_blockDeviceMappingEBSVolumeType(rName, string(awstypes.EbsVolumeTypeGp3)), Check: resource.ComposeTestCheckFunc( testAccCheckImageRecipeExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "block_device_mapping.#", "1"), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "block_device_mapping.*", map[string]string{ - "ebs.0.volume_type": tfimagebuilder.EBSVolumeTypeGP3, + "ebs.0.volume_type": string(awstypes.EbsVolumeTypeGp3), }), ), }, From 809617e8ad083aef4e6a554b54feb4b8e34b558f Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 17:22:55 +0200 Subject: [PATCH 058/112] feat: added lifecycle sweeper and cleanup --- internal/service/imagebuilder/sweep.go | 131 ++++++++++--------------- 1 file changed, 54 insertions(+), 77 deletions(-) diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index 8fcbebfdad7..8defafa78ae 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -13,7 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/sweep" "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv2" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/sweep/framework" ) func RegisterSweepers() { @@ -51,6 +51,11 @@ func RegisterSweepers() { Name: "aws_imagebuilder_infrastructure_configuration", F: sweepInfrastructureConfigurations, }) + + resource.AddTestSweepers("aws_imagebuilder_lifecycle_policy", &resource.Sweeper{ + Name: "aws_imagebuilder_lifecycle_policy", + F: sweepLifecyclePolicies, + }) } func sweepComponents(region string) error { @@ -81,19 +86,9 @@ func sweepComponents(region string) error { } for _, v := range page.ComponentVersionList { - arn := aws.ToString(v.Arn) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return fmt.Errorf("error reading ImageBuilder Components (%s): %w", arn, err) - } - r := ResourceComponent() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -133,19 +128,9 @@ func sweepDistributionConfigurations(region string) error { } for _, v := range page.DistributionConfigurationSummaryList { - arn := aws.ToString(v.Arn) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return fmt.Errorf("error reading ImageBuilder Distribution Configuration Summary (%s): %w", arn, err) - } - r := ResourceDistributionConfiguration() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -185,19 +170,9 @@ func sweepImagePipelines(region string) error { } for _, v := range page.ImagePipelineList { - arn := aws.ToString(v.Arn) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return fmt.Errorf("error reading ImageBuilder Image Pipelines (%s): %w", arn, err) - } - r := ResourceImagePipeline() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -237,19 +212,9 @@ func sweepImageRecipes(region string) error { } for _, v := range page.ImageRecipeSummaryList { - arn := aws.ToString(v.Arn) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return fmt.Errorf("error reading ImageBuilder Image Recipes (%s): %w", arn, err) - } - r := ResourceImageRecipe() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -289,19 +254,9 @@ func sweepContainerRecipes(region string) error { } for _, v := range page.ContainerRecipeSummaryList { - arn := aws.ToString(v.Arn) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return fmt.Errorf("error reading ImageBuilder Container Recipes (%s): %w", arn, err) - } - r := ResourceContainerRecipe() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -343,19 +298,9 @@ func sweepImages(region string) error { } for _, v := range page.ImageVersionList { - arn := aws.ToString(v.Arn) - - if tfresource.NotFound(err) { - continue - } - - if err != nil { - return fmt.Errorf("error reading ImageBuilder Images (%s): %w", arn, err) - } - r := ResourceImage() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -395,28 +340,60 @@ func sweepInfrastructureConfigurations(region string) error { } for _, v := range page.InfrastructureConfigurationSummaryList { - arn := aws.ToString(v.Arn) + r := ResourceInfrastructureConfiguration() + d := r.Data(nil) + d.SetId(aws.ToString(v.Arn)) + + sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + } + } + + err = sweep.SweepOrchestrator(ctx, sweepResources) - if tfresource.NotFound(err) { - continue - } + if err != nil { + return fmt.Errorf("error sweeping ImageBuilder Infrastructure Configurations (%s): %w", region, err) + } + + return nil +} - if err != nil { - return fmt.Errorf("error reading ImageBuilder Infrastructure Configurations (%s): %w", arn, err) - } +func sweepLifecyclePolicies(region string) error { + ctx := sweep.Context(region) + client, err := sweep.SharedRegionalSweepClient(ctx, region) + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + conn := client.ImageBuilderClient(ctx) + input := &imagebuilder.ListLifecyclePoliciesInput{} + sweepResources := make([]sweep.Sweepable, 0) + + pages := imagebuilder.NewListLifecyclePoliciesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if awsv2.SkipSweepError(err) { + log.Printf("[WARN] Skipping ImageBuilder Lifecycle Policies sweep for %s: %s", region, err) + return nil + } + + if err != nil { + return fmt.Errorf("error listing ImageBuilder Lifecycle Policies (%s): %w", region, err) + } + + for _, v := range page.LifecyclePolicySummaryList { r := ResourceInfrastructureConfiguration() d := r.Data(nil) - d.SetId(arn) + d.SetId(aws.ToString(v.Arn)) - sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) + sweepResources = append(sweepResources, framework.NewSweepResource(newResourceLifecyclePolicy, client)) } } err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Infrastructure Configurations (%s): %w", region, err) + return fmt.Errorf("error sweeping ImageBuilder Lifecycle Policies (%s): %w", region, err) } return nil From d35467fe5582147668e638c4f8bf41923381a218 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 17:33:43 +0200 Subject: [PATCH 059/112] feat: added arn attribute to lifecycle sweeper --- internal/service/imagebuilder/sweep.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index 8defafa78ae..f0ae6e096c9 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -382,11 +382,7 @@ func sweepLifecyclePolicies(region string) error { } for _, v := range page.LifecyclePolicySummaryList { - r := ResourceInfrastructureConfiguration() - d := r.Data(nil) - d.SetId(aws.ToString(v.Arn)) - - sweepResources = append(sweepResources, framework.NewSweepResource(newResourceLifecyclePolicy, client)) + sweepResources = append(sweepResources, framework.NewSweepResource(newResourceLifecyclePolicy, client, framework.NewAttribute("arn", v.Arn))) } } From 040b70c443acde3e37f293bb1392c13645ee28d6 Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 20:12:08 +0200 Subject: [PATCH 060/112] feat: cleanup lifecycle policy tests --- .../imagebuilder/lifecycle_policy_test.go | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 5b991073547..e7fce4a22d5 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -9,6 +9,7 @@ import ( "fmt" "testing" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/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" @@ -41,17 +42,17 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DELETE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "AGE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "10"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", "YEARS"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.%", "2"), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key1", "value1"), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key2", "value2"), - resource.TestCheckResourceAttr(resourceName, "resource_type", "AMI_IMAGE"), + resource.TestCheckResourceAttr(resourceName, "resource_type", string(awstypes.LifecyclePolicyResourceTypeAmiImage)), ), }, { @@ -80,22 +81,22 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DISABLE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", "true"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", "false"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", "DAYS"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", "value1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "AGE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "5"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", "YEARS"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), ), }, { @@ -109,7 +110,7 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", "DELETE"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", "true"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.snapshots", "true"), @@ -118,13 +119,13 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", "true"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.regions.#", "1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", "WEEKS"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "2"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", "2"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", "value1"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key2", "value2"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", "COUNT"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeCount)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "10"), ), }, From 86eb322bd42c6d95203f91a10a79984f24efd84a Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 21:17:16 +0200 Subject: [PATCH 061/112] fix: imageRecipeEBS arguments --- internal/service/imagebuilder/container_recipe.go | 1 + internal/service/imagebuilder/image_recipe.go | 1 + 2 files changed, 2 insertions(+) diff --git a/internal/service/imagebuilder/container_recipe.go b/internal/service/imagebuilder/container_recipe.go index 119d92e2527..0223f6c4cef 100644 --- a/internal/service/imagebuilder/container_recipe.go +++ b/internal/service/imagebuilder/container_recipe.go @@ -195,6 +195,7 @@ func ResourceContainerRecipe() *schema.Resource { // this is not compatible with TypeString's zero value. Type: schema.TypeBool, Optional: true, + Computed: true, ForceNew: true, }, "virtual_name": { diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index 8ff8209e808..00dfc0dbec2 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -120,6 +120,7 @@ func ResourceImageRecipe() *schema.Resource { // this is not compatible with TypeString's zero value. Type: schema.TypeBool, Optional: true, + Computed: true, ForceNew: true, }, "virtual_name": { From c8a4204284bc59aae965acddba1257239062009a Mon Sep 17 00:00:00 2001 From: Daniel Rieske Date: Sun, 14 Apr 2024 23:49:16 +0200 Subject: [PATCH 062/112] fix: notFoundException for Image resource --- internal/service/imagebuilder/distribution_configuration.go | 6 +++--- internal/service/imagebuilder/image.go | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index e8f18f4634e..c45144dd9b5 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -880,14 +880,14 @@ func flattenTargetContainerRepository(apiObject *awstypes.TargetContainerReposit } func flattenLaunchTemplateConfiguration(apiObject awstypes.LaunchTemplateConfiguration) map[string]interface{} { - tfMap := map[string]interface{}{} + tfMap := map[string]interface{}{ + "default": apiObject.SetDefaultVersion, + } if v := apiObject.LaunchTemplateId; v != nil { tfMap["launch_template_id"] = aws.ToString(v) } - tfMap["default"] = aws.Bool(apiObject.SetDefaultVersion) - if v := apiObject.AccountId; v != nil { tfMap["account_id"] = aws.ToString(v) } diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index ac72b99329b..204ba8ceea1 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -12,7 +12,6 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/aws/aws-sdk-go-v2/service/m2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -283,7 +282,7 @@ func resourceImageRead(ctx context.Context, d *schema.ResourceData, meta interfa output, err := conn.GetImage(ctx, input) - if !d.IsNewResource() && errs.IsA[*types.ResourceNotFoundException](err) { + if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { log.Printf("[WARN] Image Builder Image (%s) not found, removing from state", d.Id()) d.SetId("") return diags From 0f94c5596ab40b5aa6c4d570263aac2c5ef042cf Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 10:35:41 -0400 Subject: [PATCH 063/112] Run 'make fix-constants PKG=imagebuilder'. --- .../distribution_configuration.go | 18 +-- .../distribution_configuration_data_source.go | 2 +- ...distribution_configurations_data_source.go | 2 +- internal/service/imagebuilder/image.go | 10 +- .../service/imagebuilder/image_pipeline.go | 10 +- .../image_pipeline_data_source.go | 2 +- .../imagebuilder/image_pipeline_test.go | 18 +-- .../image_pipelines_data_source.go | 2 +- internal/service/imagebuilder/image_recipe.go | 34 +++--- .../imagebuilder/image_recipe_data_source.go | 2 +- .../service/imagebuilder/image_recipe_test.go | 4 +- .../imagebuilder/image_recipes_data_source.go | 6 +- internal/service/imagebuilder/image_test.go | 4 +- .../infrastructure_configuration.go | 18 +-- ...nfrastructure_configuration_data_source.go | 14 +-- ...frastructure_configurations_data_source.go | 6 +- .../service/imagebuilder/lifecycle_policy.go | 68 +++++------ .../imagebuilder/lifecycle_policy_test.go | 106 +++++++++--------- internal/service/imagebuilder/sweep.go | 2 +- internal/service/imagebuilder/workflow.go | 8 +- .../service/imagebuilder/workflow_test.go | 14 +-- 21 files changed, 175 insertions(+), 175 deletions(-) diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 4aae51f84f9..85402084328 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -735,11 +735,11 @@ func flattenAMIDistributionConfiguration(apiObject *awstypes.AmiDistributionConf } if v := apiObject.Description; v != nil { - tfMap["description"] = aws.ToString(v) + tfMap[names.AttrDescription] = aws.ToString(v) } if v := apiObject.KmsKeyId; v != nil { - tfMap["kms_key_id"] = aws.ToString(v) + tfMap[names.AttrKMSKeyID] = aws.ToString(v) } if v := apiObject.LaunchPermission; v != nil { @@ -747,7 +747,7 @@ func flattenAMIDistributionConfiguration(apiObject *awstypes.AmiDistributionConf } if v := apiObject.Name; v != nil { - tfMap["name"] = aws.ToString(v) + tfMap[names.AttrName] = aws.ToString(v) } if v := apiObject.TargetAccountIds; v != nil { @@ -769,7 +769,7 @@ func flattenContainerDistributionConfiguration(apiObject *awstypes.ContainerDist } if v := apiObject.Description; v != nil { - tfMap["description"] = aws.ToString(v) + tfMap[names.AttrDescription] = aws.ToString(v) } if v := apiObject.TargetRepository; v != nil { @@ -817,7 +817,7 @@ func flattenDistribution(apiObject awstypes.Distribution) map[string]interface{} } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.ToString(v) + tfMap[names.AttrRegion] = aws.ToString(v) } return tfMap @@ -871,7 +871,7 @@ func flattenTargetContainerRepository(apiObject *awstypes.TargetContainerReposit tfMap := map[string]interface{}{} if v := apiObject.RepositoryName; v != nil { - tfMap["repository_name"] = aws.ToString(v) + tfMap[names.AttrRepositoryName] = aws.ToString(v) } tfMap["service"] = string(apiObject.Service) @@ -889,7 +889,7 @@ func flattenLaunchTemplateConfiguration(apiObject awstypes.LaunchTemplateConfigu } if v := apiObject.AccountId; v != nil { - tfMap["account_id"] = aws.ToString(v) + tfMap[names.AttrAccountID] = aws.ToString(v) } return tfMap @@ -913,10 +913,10 @@ func flattenFastLaunchConfiguration(apiObject awstypes.FastLaunchConfiguration) tfMap := map[string]interface{}{} if v := apiObject.AccountId; v != nil { - tfMap["account_id"] = aws.ToString(v) + tfMap[names.AttrAccountID] = aws.ToString(v) } - tfMap["enabled"] = aws.Bool(apiObject.Enabled) + tfMap[names.AttrEnabled] = aws.Bool(apiObject.Enabled) if v := apiObject.LaunchTemplate; v != nil { tfMap[names.AttrLaunchTemplate] = []interface{}{flattenFastLaunchLaunchTemplateSpecification(v)} diff --git a/internal/service/imagebuilder/distribution_configuration_data_source.go b/internal/service/imagebuilder/distribution_configuration_data_source.go index 026f56921fa..add03999ca0 100644 --- a/internal/service/imagebuilder/distribution_configuration_data_source.go +++ b/internal/service/imagebuilder/distribution_configuration_data_source.go @@ -263,7 +263,7 @@ func dataSourceDistributionConfigurationRead(ctx context.Context, d *schema.Reso distributionConfiguration := output.DistributionConfiguration d.SetId(aws.ToString(distributionConfiguration.Arn)) - d.Set("arn", distributionConfiguration.Arn) + d.Set(names.AttrARN, distributionConfiguration.Arn) d.Set("date_created", distributionConfiguration.DateCreated) d.Set("date_updated", distributionConfiguration.DateUpdated) d.Set(names.AttrDescription, distributionConfiguration.Description) diff --git a/internal/service/imagebuilder/distribution_configurations_data_source.go b/internal/service/imagebuilder/distribution_configurations_data_source.go index 1296f1dd623..2a6eb9b4345 100644 --- a/internal/service/imagebuilder/distribution_configurations_data_source.go +++ b/internal/service/imagebuilder/distribution_configurations_data_source.go @@ -43,7 +43,7 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res input := &imagebuilder.ListDistributionConfigurationsInput{} - if v, ok := d.GetOk("filter"); ok { + if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index fc73a38ae6e..e98ec8f76b4 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -458,11 +458,11 @@ func flattenAMI(apiObject awstypes.Ami) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.AccountId; v != nil { - tfMap["account_id"] = aws.ToString(v) + tfMap[names.AttrAccountID] = aws.ToString(v) } if v := apiObject.Description; v != nil { - tfMap["description"] = aws.ToString(v) + tfMap[names.AttrDescription] = aws.ToString(v) } if v := apiObject.Image; v != nil { @@ -470,11 +470,11 @@ func flattenAMI(apiObject awstypes.Ami) map[string]interface{} { } if v := apiObject.Name; v != nil { - tfMap["name"] = aws.ToString(v) + tfMap[names.AttrName] = aws.ToString(v) } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.ToString(v) + tfMap[names.AttrRegion] = aws.ToString(v) } return tfMap @@ -502,7 +502,7 @@ func flattenContainer(apiObject awstypes.Container) map[string]interface{} { } if v := apiObject.Region; v != nil { - tfMap["region"] = aws.ToString(v) + tfMap[names.AttrRegion] = aws.ToString(v) } return tfMap diff --git a/internal/service/imagebuilder/image_pipeline.go b/internal/service/imagebuilder/image_pipeline.go index 357d62edf14..7f7b8bee36a 100644 --- a/internal/service/imagebuilder/image_pipeline.go +++ b/internal/service/imagebuilder/image_pipeline.go @@ -192,7 +192,7 @@ func ResourceImagePipeline() *schema.Resource { }, }, }, - "status": { + names.AttrStatus: { Type: schema.TypeString, Optional: true, Default: string(awstypes.PipelineStatusEnabled), @@ -297,7 +297,7 @@ func resourceImagePipelineCreate(ctx context.Context, d *schema.ResourceData, me input.Schedule = expandPipelineSchedule(v.([]interface{})[0].(map[string]interface{})) } - if v, ok := d.GetOk("status"); ok { + if v, ok := d.GetOk(names.AttrStatus); ok { input.Status = awstypes.PipelineStatus(v.(string)) } @@ -441,7 +441,7 @@ func resourceImagePipelineUpdate(ctx context.Context, d *schema.ResourceData, me input.Schedule = expandPipelineSchedule(v.([]interface{})[0].(map[string]interface{})) } - if v, ok := d.GetOk("status"); ok { + if v, ok := d.GetOk(names.AttrStatus); ok { input.Status = awstypes.PipelineStatus(v.(string)) } @@ -582,7 +582,7 @@ func flattenECRConfiguration(apiObject *awstypes.EcrConfiguration) map[string]in tfMap := map[string]interface{}{} if v := apiObject.RepositoryName; v != nil { - tfMap["repository_name"] = aws.ToString(v) + tfMap[names.AttrRepositoryName] = aws.ToString(v) } if v := apiObject.ContainerTags; v != nil { @@ -620,7 +620,7 @@ func flattenSchedule(apiObject *awstypes.Schedule) map[string]interface{} { tfMap["pipeline_execution_start_condition"] = string(apiObject.PipelineExecutionStartCondition) if v := apiObject.ScheduleExpression; v != nil { - tfMap["schedule_expression"] = aws.ToString(v) + tfMap[names.AttrScheduleExpression] = aws.ToString(v) } if v := apiObject.Timezone; v != nil { diff --git a/internal/service/imagebuilder/image_pipeline_data_source.go b/internal/service/imagebuilder/image_pipeline_data_source.go index 2a93d49a439..78af1452e46 100644 --- a/internal/service/imagebuilder/image_pipeline_data_source.go +++ b/internal/service/imagebuilder/image_pipeline_data_source.go @@ -171,7 +171,7 @@ func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, me imagePipeline := output.ImagePipeline d.SetId(aws.ToString(imagePipeline.Arn)) - d.Set("arn", imagePipeline.Arn) + d.Set(names.AttrARN, imagePipeline.Arn) d.Set("container_recipe_arn", imagePipeline.ContainerRecipeArn) d.Set("date_created", imagePipeline.DateCreated) d.Set("date_last_run", imagePipeline.DateLastRun) diff --git a/internal/service/imagebuilder/image_pipeline_test.go b/internal/service/imagebuilder/image_pipeline_test.go index 617873580ec..d238fc9701f 100644 --- a/internal/service/imagebuilder/image_pipeline_test.go +++ b/internal/service/imagebuilder/image_pipeline_test.go @@ -52,12 +52,12 @@ func TestAccImageBuilderImagePipeline_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.0.image_tests_enabled", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.0.timeout_minutes", "720"), - resource.TestCheckResourceAttrPair(resourceName, "infrastructure_configuration_arn", infrastructureConfigurationResourceName, "arn"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrPair(resourceName, "infrastructure_configuration_arn", infrastructureConfigurationResourceName, names.AttrARN), + resource.TestCheckResourceAttr(resourceName, names.AttrName, rName), resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), - resource.TestCheckResourceAttr(resourceName, "schedule.#", "0"), - resource.TestCheckResourceAttr(resourceName, "status", string(types.PipelineStatusEnabled)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "schedule.#", acctest.Ct0), + resource.TestCheckResourceAttr(resourceName, names.AttrStatus, string(types.PipelineStatusEnabled)), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct0), ), }, { @@ -468,7 +468,7 @@ func TestAccImageBuilderImagePipeline_Schedule_pipelineExecutionStartCondition(t Config: testAccImagePipelineConfig_scheduleExecutionStartCondition(rName, string(types.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "schedule.#", "1"), + resource.TestCheckResourceAttr(resourceName, "schedule.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "schedule.0.pipeline_execution_start_condition", string(types.PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable)), ), }, @@ -482,7 +482,7 @@ func TestAccImageBuilderImagePipeline_Schedule_pipelineExecutionStartCondition(t Config: testAccImagePipelineConfig_scheduleExecutionStartCondition(rName, string(types.PipelineExecutionStartConditionExpressionMatchOnly)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "schedule.#", "1"), + resource.TestCheckResourceAttr(resourceName, "schedule.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "schedule.0.pipeline_execution_start_condition", string(types.PipelineExecutionStartConditionExpressionMatchOnly)), ), }, @@ -581,7 +581,7 @@ func TestAccImageBuilderImagePipeline_status(t *testing.T) { Config: testAccImagePipelineConfig_status(rName, string(types.PipelineStatusDisabled)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "status", string(types.PipelineStatusDisabled)), + resource.TestCheckResourceAttr(resourceName, names.AttrStatus, string(types.PipelineStatusDisabled)), ), }, { @@ -593,7 +593,7 @@ func TestAccImageBuilderImagePipeline_status(t *testing.T) { Config: testAccImagePipelineConfig_status(rName, string(types.PipelineStatusEnabled)), Check: resource.ComposeTestCheckFunc( testAccCheckImagePipelineExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "status", string(types.PipelineStatusEnabled)), + resource.TestCheckResourceAttr(resourceName, names.AttrStatus, string(types.PipelineStatusEnabled)), ), }, }, diff --git a/internal/service/imagebuilder/image_pipelines_data_source.go b/internal/service/imagebuilder/image_pipelines_data_source.go index b0b907e3c4f..43e9abbc502 100644 --- a/internal/service/imagebuilder/image_pipelines_data_source.go +++ b/internal/service/imagebuilder/image_pipelines_data_source.go @@ -43,7 +43,7 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m input := &imagebuilder.ListImagePipelinesInput{} - if v, ok := d.GetOk("filter"); ok { + if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index f77bd9b1eac..a4bdd5aea3e 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -105,7 +105,7 @@ func ResourceImageRecipe() *schema.Resource { ForceNew: true, ValidateFunc: validation.IntBetween(1, 16000), }, - "volume_type": { + names.AttrVolumeType: { Type: schema.TypeString, Optional: true, ForceNew: true, @@ -490,7 +490,7 @@ func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *aw apiObject.Encrypted = aws.Bool(v) } - if v, ok := tfMap["iops"].(int); ok && v != 0 { + if v, ok := tfMap[names.AttrIOPS].(int); ok && v != 0 { apiObject.Iops = aws.Int32(int32(v)) } @@ -502,15 +502,15 @@ func expandEBSInstanceBlockDeviceSpecification(tfMap map[string]interface{}) *aw apiObject.SnapshotId = aws.String(v) } - if v, ok := tfMap["throughput"].(int); ok && v != 0 { + if v, ok := tfMap[names.AttrThroughput].(int); ok && v != 0 { apiObject.Throughput = aws.Int32(int32(v)) } - if v, ok := tfMap["volume_size"].(int); ok && v != 0 { + if v, ok := tfMap[names.AttrVolumeSize].(int); ok && v != 0 { apiObject.VolumeSize = aws.Int32(int32(v)) } - if v, ok := tfMap["volume_type"].(string); ok && v != "" { + if v, ok := tfMap[names.AttrVolumeType].(string); ok && v != "" { apiObject.VolumeType = awstypes.EbsVolumeType(v) } @@ -605,13 +605,13 @@ func flattenComponentParameter(apiObject awstypes.ComponentParameter) map[string tfMap := map[string]interface{}{} if v := apiObject.Name; v != nil { - tfMap["name"] = aws.ToString(v) + tfMap[names.AttrName] = aws.ToString(v) } if v := apiObject.Value; v != nil { // ImageBuilder API quirk // Even though Value is a slice, only one element is accepted. - tfMap["value"] = aws.StringSlice(v)[0] + tfMap[names.AttrValue] = aws.StringSlice(v)[0] } return tfMap @@ -639,34 +639,34 @@ func flattenEBSInstanceBlockDeviceSpecification(apiObject *awstypes.EbsInstanceB tfMap := map[string]interface{}{} if v := apiObject.DeleteOnTermination; v != nil { - tfMap["delete_on_termination"] = strconv.FormatBool(aws.ToBool(v)) + tfMap[names.AttrDeleteOnTermination] = strconv.FormatBool(aws.ToBool(v)) } if v := apiObject.Encrypted; v != nil { - tfMap["encrypted"] = strconv.FormatBool(aws.ToBool(v)) + tfMap[names.AttrEncrypted] = strconv.FormatBool(aws.ToBool(v)) } if v := apiObject.Iops; v != nil { - tfMap["iops"] = aws.ToInt32(v) + tfMap[names.AttrIOPS] = aws.ToInt32(v) } if v := apiObject.KmsKeyId; v != nil { - tfMap["kms_key_id"] = aws.ToString(v) + tfMap[names.AttrKMSKeyID] = aws.ToString(v) } if v := apiObject.SnapshotId; v != nil { - tfMap["snapshot_id"] = aws.ToString(v) + tfMap[names.AttrSnapshotID] = aws.ToString(v) } if v := apiObject.Throughput; v != nil { - tfMap["throughput"] = aws.ToInt32(v) + tfMap[names.AttrThroughput] = aws.ToInt32(v) } if v := apiObject.VolumeSize; v != nil { - tfMap["volume_size"] = aws.ToInt32(v) + tfMap[names.AttrVolumeSize] = aws.ToInt32(v) } - tfMap["volume_type"] = apiObject.VolumeType + tfMap[names.AttrVolumeType] = apiObject.VolumeType return tfMap } @@ -675,7 +675,7 @@ func flattenInstanceBlockDeviceMapping(apiObject awstypes.InstanceBlockDeviceMap tfMap := map[string]interface{}{} if v := apiObject.DeviceName; v != nil { - tfMap["device_name"] = aws.ToString(v) + tfMap[names.AttrDeviceName] = aws.ToString(v) } if v := apiObject.Ebs; v != nil { @@ -687,7 +687,7 @@ func flattenInstanceBlockDeviceMapping(apiObject awstypes.InstanceBlockDeviceMap } if v := apiObject.VirtualName; v != nil { - tfMap["virtual_name"] = aws.ToString(v) + tfMap[names.AttrVirtualName] = aws.ToString(v) } return tfMap diff --git a/internal/service/imagebuilder/image_recipe_data_source.go b/internal/service/imagebuilder/image_recipe_data_source.go index 37410d6ff45..75d1aed44c4 100644 --- a/internal/service/imagebuilder/image_recipe_data_source.go +++ b/internal/service/imagebuilder/image_recipe_data_source.go @@ -181,7 +181,7 @@ func dataSourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta imageRecipe := output.ImageRecipe d.SetId(aws.ToString(imageRecipe.Arn)) - d.Set("arn", imageRecipe.Arn) + d.Set(names.AttrARN, imageRecipe.Arn) d.Set("block_device_mapping", flattenInstanceBlockDeviceMappings(imageRecipe.BlockDeviceMappings)) d.Set("component", flattenComponentConfigurations(imageRecipe.Components)) d.Set("date_created", imageRecipe.DateCreated) diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index 62daa91fa9e..94ff8a7324c 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -47,8 +47,8 @@ func TestAccImageBuilderImageRecipe_basic(t *testing.T) { acctest.CheckResourceAttrAccountID(resourceName, names.AttrOwner), acctest.CheckResourceAttrRegionalARNAccountID(resourceName, "parent_image", "imagebuilder", "aws", "image/amazon-linux-2-x86/x.x.x"), resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformLinux)), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct0), + resource.TestCheckResourceAttr(resourceName, names.AttrVersion, "1.0.0"), ), }, { diff --git a/internal/service/imagebuilder/image_recipes_data_source.go b/internal/service/imagebuilder/image_recipes_data_source.go index cba3f005264..7b8e32d1214 100644 --- a/internal/service/imagebuilder/image_recipes_data_source.go +++ b/internal/service/imagebuilder/image_recipes_data_source.go @@ -35,7 +35,7 @@ func DataSourceImageRecipes() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "owner": { + names.AttrOwner: { Type: schema.TypeString, Optional: true, ValidateDiagFunc: enum.Validate[awstypes.Ownership](), @@ -50,11 +50,11 @@ func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, met input := &imagebuilder.ListImageRecipesInput{} - if v, ok := d.GetOk("owner"); ok { + if v, ok := d.GetOk(names.AttrOwner); ok { input.Owner = awstypes.Ownership(v.(string)) } - if v, ok := d.GetOk("filter"); ok { + if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } diff --git a/internal/service/imagebuilder/image_test.go b/internal/service/imagebuilder/image_test.go index 9d4cf7a6823..a16d3b163c2 100644 --- a/internal/service/imagebuilder/image_test.go +++ b/internal/service/imagebuilder/image_test.go @@ -48,8 +48,8 @@ func TestAccImageBuilderImage_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.0.image_tests_enabled", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "image_tests_configuration.0.timeout_minutes", "720"), - resource.TestCheckResourceAttrPair(resourceName, "infrastructure_configuration_arn", infrastructureConfigurationResourceName, "arn"), - resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttrPair(resourceName, "infrastructure_configuration_arn", infrastructureConfigurationResourceName, names.AttrARN), + resource.TestCheckResourceAttr(resourceName, names.AttrName, rName), resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "os_version", "Amazon Linux 2"), resource.TestCheckResourceAttr(resourceName, "output_resources.#", acctest.Ct1), diff --git a/internal/service/imagebuilder/infrastructure_configuration.go b/internal/service/imagebuilder/infrastructure_configuration.go index 6dd7da3b90a..8f763d89b10 100644 --- a/internal/service/imagebuilder/infrastructure_configuration.go +++ b/internal/service/imagebuilder/infrastructure_configuration.go @@ -196,7 +196,7 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re input.ResourceTags = Tags(tftags.New(ctx, v.(map[string]interface{}))) } - if v, ok := d.GetOk("security_group_ids"); ok && v.(*schema.Set).Len() > 0 { + if v, ok := d.GetOk(names.AttrSecurityGroupIDs); ok && v.(*schema.Set).Len() > 0 { input.SecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set)) } @@ -289,11 +289,11 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso } else { d.Set("logging", nil) } - d.Set("name", infrastructureConfiguration.Name) - d.Set("resource_tags", KeyValueTags(ctx, infrastructureConfiguration.ResourceTags).Map()) - d.Set("security_group_ids", infrastructureConfiguration.SecurityGroupIds) - d.Set("sns_topic_arn", infrastructureConfiguration.SnsTopicArn) - d.Set("subnet_id", infrastructureConfiguration.SubnetId) + d.Set(names.AttrName, infrastructureConfiguration.Name) + d.Set(names.AttrResourceTags, KeyValueTags(ctx, infrastructureConfiguration.ResourceTags).Map()) + d.Set(names.AttrSecurityGroupIDs, infrastructureConfiguration.SecurityGroupIds) + d.Set(names.AttrSNSTopicARN, infrastructureConfiguration.SnsTopicArn) + d.Set(names.AttrSubnetID, infrastructureConfiguration.SubnetId) setTagsOut(ctx, infrastructureConfiguration.Tags) @@ -352,7 +352,7 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re input.ResourceTags = Tags(tftags.New(ctx, v.(map[string]interface{}))) } - if v, ok := d.GetOk("security_group_ids"); ok && v.(*schema.Set).Len() > 0 { + if v, ok := d.GetOk(names.AttrSecurityGroupIDs); ok && v.(*schema.Set).Len() > 0 { input.SecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set)) } @@ -501,11 +501,11 @@ func flattenS3Logs(apiObject *awstypes.S3Logs) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.S3BucketName; v != nil { - tfMap["s3_bucket_name"] = aws.ToString(v) + tfMap[names.AttrS3BucketName] = aws.ToString(v) } if v := apiObject.S3KeyPrefix; v != nil { - tfMap["s3_key_prefix"] = aws.ToString(v) + tfMap[names.AttrS3KeyPrefix] = aws.ToString(v) } return tfMap diff --git a/internal/service/imagebuilder/infrastructure_configuration_data_source.go b/internal/service/imagebuilder/infrastructure_configuration_data_source.go index cf4a201b50d..6994a164701 100644 --- a/internal/service/imagebuilder/infrastructure_configuration_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configuration_data_source.go @@ -144,7 +144,7 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re infrastructureConfiguration := output.InfrastructureConfiguration d.SetId(aws.ToString(infrastructureConfiguration.Arn)) - d.Set("arn", infrastructureConfiguration.Arn) + d.Set(names.AttrARN, infrastructureConfiguration.Arn) d.Set("date_created", infrastructureConfiguration.DateCreated) d.Set("date_updated", infrastructureConfiguration.DateUpdated) d.Set(names.AttrDescription, infrastructureConfiguration.Description) @@ -163,12 +163,12 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re } else { d.Set("logging", nil) } - d.Set("name", infrastructureConfiguration.Name) - d.Set("resource_tags", KeyValueTags(ctx, infrastructureConfiguration.ResourceTags).Map()) - d.Set("security_group_ids", infrastructureConfiguration.SecurityGroupIds) - d.Set("sns_topic_arn", infrastructureConfiguration.SnsTopicArn) - d.Set("subnet_id", infrastructureConfiguration.SubnetId) - d.Set("tags", KeyValueTags(ctx, infrastructureConfiguration.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) + d.Set(names.AttrName, infrastructureConfiguration.Name) + d.Set(names.AttrResourceTags, KeyValueTags(ctx, infrastructureConfiguration.ResourceTags).Map()) + d.Set(names.AttrSecurityGroupIDs, infrastructureConfiguration.SecurityGroupIds) + d.Set(names.AttrSNSTopicARN, infrastructureConfiguration.SnsTopicArn) + d.Set(names.AttrSubnetID, infrastructureConfiguration.SubnetId) + d.Set(names.AttrTags, KeyValueTags(ctx, infrastructureConfiguration.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) d.Set("terminate_instance_on_failure", infrastructureConfiguration.TerminateInstanceOnFailure) return diags diff --git a/internal/service/imagebuilder/infrastructure_configurations_data_source.go b/internal/service/imagebuilder/infrastructure_configurations_data_source.go index 6ee6d8560e5..12fc1554fb9 100644 --- a/internal/service/imagebuilder/infrastructure_configurations_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configurations_data_source.go @@ -27,8 +27,8 @@ func DataSourceInfrastructureConfigurations() *schema.Resource { Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "filter": namevaluesfilters.Schema(), - "names": { + names.AttrFilter: namevaluesfilters.Schema(), + names.AttrNames: { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, @@ -43,7 +43,7 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R input := &imagebuilder.ListInfrastructureConfigurationsInput{} - if v, ok := d.GetOk("filter"); ok { + if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index e901333e9ee..96bf8b09c72 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -55,8 +55,8 @@ func (r *resourceLifecyclePolicy) Metadata(_ context.Context, request resource.M func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ - "arn": framework.ARNAttributeComputedOnly(), - "description": schema.StringAttribute{ + names.AttrARN: framework.ARNAttributeComputedOnly(), + names.AttrDescription: schema.StringAttribute{ Optional: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.UseStateForUnknown(), @@ -65,14 +65,14 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem "execution_role": schema.StringAttribute{ Required: true, }, - "id": framework.IDAttribute(), - "name": schema.StringAttribute{ + names.AttrID: framework.IDAttribute(), + names.AttrName: schema.StringAttribute{ Required: true, PlanModifiers: []planmodifier.String{ stringplanmodifier.RequiresReplace(), }, }, - "resource_type": schema.StringAttribute{ + names.AttrResourceType: schema.StringAttribute{ Optional: true, Computed: true, PlanModifiers: []planmodifier.String{ @@ -82,7 +82,7 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem enum.FrameworkValidate[awstypes.LifecyclePolicyResourceType](), }, }, - "status": schema.StringAttribute{ + names.AttrStatus: schema.StringAttribute{ Optional: true, Computed: true, PlanModifiers: []planmodifier.String{ @@ -103,14 +103,14 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, NestedObject: schema.NestedBlockObject{ Blocks: map[string]schema.Block{ - "action": schema.ListNestedBlock{ + names.AttrAction: schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "type": schema.StringAttribute{ + names.AttrType: schema.StringAttribute{ Required: true, Validators: []validator.String{ enum.FrameworkValidate[awstypes.LifecyclePolicyDetailActionType](), @@ -151,26 +151,26 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, }, }, - "filter": schema.ListNestedBlock{ + names.AttrFilter: schema.ListNestedBlock{ Validators: []validator.List{ listvalidator.SizeAtMost(1), listvalidator.IsRequired(), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "type": schema.StringAttribute{ + names.AttrType: schema.StringAttribute{ Required: true, Validators: []validator.String{ enum.FrameworkValidate[awstypes.LifecyclePolicyDetailFilterType](), }, }, - "value": schema.Int64Attribute{ + names.AttrValue: schema.Int64Attribute{ Required: true, }, "retain_at_least": schema.Int64Attribute{ Optional: true, }, - "unit": schema.StringAttribute{ + names.AttrUnit: schema.StringAttribute{ Optional: true, Validators: []validator.String{ enum.FrameworkValidate[awstypes.LifecyclePolicyTimeUnit](), @@ -220,13 +220,13 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "unit": schema.StringAttribute{ + names.AttrUnit: schema.StringAttribute{ Required: true, Validators: []validator.String{ enum.FrameworkValidate[awstypes.LifecyclePolicyTimeUnit](), }, }, - "value": schema.Int64Attribute{ + names.AttrValue: schema.Int64Attribute{ Required: true, }, }, @@ -261,7 +261,7 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ - "name": schema.StringAttribute{ + names.AttrName: schema.StringAttribute{ Required: true, }, "semantic_version": schema.StringAttribute{ @@ -546,7 +546,7 @@ func (r *resourceLifecyclePolicy) Delete(ctx context.Context, req resource.Delet } func (r *resourceLifecyclePolicy) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp) + resource.ImportStatePassthroughID(ctx, path.Root(names.AttrID), req, resp) } func (r *resourceLifecyclePolicy) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { @@ -856,8 +856,8 @@ func flattenPolicyDetails(ctx context.Context, apiObject []awstypes.LifecyclePol diags.Append(d...) obj := map[string]attr.Value{ - "action": action, - "filter": filter, + names.AttrAction: action, + names.AttrFilter: filter, "exclusion_rules": exclusionRules, } @@ -886,7 +886,7 @@ func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolic obj := map[string]attr.Value{ "include_resources": includeResources, - "type": flex.StringValueToFramework(ctx, apiObject.Type), + names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), } objVal, d := types.ObjectValue(resourceActionAttrTypes, obj) @@ -930,10 +930,10 @@ func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolic } obj := map[string]attr.Value{ - "type": flex.StringValueToFramework(ctx, apiObject.Type), - "value": flex.Int32ToFramework(ctx, apiObject.Value), + names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), + names.AttrValue: flex.Int32ToFramework(ctx, apiObject.Value), "retain_at_least": flex.Int32ToFramework(ctx, apiObject.RetainAtLeast), - "unit": flex.StringValueToFramework(ctx, apiObject.Unit), + names.AttrUnit: flex.StringValueToFramework(ctx, apiObject.Unit), } objVal, d := types.ObjectValue(resourceFilterAttrTypes, obj) @@ -1007,8 +1007,8 @@ func flattenExclusionRulesAMISLastLaunched(ctx context.Context, apiObject *awsty } obj := map[string]attr.Value{ - "unit": flex.StringValueToFramework(ctx, apiObject.Unit), - "value": flex.Int32ToFramework(ctx, apiObject.Value), + names.AttrUnit: flex.StringValueToFramework(ctx, apiObject.Unit), + names.AttrValue: flex.Int32ToFramework(ctx, apiObject.Value), } objVal, d := types.ObjectValue(resourceLastLaunchedAttrTypes, obj) @@ -1057,7 +1057,7 @@ func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.L for _, recipe := range apiObject { obj := map[string]attr.Value{ - "name": flex.StringToFramework(ctx, recipe.Name), + names.AttrName: flex.StringToFramework(ctx, recipe.Name), "semantic_version": flex.StringToFramework(ctx, recipe.SemanticVersion), } @@ -1140,13 +1140,13 @@ type resourceLastLaunchedData struct { } var resourcePolicyDetailAttrTypes = map[string]attr.Type{ - "action": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceActionAttrTypes}}, - "filter": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceFilterAttrTypes}}, + names.AttrAction: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceActionAttrTypes}}, + names.AttrFilter: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceFilterAttrTypes}}, "exclusion_rules": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceExclusionRulesAttrTypes}}, } var resourceActionAttrTypes = map[string]attr.Type{ - "type": types.StringType, + names.AttrType: types.StringType, "include_resources": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceIncludeResourcesAttrTypes}}, } @@ -1157,10 +1157,10 @@ var resourceIncludeResourcesAttrTypes = map[string]attr.Type{ } var resourceFilterAttrTypes = map[string]attr.Type{ - "type": types.StringType, - "value": types.Int64Type, + names.AttrType: types.StringType, + names.AttrValue: types.Int64Type, "retain_at_least": types.Int64Type, - "unit": types.StringType, + names.AttrUnit: types.StringType, } var resourceExclusionRulesAttrTypes = map[string]attr.Type{ @@ -1177,8 +1177,8 @@ var resourceAMISAttrTypes = map[string]attr.Type{ } var resourceLastLaunchedAttrTypes = map[string]attr.Type{ - "unit": types.StringType, - "value": types.Int64Type, + names.AttrUnit: types.StringType, + names.AttrValue: types.Int64Type, } var resourceResourceSelectionAttrTypes = map[string]attr.Type{ @@ -1187,6 +1187,6 @@ var resourceResourceSelectionAttrTypes = map[string]attr.Type{ } var resourceRecipeAttrTypes = map[string]attr.Type{ - "name": types.StringType, + names.AttrName: types.StringType, "semantic_version": types.StringType, } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index e7fce4a22d5..7aa051bf6ee 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -36,23 +36,23 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { Config: testAccLifecyclePolicyConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - acctest.CheckResourceAttrRegionalARN(resourceName, "arn", "imagebuilder", fmt.Sprintf("lifecycle-policy/%s", rName)), - resource.TestCheckResourceAttr(resourceName, "description", "Used for setting lifecycle policies"), + acctest.CheckResourceAttrRegionalARN(resourceName, names.AttrARN, "imagebuilder", fmt.Sprintf("lifecycle-policy/%s", rName)), + resource.TestCheckResourceAttr(resourceName, names.AttrDescription, "Used for setting lifecycle policies"), resource.TestCheckResourceAttrSet(resourceName, "execution_role"), - resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, names.AttrName, rName), + resource.TestCheckResourceAttr(resourceName, "policy_details.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "10"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", acctest.Ct10), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), - resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.%", "2"), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key1", "value1"), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key2", "value2"), - resource.TestCheckResourceAttr(resourceName, "resource_type", string(awstypes.LifecyclePolicyResourceTypeAmiImage)), + resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.%", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key2", acctest.CtValue2), + resource.TestCheckResourceAttr(resourceName, names.AttrResourceType, string(awstypes.LifecyclePolicyResourceTypeAmiImage)), ), }, { @@ -79,20 +79,20 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { Config: testAccLifecyclePolicyConfig_policyDetails(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", "true"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", "false"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", "value1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "5"), @@ -108,25 +108,25 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "policy_details.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", "true"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.snapshots", "true"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", "true"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.regions.#", "1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.snapshots", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.regions.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "2"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", "2"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", "value1"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key2", "value2"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", "1"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key2", acctest.CtValue2), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeCount)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "10"), + resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", acctest.Ct10), ), }, }, @@ -148,8 +148,8 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { Config: testAccLifecyclePolicyConfig_resourceSelection(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.name", rName), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.semantic_version", "1.0.0"), ), @@ -163,8 +163,8 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { Config: testAccLifecyclePolicyConfig_resourceSelectionUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "resource_selection.#", "1"), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", "1"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.name", rName), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.semantic_version", "2.0.0"), ), @@ -185,11 +185,11 @@ func TestAccImageBuilderLifecyclePolicy_tags(t *testing.T) { CheckDestroy: testAccCheckLifecyclePolicyDestroy(ctx), Steps: []resource.TestStep{ { - Config: testAccLifecyclePolicyConfig_tags1(rName, "key1", "value1"), + Config: testAccLifecyclePolicyConfig_tags1(rName, acctest.CtKey1, acctest.CtValue1), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey1, acctest.CtValue1), ), }, { @@ -198,20 +198,20 @@ func TestAccImageBuilderLifecyclePolicy_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccLifecyclePolicyConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccLifecyclePolicyConfig_tags2(rName, acctest.CtKey1, acctest.CtValue1Updated, acctest.CtKey2, acctest.CtValue2), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey1, acctest.CtValue1Updated), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey2, acctest.CtValue2), ), }, { - Config: testAccLifecyclePolicyConfig_tags1(rName, "key2", "value2"), + Config: testAccLifecyclePolicyConfig_tags1(rName, acctest.CtKey2, acctest.CtValue2), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey2, acctest.CtValue2), ), }, }, diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index f0ae6e096c9..a855095ab25 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -382,7 +382,7 @@ func sweepLifecyclePolicies(region string) error { } for _, v := range page.LifecyclePolicySummaryList { - sweepResources = append(sweepResources, framework.NewSweepResource(newResourceLifecyclePolicy, client, framework.NewAttribute("arn", v.Arn))) + sweepResources = append(sweepResources, framework.NewSweepResource(newResourceLifecyclePolicy, client, framework.NewAttribute(names.AttrARN, v.Arn))) } } diff --git a/internal/service/imagebuilder/workflow.go b/internal/service/imagebuilder/workflow.go index 3cb0e1fd4b0..df32f18a0bd 100644 --- a/internal/service/imagebuilder/workflow.go +++ b/internal/service/imagebuilder/workflow.go @@ -83,7 +83,7 @@ func ResourceWorkflow() *schema.Resource { }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), - "type": { + names.AttrType: { Type: schema.TypeString, Required: true, ForceNew: true, @@ -113,9 +113,9 @@ func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta in input := &imagebuilder.CreateWorkflowInput{ ClientToken: aws.String(id.UniqueId()), - Name: aws.String(d.Get("name").(string)), - SemanticVersion: aws.String(d.Get("version").(string)), - Type: awstypes.WorkflowType(d.Get("type").(string)), + Name: aws.String(d.Get(names.AttrName).(string)), + SemanticVersion: aws.String(d.Get(names.AttrVersion).(string)), + Type: awstypes.WorkflowType(d.Get(names.AttrType).(string)), Tags: getTagsIn(ctx), } diff --git a/internal/service/imagebuilder/workflow_test.go b/internal/service/imagebuilder/workflow_test.go index 30cfe958c7b..3d10667a499 100644 --- a/internal/service/imagebuilder/workflow_test.go +++ b/internal/service/imagebuilder/workflow_test.go @@ -41,13 +41,13 @@ func TestAccImageBuilderWorkflow_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "change_description", ""), resource.TestMatchResourceAttr(resourceName, "data", regexache.MustCompile(`schemaVersion`)), acctest.CheckResourceAttrRFC3339(resourceName, "date_created"), - resource.TestCheckResourceAttr(resourceName, "description", ""), - resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), - resource.TestCheckResourceAttr(resourceName, "name", rName), - acctest.CheckResourceAttrAccountID(resourceName, "owner"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "type", string(types.WorkflowTypeTest)), - resource.TestCheckResourceAttr(resourceName, "version", "1.0.0"), + resource.TestCheckResourceAttr(resourceName, names.AttrDescription, ""), + resource.TestCheckResourceAttr(resourceName, names.AttrKMSKeyID, ""), + resource.TestCheckResourceAttr(resourceName, names.AttrName, rName), + acctest.CheckResourceAttrAccountID(resourceName, names.AttrOwner), + resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct0), + resource.TestCheckResourceAttr(resourceName, names.AttrType, string(types.WorkflowTypeTest)), + resource.TestCheckResourceAttr(resourceName, names.AttrVersion, "1.0.0"), ), }, { From 625842df2645986b7a49ac7230fc0e9d2f3af1d4 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 10:38:26 -0400 Subject: [PATCH 064/112] Remove unsued code. --- .../imagebuilder_filters.go | 36 ------------------- 1 file changed, 36 deletions(-) delete mode 100644 internal/generate/namevaluesfiltersv2/imagebuilder_filters.go diff --git a/internal/generate/namevaluesfiltersv2/imagebuilder_filters.go b/internal/generate/namevaluesfiltersv2/imagebuilder_filters.go deleted file mode 100644 index 896acfc4fc8..00000000000 --- a/internal/generate/namevaluesfiltersv2/imagebuilder_filters.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -//go:build !generate -// +build !generate - -package namevaluesfiltersv2 - -import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports - "github.com/aws/aws-sdk-go-v2/aws" - imagebuildertypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" -) - -// []*SERVICE.Filter handling - -// ImagebuilderFilters returns imagebuilder service filters. -func (filters NameValuesFilters) ImagebuilderFilters() []imagebuildertypes.Filter { - m := filters.Map() - - if len(m) == 0 { - return nil - } - - result := make([]imagebuildertypes.Filter, 0, len(m)) - - for k, v := range m { - filter := imagebuildertypes.Filter{ - Name: aws.String(k), - Values: v, - } - - result = append(result, filter) - } - - return result -} From 8094e237c3431d2ad59d6531e0b08984112e8587 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 10:38:37 -0400 Subject: [PATCH 065/112] Run 'make fmt'. --- .../service/imagebuilder/lifecycle_policy.go | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 96bf8b09c72..b2d907bdaab 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -856,8 +856,8 @@ func flattenPolicyDetails(ctx context.Context, apiObject []awstypes.LifecyclePol diags.Append(d...) obj := map[string]attr.Value{ - names.AttrAction: action, - names.AttrFilter: filter, + names.AttrAction: action, + names.AttrFilter: filter, "exclusion_rules": exclusionRules, } @@ -886,7 +886,7 @@ func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolic obj := map[string]attr.Value{ "include_resources": includeResources, - names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), + names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), } objVal, d := types.ObjectValue(resourceActionAttrTypes, obj) @@ -930,10 +930,10 @@ func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolic } obj := map[string]attr.Value{ - names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), - names.AttrValue: flex.Int32ToFramework(ctx, apiObject.Value), + names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), + names.AttrValue: flex.Int32ToFramework(ctx, apiObject.Value), "retain_at_least": flex.Int32ToFramework(ctx, apiObject.RetainAtLeast), - names.AttrUnit: flex.StringValueToFramework(ctx, apiObject.Unit), + names.AttrUnit: flex.StringValueToFramework(ctx, apiObject.Unit), } objVal, d := types.ObjectValue(resourceFilterAttrTypes, obj) @@ -1057,7 +1057,7 @@ func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.L for _, recipe := range apiObject { obj := map[string]attr.Value{ - names.AttrName: flex.StringToFramework(ctx, recipe.Name), + names.AttrName: flex.StringToFramework(ctx, recipe.Name), "semantic_version": flex.StringToFramework(ctx, recipe.SemanticVersion), } @@ -1140,13 +1140,13 @@ type resourceLastLaunchedData struct { } var resourcePolicyDetailAttrTypes = map[string]attr.Type{ - names.AttrAction: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceActionAttrTypes}}, - names.AttrFilter: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceFilterAttrTypes}}, + names.AttrAction: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceActionAttrTypes}}, + names.AttrFilter: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceFilterAttrTypes}}, "exclusion_rules": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceExclusionRulesAttrTypes}}, } var resourceActionAttrTypes = map[string]attr.Type{ - names.AttrType: types.StringType, + names.AttrType: types.StringType, "include_resources": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceIncludeResourcesAttrTypes}}, } @@ -1157,10 +1157,10 @@ var resourceIncludeResourcesAttrTypes = map[string]attr.Type{ } var resourceFilterAttrTypes = map[string]attr.Type{ - names.AttrType: types.StringType, - names.AttrValue: types.Int64Type, + names.AttrType: types.StringType, + names.AttrValue: types.Int64Type, "retain_at_least": types.Int64Type, - names.AttrUnit: types.StringType, + names.AttrUnit: types.StringType, } var resourceExclusionRulesAttrTypes = map[string]attr.Type{ @@ -1187,6 +1187,6 @@ var resourceResourceSelectionAttrTypes = map[string]attr.Type{ } var resourceRecipeAttrTypes = map[string]attr.Type{ - names.AttrName: types.StringType, + names.AttrName: types.StringType, "semantic_version": types.StringType, } From 4590b1b522a65aabd6c7bb2e47fde14445a51d33 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 10:38:50 -0400 Subject: [PATCH 066/112] Import 'names'. --- internal/service/imagebuilder/sweep.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index a855095ab25..846b401835b 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/sweep" "github.com/hashicorp/terraform-provider-aws/internal/sweep/awsv2" "github.com/hashicorp/terraform-provider-aws/internal/sweep/framework" + "github.com/hashicorp/terraform-provider-aws/names" ) func RegisterSweepers() { From 20d588005c78f714bf8fd9e2d9e47d8448dd0591 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 10:51:25 -0400 Subject: [PATCH 067/112] r/aws_imagebuilder_component: Reduce visibility. --- internal/service/imagebuilder/component.go | 69 +++++++++++-------- .../service/imagebuilder/component_test.go | 45 ++++-------- internal/service/imagebuilder/export_tests.go | 2 + .../imagebuilder/service_package_gen.go | 2 +- internal/service/imagebuilder/sweep.go | 2 +- 5 files changed, 58 insertions(+), 62 deletions(-) diff --git a/internal/service/imagebuilder/component.go b/internal/service/imagebuilder/component.go index 1ac9e546850..75f9b7e8f6b 100644 --- a/internal/service/imagebuilder/component.go +++ b/internal/service/imagebuilder/component.go @@ -12,6 +12,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -20,18 +21,20 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_component", name="Component") // @Tags(identifierAttribute="id") -func ResourceComponent() *schema.Resource { +func resourceComponent() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceComponentCreate, ReadWithoutTimeout: resourceComponentRead, UpdateWithoutTimeout: resourceComponentUpdate, DeleteWithoutTimeout: resourceComponentDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -182,10 +185,6 @@ func resourceComponentCreate(ctx context.Context, d *schema.ResourceData, meta i return sdkdiag.AppendErrorf(diags, "creating Image Builder Component: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Component: empty result") - } - d.SetId(aws.ToString(output.ComponentBuildVersionArn)) return append(diags, resourceComponentRead(ctx, d, meta)...) @@ -195,28 +194,18 @@ func resourceComponentRead(ctx context.Context, d *schema.ResourceData, meta int var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetComponentInput{ - ComponentBuildVersionArn: aws.String(d.Id()), - } - - output, err := conn.GetComponent(ctx, input) + component, err := findComponentByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Component (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Component (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Component (%s): %s", d.Id(), err) } - if output == nil || output.Component == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Component (%s): empty result", d.Id()) - } - - component := output.Component - d.Set(names.AttrARN, component.Arn) d.Set("change_description", component.ChangeDescription) d.Set("data", component.Data) @@ -228,12 +217,11 @@ func resourceComponentRead(ctx context.Context, d *schema.ResourceData, meta int d.Set(names.AttrOwner, component.Owner) d.Set("platform", component.Platform) d.Set("supported_os_versions", component.SupportedOsVersions) - - setTagsOut(ctx, component.Tags) - d.Set(names.AttrType, component.Type) d.Set(names.AttrVersion, component.Version) + setTagsOut(ctx, component.Tags) + return diags } @@ -247,21 +235,19 @@ func resourceComponentUpdate(ctx context.Context, d *schema.ResourceData, meta i func resourceComponentDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics + conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) if v, ok := d.GetOk(names.AttrSkipDestroy); ok && v.(bool) { - log.Printf("[DEBUG] Retaining Imagebuilder Component version %q", d.Id()) + log.Printf("[DEBUG] Retaining Image Builder Component version %q", d.Id()) return diags } - conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - - input := &imagebuilder.DeleteComponentInput{ + log.Printf("[DEBUG] Deleting Image Builder Component: %s", d.Id()) + _, err := conn.DeleteComponent(ctx, &imagebuilder.DeleteComponentInput{ ComponentBuildVersionArn: aws.String(d.Id()), - } - - _, err := conn.DeleteComponent(ctx, input) + }) - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -271,3 +257,28 @@ func resourceComponentDelete(ctx context.Context, d *schema.ResourceData, meta i return diags } + +func findComponentByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.Component, error) { + input := &imagebuilder.GetComponentInput{ + ComponentBuildVersionArn: aws.String(arn), + } + + output, err := conn.GetComponent(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.Component == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Component, nil +} diff --git a/internal/service/imagebuilder/component_test.go b/internal/service/imagebuilder/component_test.go index 39624e3c24f..c6b641a7164 100644 --- a/internal/service/imagebuilder/component_test.go +++ b/internal/service/imagebuilder/component_test.go @@ -9,17 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/create" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -47,10 +44,10 @@ func TestAccImageBuilderComponent_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, names.AttrKMSKeyID, ""), resource.TestCheckResourceAttr(resourceName, names.AttrName, rName), acctest.CheckResourceAttrAccountID(resourceName, names.AttrOwner), - resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformLinux)), + resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformLinux)), resource.TestCheckResourceAttr(resourceName, "supported_os_versions.#", acctest.Ct0), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct0), - resource.TestCheckResourceAttr(resourceName, names.AttrType, string(types.ComponentTypeBuild)), + resource.TestCheckResourceAttr(resourceName, names.AttrType, string(awstypes.ComponentTypeBuild)), resource.TestCheckResourceAttr(resourceName, names.AttrVersion, "1.0.0"), ), }, @@ -187,7 +184,7 @@ func TestAccImageBuilderComponent_Platform_windows(t *testing.T) { Config: testAccComponentConfig_platformWindows(rName), Check: resource.ComposeTestCheckFunc( testAccCheckComponentExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "platform", string(types.PlatformWindows)), + resource.TestCheckResourceAttr(resourceName, "platform", string(awstypes.PlatformWindows)), ), }, { @@ -310,49 +307,35 @@ func testAccCheckComponentDestroy(ctx context.Context) resource.TestCheckFunc { continue } - input := &imagebuilder.GetComponentInput{ - ComponentBuildVersionArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetComponent(ctx, input) + _, err := tfimagebuilder.FindComponentByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, "tfimagebuilder", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Component (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Component %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckComponentExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckComponentExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetComponentInput{ - ComponentBuildVersionArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetComponent(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Component (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindComponentByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 017cee974c8..bc1f150af65 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -5,7 +5,9 @@ package imagebuilder // Exports for use in tests only. var ( + ResourceComponent = resourceComponent ResourceLifecyclePolicy = newResourceLifecyclePolicy + FindComponentByARN = findComponentByARN FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 7a9864a2906..b4b713de802 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -93,7 +93,7 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePackageSDKResource { return []*types.ServicePackageSDKResource{ { - Factory: ResourceComponent, + Factory: resourceComponent, TypeName: "aws_imagebuilder_component", Name: "Component", Tags: &types.ServicePackageResourceTags{ diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index 846b401835b..89d3685950d 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -87,7 +87,7 @@ func sweepComponents(region string) error { } for _, v := range page.ComponentVersionList { - r := ResourceComponent() + r := resourceComponent() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) From 6edea27faaa417b4b9bb51f971eed1abfcb9b6f3 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 10:56:48 -0400 Subject: [PATCH 068/112] d/aws_imagebuilder_component: Reduce visibility. --- .../imagebuilder/component_data_source.go | 28 ++++++------------- .../imagebuilder/service_package_gen.go | 4 ++- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/internal/service/imagebuilder/component_data_source.go b/internal/service/imagebuilder/component_data_source.go index bfa3a636cb2..54a08e2d69e 100644 --- a/internal/service/imagebuilder/component_data_source.go +++ b/internal/service/imagebuilder/component_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -17,8 +16,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_component") -func DataSourceComponent() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_component", name="Component") +// @Tags +func dataSourceComponent() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceComponentRead, @@ -86,26 +86,16 @@ func dataSourceComponentRead(ctx context.Context, d *schema.ResourceData, meta i var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetComponentInput{} - - if v, ok := d.GetOk(names.AttrARN); ok { - input.ComponentBuildVersionArn = aws.String(v.(string)) - } - - output, err := conn.GetComponent(ctx, input) + arn := d.Get(names.AttrARN).(string) + component, err := findComponentByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Component: %s", err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Component (%s): %s", arn, err) } - if output == nil || output.Component == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Component: empty result") - } - - component := output.Component - - d.SetId(aws.ToString(component.Arn)) - d.Set(names.AttrARN, component.Arn) + arn = aws.ToString(component.Arn) + d.SetId(arn) + d.Set(names.AttrARN, arn) d.Set("change_description", component.ChangeDescription) d.Set("data", component.Data) d.Set("date_created", component.DateCreated) diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index b4b713de802..f4123fc7bd0 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -33,8 +33,10 @@ func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.Servic func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePackageSDKDataSource { return []*types.ServicePackageSDKDataSource{ { - Factory: DataSourceComponent, + Factory: dataSourceComponent, TypeName: "aws_imagebuilder_component", + Name: "Component", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceComponents, From f51fcadf75d714a9158d90b864cc2db7fff52e94 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:02:42 -0400 Subject: [PATCH 069/112] d/aws_imagebuilder_components: Reduce visibility. --- .../imagebuilder/components_data_source.go | 46 +++++++++++++------ .../imagebuilder/service_package_gen.go | 2 +- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/internal/service/imagebuilder/components_data_source.go b/internal/service/imagebuilder/components_data_source.go index 152e1018487..2b073d63de6 100644 --- a/internal/service/imagebuilder/components_data_source.go +++ b/internal/service/imagebuilder/components_data_source.go @@ -16,13 +16,15 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" namevaluesfiltersv2 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v2" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKDataSource("aws_imagebuilder_components", name="Components") -func DataSourceComponents() *schema.Resource { +func dataSourceComponents() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceComponentsRead, + Schema: map[string]*schema.Schema{ names.AttrARNs: { Type: schema.TypeSet, @@ -50,30 +52,44 @@ func dataSourceComponentsRead(ctx context.Context, d *schema.ResourceData, meta input := &imagebuilder.ListComponentsInput{} - if v, ok := d.GetOk(names.AttrOwner); ok { - input.Owner = awstypes.Ownership(v.(string)) - } - if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } - out, err := conn.ListComponents(ctx, input) - - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Components: %s", err) + if v, ok := d.GetOk(names.AttrOwner); ok { + input.Owner = awstypes.Ownership(v.(string)) } - var arns, nms []string + components, err := findComponents(ctx, conn, input) - for _, r := range out.ComponentVersionList { - arns = append(arns, aws.ToString(r.Arn)) - nms = append(nms, aws.ToString(r.Name)) + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Image Builder Components: %s", err) } d.SetId(meta.(*conns.AWSClient).Region) - d.Set(names.AttrARNs, arns) - d.Set(names.AttrNames, nms) + d.Set(names.AttrARNs, tfslices.ApplyToAll(components, func(v awstypes.ComponentVersion) string { + return aws.ToString(v.Arn) + })) + d.Set(names.AttrNames, tfslices.ApplyToAll(components, func(v awstypes.ComponentVersion) string { + return aws.ToString(v.Name) + })) return diags } + +func findComponents(ctx context.Context, conn *imagebuilder.Client, input *imagebuilder.ListComponentsInput) ([]awstypes.ComponentVersion, error) { + var output []awstypes.ComponentVersion + + pages := imagebuilder.NewListComponentsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.ComponentVersionList...) + } + + return output, nil +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index f4123fc7bd0..1917b9e45a6 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -39,7 +39,7 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceComponents, + Factory: dataSourceComponents, TypeName: "aws_imagebuilder_components", Name: "Components", }, From 1a2344172d4226fdfcbc653da6c76fa51ff93674 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:20:55 -0400 Subject: [PATCH 070/112] r/aws_imagebuilder_container_recipe: Reduce visibility. --- .../service/imagebuilder/container_recipe.go | 74 ++++++++++++------- .../imagebuilder/container_recipe_test.go | 36 +++------ internal/service/imagebuilder/export_tests.go | 2 + .../imagebuilder/service_package_gen.go | 2 +- 4 files changed, 60 insertions(+), 54 deletions(-) diff --git a/internal/service/imagebuilder/container_recipe.go b/internal/service/imagebuilder/container_recipe.go index 92c82008c0a..2c119dfa08e 100644 --- a/internal/service/imagebuilder/container_recipe.go +++ b/internal/service/imagebuilder/container_recipe.go @@ -13,6 +13,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -21,21 +22,24 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/sdkv2/types/nullable" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_container_recipe", name="Container Recipe") // @Tags(identifierAttribute="id") -func ResourceContainerRecipe() *schema.Resource { +func resourceContainerRecipe() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceContainerRecipeCreate, ReadWithoutTimeout: resourceContainerRecipeRead, UpdateWithoutTimeout: resourceContainerRecipeUpdate, DeleteWithoutTimeout: resourceContainerRecipeDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, + Schema: map[string]*schema.Schema{ names.AttrARN: { Type: schema.TypeString, @@ -282,6 +286,7 @@ func ResourceContainerRecipe() *schema.Resource { ValidateFunc: validation.StringLenBetween(1, 1024), }, }, + CustomizeDiff: verify.SetTagsDiff, } } @@ -353,10 +358,6 @@ func resourceContainerRecipeCreate(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "creating Image Builder Container Recipe: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Container Recipe: empty response") - } - d.SetId(aws.ToString(output.ContainerRecipeArn)) return append(diags, resourceContainerRecipeRead(ctx, d, meta)...) @@ -366,54 +367,47 @@ func resourceContainerRecipeRead(ctx context.Context, d *schema.ResourceData, me var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetContainerRecipeInput{ - ContainerRecipeArn: aws.String(d.Id()), - } - - output, err := conn.GetContainerRecipe(ctx, input) + containerRecipe, err := findContainerRecipeByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Container Recipe (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Container Recipe (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): %s", d.Id(), err) } - if output == nil || output.ContainerRecipe == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Container Recipe (%s): empty response", d.Id()) - } - - containerRecipe := output.ContainerRecipe - d.Set(names.AttrARN, containerRecipe.Arn) - d.Set("component", flattenComponentConfigurations(containerRecipe.Components)) + if err := d.Set("component", flattenComponentConfigurations(containerRecipe.Components)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting component: %s", err) + } d.Set("container_type", containerRecipe.ContainerType) d.Set("date_created", containerRecipe.DateCreated) d.Set(names.AttrDescription, containerRecipe.Description) d.Set("dockerfile_template_data", containerRecipe.DockerfileTemplateData) d.Set(names.AttrEncrypted, containerRecipe.Encrypted) - if containerRecipe.InstanceConfiguration != nil { - d.Set("instance_configuration", []interface{}{flattenInstanceConfiguration(containerRecipe.InstanceConfiguration)}) + if err := d.Set("instance_configuration", []interface{}{flattenInstanceConfiguration(containerRecipe.InstanceConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting instance_configuration: %s", err) + } } else { d.Set("instance_configuration", nil) } - d.Set(names.AttrKMSKeyID, containerRecipe.KmsKeyId) d.Set(names.AttrName, containerRecipe.Name) d.Set(names.AttrOwner, containerRecipe.Owner) d.Set("parent_image", containerRecipe.ParentImage) d.Set("platform", containerRecipe.Platform) - - setTagsOut(ctx, containerRecipe.Tags) - - d.Set("target_repository", []interface{}{flattenTargetContainerRepository(containerRecipe.TargetRepository)}) + if err := d.Set("target_repository", []interface{}{flattenTargetContainerRepository(containerRecipe.TargetRepository)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting target_repository: %s", err) + } d.Set(names.AttrVersion, containerRecipe.Version) d.Set("working_directory", containerRecipe.WorkingDirectory) + setTagsOut(ctx, containerRecipe.Tags) + return diags } @@ -433,9 +427,10 @@ func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, ContainerRecipeArn: aws.String(d.Id()), } + log.Printf("[DEBUG] Deleting Image Builder Container Recipe: %s", d.Id()) _, err := conn.DeleteContainerRecipe(ctx, input) - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -446,6 +441,31 @@ func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, return diags } +func findContainerRecipeByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.ContainerRecipe, error) { + input := &imagebuilder.GetContainerRecipeInput{ + ContainerRecipeArn: aws.String(arn), + } + + output, err := conn.GetContainerRecipe(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.ContainerRecipe == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.ContainerRecipe, nil +} + func expandInstanceConfiguration(tfMap map[string]interface{}) *awstypes.InstanceConfiguration { if tfMap == nil { return nil diff --git a/internal/service/imagebuilder/container_recipe_test.go b/internal/service/imagebuilder/container_recipe_test.go index 68b96e03c56..420d859ca82 100644 --- a/internal/service/imagebuilder/container_recipe_test.go +++ b/internal/service/imagebuilder/container_recipe_test.go @@ -9,16 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -704,49 +702,35 @@ func testAccCheckContainerRecipeDestroy(ctx context.Context) resource.TestCheckF continue } - input := &imagebuilder.GetContainerRecipeInput{ - ContainerRecipeArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetContainerRecipe(ctx, input) + _, err := tfimagebuilder.FindContainerRecipeByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Container Recipe (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Container Recipe (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Container Recipe %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckContainerRecipeExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckContainerRecipeExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetContainerRecipeInput{ - ContainerRecipeArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetContainerRecipe(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Container Recipe (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindContainerRecipeByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index bc1f150af65..9fa31ef9ab7 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -6,8 +6,10 @@ package imagebuilder // Exports for use in tests only. var ( ResourceComponent = resourceComponent + ResourceContainerRecipe = resourceContainerRecipe ResourceLifecyclePolicy = newResourceLifecyclePolicy FindComponentByARN = findComponentByARN + FindContainerRecipeByARN = findContainerRecipeByARN FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 1917b9e45a6..f5a34c4998b 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -103,7 +103,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceContainerRecipe, + Factory: resourceContainerRecipe, TypeName: "aws_imagebuilder_container_recipe", Name: "Container Recipe", Tags: &types.ServicePackageResourceTags{ From 504af6a4c229e466d4a672f3d27b6bffc2c7094e Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:29:04 -0400 Subject: [PATCH 071/112] d/aws_imagebuilder_container_recipe: Reduce visibility. --- .../container_recipe_data_source.go | 45 +++++++++---------- .../imagebuilder/service_package_gen.go | 4 +- 2 files changed, 23 insertions(+), 26 deletions(-) diff --git a/internal/service/imagebuilder/container_recipe_data_source.go b/internal/service/imagebuilder/container_recipe_data_source.go index 3523693559b..7ceca78c876 100644 --- a/internal/service/imagebuilder/container_recipe_data_source.go +++ b/internal/service/imagebuilder/container_recipe_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -17,10 +16,12 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_container_recipe") -func DataSourceContainerRecipe() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_container_recipe", name="Container Recipe") +// @Tags +func dataSourceContainerRecipe() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceContainerRecipeRead, + Schema: map[string]*schema.Schema{ names.AttrARN: { Type: schema.TypeString, @@ -199,50 +200,44 @@ func DataSourceContainerRecipe() *schema.Resource { func dataSourceContainerRecipeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - - input := &imagebuilder.GetContainerRecipeInput{} - if v, ok := d.GetOk(names.AttrARN); ok { - input.ContainerRecipeArn = aws.String(v.(string)) - } - - output, err := conn.GetContainerRecipe(ctx, input) + arn := d.Get(names.AttrARN).(string) + containerRecipe, err := findContainerRecipeByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): %s", aws.ToString(input.ContainerRecipeArn), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): %s", arn, err) } - if output == nil || output.ContainerRecipe == nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipe (%s): empty response", aws.ToString(input.ContainerRecipeArn)) + arn = aws.ToString(containerRecipe.Arn) + d.SetId(arn) + d.Set(names.AttrARN, arn) + if err := d.Set("component", flattenComponentConfigurations(containerRecipe.Components)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting component: %s", err) } - - containerRecipe := output.ContainerRecipe - - d.SetId(aws.ToString(containerRecipe.Arn)) - d.Set(names.AttrARN, containerRecipe.Arn) - d.Set("component", flattenComponentConfigurations(containerRecipe.Components)) d.Set("container_type", containerRecipe.ContainerType) d.Set("date_created", containerRecipe.DateCreated) d.Set(names.AttrDescription, containerRecipe.Description) d.Set("dockerfile_template_data", containerRecipe.DockerfileTemplateData) d.Set(names.AttrEncrypted, containerRecipe.Encrypted) - if containerRecipe.InstanceConfiguration != nil { - d.Set("instance_configuration", []interface{}{flattenInstanceConfiguration(containerRecipe.InstanceConfiguration)}) + if err := d.Set("instance_configuration", []interface{}{flattenInstanceConfiguration(containerRecipe.InstanceConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting instance_configuration: %s", err) + } } else { d.Set("instance_configuration", nil) } - d.Set(names.AttrKMSKeyID, containerRecipe.KmsKeyId) d.Set(names.AttrName, containerRecipe.Name) d.Set(names.AttrOwner, containerRecipe.Owner) d.Set("parent_image", containerRecipe.ParentImage) d.Set("platform", containerRecipe.Platform) - d.Set(names.AttrTags, KeyValueTags(ctx, containerRecipe.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) - d.Set("target_repository", []interface{}{flattenTargetContainerRepository(containerRecipe.TargetRepository)}) + if err := d.Set("target_repository", []interface{}{flattenTargetContainerRepository(containerRecipe.TargetRepository)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting target_repository: %s", err) + } d.Set(names.AttrVersion, containerRecipe.Version) d.Set("working_directory", containerRecipe.WorkingDirectory) + setTagsOut(ctx, containerRecipe.Tags) + return diags } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index f5a34c4998b..785ffe6a5d1 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -44,8 +44,10 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Components", }, { - Factory: DataSourceContainerRecipe, + Factory: dataSourceContainerRecipe, TypeName: "aws_imagebuilder_container_recipe", + Name: "Container Recipe", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceContainerRecipes, From fa841ad4ca0b3fe8985f2c27114de6812c87a07c Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:39:35 -0400 Subject: [PATCH 072/112] d/aws_imagebuilder_container_recipes: Reduce visibility. --- .../container_recipes_data_source.go | 46 +++++++++++++------ .../imagebuilder/service_package_gen.go | 2 +- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/internal/service/imagebuilder/container_recipes_data_source.go b/internal/service/imagebuilder/container_recipes_data_source.go index 1483753741b..222958e55c7 100644 --- a/internal/service/imagebuilder/container_recipes_data_source.go +++ b/internal/service/imagebuilder/container_recipes_data_source.go @@ -16,13 +16,15 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" namevaluesfiltersv2 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v2" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKDataSource("aws_imagebuilder_container_recipes", name="Container Recipes") -func DataSourceContainerRecipes() *schema.Resource { +func dataSourceContainerRecipes() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceContainerRecipesRead, + Schema: map[string]*schema.Schema{ names.AttrARNs: { Type: schema.TypeSet, @@ -50,30 +52,44 @@ func dataSourceContainerRecipesRead(ctx context.Context, d *schema.ResourceData, input := &imagebuilder.ListContainerRecipesInput{} - if v, ok := d.GetOk(names.AttrOwner); ok { - input.Owner = awstypes.Ownership(v.(string)) - } - if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } - out, err := conn.ListContainerRecipes(ctx, input) - - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipes: %s", err) + if v, ok := d.GetOk(names.AttrOwner); ok { + input.Owner = awstypes.Ownership(v.(string)) } - var arns, nms []string + containerRecipes, err := findContainerRecipes(ctx, conn, input) - for _, r := range out.ContainerRecipeSummaryList { - arns = append(arns, aws.ToString(r.Arn)) - nms = append(nms, aws.ToString(r.Name)) + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Image Builder Container Recipes: %s", err) } d.SetId(meta.(*conns.AWSClient).Region) - d.Set(names.AttrARNs, arns) - d.Set(names.AttrNames, nms) + d.Set(names.AttrARNs, tfslices.ApplyToAll(containerRecipes, func(v awstypes.ContainerRecipeSummary) string { + return aws.ToString(v.Arn) + })) + d.Set(names.AttrNames, tfslices.ApplyToAll(containerRecipes, func(v awstypes.ContainerRecipeSummary) string { + return aws.ToString(v.Name) + })) return diags } + +func findContainerRecipes(ctx context.Context, conn *imagebuilder.Client, input *imagebuilder.ListContainerRecipesInput) ([]awstypes.ContainerRecipeSummary, error) { + var output []awstypes.ContainerRecipeSummary + + pages := imagebuilder.NewListContainerRecipesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.ContainerRecipeSummaryList...) + } + + return output, nil +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 785ffe6a5d1..48b89674819 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -50,7 +50,7 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceContainerRecipes, + Factory: dataSourceContainerRecipes, TypeName: "aws_imagebuilder_container_recipes", Name: "Container Recipes", }, From be6671668dd9c9d8b89e1d82265a7eae0afec5c9 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:48:18 -0400 Subject: [PATCH 073/112] r/aws_imagebuilder_distribution_configuration: Reduce visibility. --- .../service/imagebuilder/container_recipe.go | 8 +-- .../distribution_configuration.go | 64 +++++++++++-------- .../distribution_configuration_test.go | 36 +++-------- internal/service/imagebuilder/export_tests.go | 14 ++-- .../imagebuilder/service_package_gen.go | 2 +- 5 files changed, 61 insertions(+), 63 deletions(-) diff --git a/internal/service/imagebuilder/container_recipe.go b/internal/service/imagebuilder/container_recipe.go index 2c119dfa08e..3bbcc7b522d 100644 --- a/internal/service/imagebuilder/container_recipe.go +++ b/internal/service/imagebuilder/container_recipe.go @@ -423,12 +423,10 @@ func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteContainerRecipeInput{ - ContainerRecipeArn: aws.String(d.Id()), - } - log.Printf("[DEBUG] Deleting Image Builder Container Recipe: %s", d.Id()) - _, err := conn.DeleteContainerRecipe(ctx, input) + _, err := conn.DeleteContainerRecipe(ctx, &imagebuilder.DeleteContainerRecipeInput{ + ContainerRecipeArn: aws.String(d.Id()), + }) if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 85402084328..79bb816bcce 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -13,6 +13,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -20,18 +21,20 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_distribution_configuration", name="Distribution Configuration") // @Tags(identifierAttribute="id") -func ResourceDistributionConfiguration() *schema.Resource { +func resourceDistributionConfiguration() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceDistributionConfigurationCreate, ReadWithoutTimeout: resourceDistributionConfigurationRead, UpdateWithoutTimeout: resourceDistributionConfigurationUpdate, DeleteWithoutTimeout: resourceDistributionConfigurationDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -320,10 +323,6 @@ func resourceDistributionConfigurationCreate(ctx context.Context, d *schema.Reso return sdkdiag.AppendErrorf(diags, "creating Image Builder Distribution Configuration: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Distribution Configuration: empty response") - } - d.SetId(aws.ToString(output.DistributionConfigurationArn)) return append(diags, resourceDistributionConfigurationRead(ctx, d, meta)...) @@ -333,33 +332,25 @@ func resourceDistributionConfigurationRead(ctx context.Context, d *schema.Resour var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetDistributionConfigurationInput{ - DistributionConfigurationArn: aws.String(d.Id()), - } - - output, err := conn.GetDistributionConfiguration(ctx, input) + distributionConfiguration, err := findDistributionConfigurationByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Distribution Configuration (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Distribution Configuration (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Distribution Configuration (%s): %s", d.Id(), err) } - if output == nil || output.DistributionConfiguration == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Distribution Configuration (%s): empty response", d.Id()) - } - - distributionConfiguration := output.DistributionConfiguration - d.Set(names.AttrARN, distributionConfiguration.Arn) d.Set("date_created", distributionConfiguration.DateCreated) d.Set("date_updated", distributionConfiguration.DateUpdated) d.Set(names.AttrDescription, distributionConfiguration.Description) - d.Set("distribution", flattenDistributions(distributionConfiguration.Distributions)) + if err := d.Set("distribution", flattenDistributions(distributionConfiguration.Distributions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting distribution: %s", err) + } d.Set(names.AttrName, distributionConfiguration.Name) setTagsOut(ctx, distributionConfiguration.Tags) @@ -384,7 +375,6 @@ func resourceDistributionConfigurationUpdate(ctx context.Context, d *schema.Reso input.Distributions = expandDistributions(v.(*schema.Set).List()) } - log.Printf("[DEBUG] UpdateDistributionConfiguration: %#v", input) _, err := conn.UpdateDistributionConfiguration(ctx, input) if err != nil { @@ -399,13 +389,12 @@ func resourceDistributionConfigurationDelete(ctx context.Context, d *schema.Reso var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteDistributionConfigurationInput{ + log.Printf("[DEBUG] Deleting Image Builder Distribution Configuration: %s", d.Id()) + _, err := conn.DeleteDistributionConfiguration(ctx, &imagebuilder.DeleteDistributionConfigurationInput{ DistributionConfigurationArn: aws.String(d.Id()), - } + }) - _, err := conn.DeleteDistributionConfiguration(ctx, input) - - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -416,6 +405,31 @@ func resourceDistributionConfigurationDelete(ctx context.Context, d *schema.Reso return diags } +func findDistributionConfigurationByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.DistributionConfiguration, error) { + input := &imagebuilder.GetDistributionConfigurationInput{ + DistributionConfigurationArn: aws.String(arn), + } + + output, err := conn.GetDistributionConfiguration(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.DistributionConfiguration == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.DistributionConfiguration, nil +} + func expandAMIDistributionConfiguration(tfMap map[string]interface{}) *awstypes.AmiDistributionConfiguration { if tfMap == nil { return nil diff --git a/internal/service/imagebuilder/distribution_configuration_test.go b/internal/service/imagebuilder/distribution_configuration_test.go index 4cf0936aacc..a512b061b4b 100644 --- a/internal/service/imagebuilder/distribution_configuration_test.go +++ b/internal/service/imagebuilder/distribution_configuration_test.go @@ -8,15 +8,13 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -933,49 +931,35 @@ func testAccCheckDistributionConfigurationDestroy(ctx context.Context) resource. continue } - input := &imagebuilder.GetDistributionConfigurationInput{ - DistributionConfigurationArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetDistributionConfiguration(ctx, input) + _, err := tfimagebuilder.FindDistributionConfigurationByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Distribution Configuration (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Distribution Configuration (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Distribution Configuration %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckDistributionConfigurationExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckDistributionConfigurationExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetDistributionConfigurationInput{ - DistributionConfigurationArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetDistributionConfiguration(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Distribution Configuration (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindDistributionConfigurationByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 9fa31ef9ab7..75caad54668 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -5,11 +5,13 @@ package imagebuilder // Exports for use in tests only. var ( - ResourceComponent = resourceComponent - ResourceContainerRecipe = resourceContainerRecipe - ResourceLifecyclePolicy = newResourceLifecyclePolicy + ResourceComponent = resourceComponent + ResourceContainerRecipe = resourceContainerRecipe + ResourceDistributionConfiguration = resourceDistributionConfiguration + ResourceLifecyclePolicy = newResourceLifecyclePolicy - FindComponentByARN = findComponentByARN - FindContainerRecipeByARN = findContainerRecipeByARN - FindLifecyclePolicyByARN = findLifecyclePolicyByARN + FindComponentByARN = findComponentByARN + FindContainerRecipeByARN = findContainerRecipeByARN + FindDistributionConfigurationByARN = findDistributionConfigurationByARN + FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 48b89674819..2a78477d2f9 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -113,7 +113,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceDistributionConfiguration, + Factory: resourceDistributionConfiguration, TypeName: "aws_imagebuilder_distribution_configuration", Name: "Distribution Configuration", Tags: &types.ServicePackageResourceTags{ From 2cf51b1b9f0e6c10e09a867a5637f6e0703851be Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:51:21 -0400 Subject: [PATCH 074/112] d/aws_imagebuilder_distribution_configuration: Reduce visibility. --- .../distribution_configuration_data_source.go | 34 +++++++------------ .../imagebuilder/service_package_gen.go | 3 +- 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/internal/service/imagebuilder/distribution_configuration_data_source.go b/internal/service/imagebuilder/distribution_configuration_data_source.go index add03999ca0..fe871f28607 100644 --- a/internal/service/imagebuilder/distribution_configuration_data_source.go +++ b/internal/service/imagebuilder/distribution_configuration_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -18,7 +17,8 @@ import ( ) // @SDKDataSource("aws_imagebuilder_distribution_configuration") -func DataSourceDistributionConfiguration() *schema.Resource { +// @Tags +func dataSourceDistributionConfiguration() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceDistributionConfigurationRead, @@ -242,34 +242,26 @@ func DataSourceDistributionConfiguration() *schema.Resource { func dataSourceDistributionConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - input := &imagebuilder.GetDistributionConfigurationInput{} - - if v, ok := d.GetOk(names.AttrARN); ok { - input.DistributionConfigurationArn = aws.String(v.(string)) - } - - output, err := conn.GetDistributionConfiguration(ctx, input) + arn := d.Get(names.AttrARN).(string) + distributionConfiguration, err := findDistributionConfigurationByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Distribution Configuration (%s): %s", d.Id(), err) - } - - if output == nil || output.DistributionConfiguration == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Distribution Configuration (%s): empty response", d.Id()) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Distribution Configuration (%s): %s", arn, err) } - distributionConfiguration := output.DistributionConfiguration - - d.SetId(aws.ToString(distributionConfiguration.Arn)) - d.Set(names.AttrARN, distributionConfiguration.Arn) + arn = aws.ToString(distributionConfiguration.Arn) + d.SetId(arn) + d.Set(names.AttrARN, arn) d.Set("date_created", distributionConfiguration.DateCreated) d.Set("date_updated", distributionConfiguration.DateUpdated) d.Set(names.AttrDescription, distributionConfiguration.Description) - d.Set("distribution", flattenDistributions(distributionConfiguration.Distributions)) + if err := d.Set("distribution", flattenDistributions(distributionConfiguration.Distributions)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting distribution: %s", err) + } d.Set(names.AttrName, distributionConfiguration.Name) - d.Set(names.AttrTags, KeyValueTags(ctx, distributionConfiguration.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) + + setTagsOut(ctx, distributionConfiguration.Tags) return diags } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 2a78477d2f9..20297184298 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -55,8 +55,9 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Container Recipes", }, { - Factory: DataSourceDistributionConfiguration, + Factory: dataSourceDistributionConfiguration, TypeName: "aws_imagebuilder_distribution_configuration", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceDistributionConfigurations, From 34404111f040b230b39f29837e6fbb84e0bab630 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 11:57:10 -0400 Subject: [PATCH 075/112] d/aws_imagebuilder_distribution_configurations: Reduce visibility. --- .../container_recipe_data_source.go | 2 +- .../distribution_configuration_data_source.go | 2 +- ...distribution_configurations_data_source.go | 41 +++++++++++++------ .../imagebuilder/service_package_gen.go | 4 +- 4 files changed, 34 insertions(+), 15 deletions(-) diff --git a/internal/service/imagebuilder/container_recipe_data_source.go b/internal/service/imagebuilder/container_recipe_data_source.go index 7ceca78c876..e92c1756b2a 100644 --- a/internal/service/imagebuilder/container_recipe_data_source.go +++ b/internal/service/imagebuilder/container_recipe_data_source.go @@ -168,7 +168,7 @@ func dataSourceContainerRecipe() *schema.Resource { Type: schema.TypeString, Computed: true, }, - names.AttrTags: tftags.TagsSchema(), + names.AttrTags: tftags.TagsSchemaComputed(), "target_repository": { Type: schema.TypeList, Computed: true, diff --git a/internal/service/imagebuilder/distribution_configuration_data_source.go b/internal/service/imagebuilder/distribution_configuration_data_source.go index fe871f28607..f560352bcc5 100644 --- a/internal/service/imagebuilder/distribution_configuration_data_source.go +++ b/internal/service/imagebuilder/distribution_configuration_data_source.go @@ -16,7 +16,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_distribution_configuration") +// @SDKDataSource("aws_imagebuilder_distribution_configuration", name="Distribution Configuration") // @Tags func dataSourceDistributionConfiguration() *schema.Resource { return &schema.Resource{ diff --git a/internal/service/imagebuilder/distribution_configurations_data_source.go b/internal/service/imagebuilder/distribution_configurations_data_source.go index 2a6eb9b4345..5eb8ef15a4f 100644 --- a/internal/service/imagebuilder/distribution_configurations_data_source.go +++ b/internal/service/imagebuilder/distribution_configurations_data_source.go @@ -8,19 +8,22 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" namevaluesfiltersv2 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v2" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_distribution_configurations") -func DataSourceDistributionConfigurations() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_distribution_configurations", name="Distribution Configurations") +func dataSourceDistributionConfigurations() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceDistributionConfigurationsRead, + Schema: map[string]*schema.Schema{ names.AttrARNs: { Type: schema.TypeSet, @@ -47,22 +50,36 @@ func dataSourceDistributionConfigurationsRead(ctx context.Context, d *schema.Res input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } - out, err := conn.ListDistributionConfigurations(ctx, input) + distributionConfigurations, err := findDistributionConfigurations(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Distribution Configurations: %s", err) } - var arns, nms []string - - for _, r := range out.DistributionConfigurationSummaryList { - arns = append(arns, aws.ToString(r.Arn)) - nms = append(nms, aws.ToString(r.Name)) - } - d.SetId(meta.(*conns.AWSClient).Region) - d.Set(names.AttrARNs, arns) - d.Set(names.AttrNames, nms) + d.Set(names.AttrARNs, tfslices.ApplyToAll(distributionConfigurations, func(v awstypes.DistributionConfigurationSummary) string { + return aws.ToString(v.Arn) + })) + d.Set(names.AttrNames, tfslices.ApplyToAll(distributionConfigurations, func(v awstypes.DistributionConfigurationSummary) string { + return aws.ToString(v.Name) + })) return diags } + +func findDistributionConfigurations(ctx context.Context, conn *imagebuilder.Client, input *imagebuilder.ListDistributionConfigurationsInput) ([]awstypes.DistributionConfigurationSummary, error) { + var output []awstypes.DistributionConfigurationSummary + + pages := imagebuilder.NewListDistributionConfigurationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.DistributionConfigurationSummaryList...) + } + + return output, nil +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 20297184298..0d905831520 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -57,11 +57,13 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac { Factory: dataSourceDistributionConfiguration, TypeName: "aws_imagebuilder_distribution_configuration", + Name: "Distribution Configuration", Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceDistributionConfigurations, + Factory: dataSourceDistributionConfigurations, TypeName: "aws_imagebuilder_distribution_configurations", + Name: "Distribution Configurations", }, { Factory: DataSourceImage, From e1917f9963e2fab304fdb6a63a6cca54dc4d7d77 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 12:15:54 -0400 Subject: [PATCH 076/112] r/aws_imagebuilder_image: Reduce visibility. --- internal/service/imagebuilder/export_tests.go | 2 + internal/service/imagebuilder/image.go | 76 ++++++++++++------- internal/service/imagebuilder/image_test.go | 36 +++------ .../imagebuilder/service_package_gen.go | 2 +- 4 files changed, 61 insertions(+), 55 deletions(-) diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 75caad54668..69a630f00dd 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -8,10 +8,12 @@ var ( ResourceComponent = resourceComponent ResourceContainerRecipe = resourceContainerRecipe ResourceDistributionConfiguration = resourceDistributionConfiguration + ResourceImage = resourceImage ResourceLifecyclePolicy = newResourceLifecyclePolicy FindComponentByARN = findComponentByARN FindContainerRecipeByARN = findContainerRecipeByARN FindDistributionConfigurationByARN = findDistributionConfigurationByARN + FindImageByARN = findImageByARN FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index e98ec8f76b4..4da9dd7de16 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -14,6 +14,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -21,13 +22,14 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_image", name="Image") // @Tags(identifierAttribute="id") -func ResourceImage() *schema.Resource { +func resourceImage() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceImageCreate, ReadWithoutTimeout: resourceImageRead, @@ -322,14 +324,10 @@ func resourceImageCreate(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "creating Image Builder Image: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Image: empty response") - } - d.SetId(aws.ToString(output.ImageBuildVersionArn)) if _, err := waitImageStatusAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for Image Builder Image (%s) to become available: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for Image Builder Image (%s) create: %s", d.Id(), err) } return append(diags, resourceImageRead(ctx, d, meta)...) @@ -339,28 +337,18 @@ func resourceImageRead(ctx context.Context, d *schema.ResourceData, meta interfa var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImageInput{ - ImageBuildVersionArn: aws.String(d.Id()), - } - - output, err := conn.GetImage(ctx, input) + image, err := findImageByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Image (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image (%s): %s", d.Id(), err) } - if output == nil || output.Image == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image (%s): empty response", d.Id()) - } - - image := output.Image - d.Set(names.AttrARN, image.Arn) if image.ContainerRecipe != nil { d.Set("container_recipe_arn", image.ContainerRecipe.Arn) @@ -375,12 +363,16 @@ func resourceImageRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("image_recipe_arn", image.ImageRecipe.Arn) } if image.ImageScanningConfiguration != nil { - d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(image.ImageScanningConfiguration)}) + if err := d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(image.ImageScanningConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image_scanning_configuration: %s", err) + } } else { d.Set("image_scanning_configuration", nil) } if image.ImageTestsConfiguration != nil { - d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(image.ImageTestsConfiguration)}) + if err := d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(image.ImageTestsConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image_tests_configuration: %s", err) + } } else { d.Set("image_tests_configuration", nil) } @@ -390,14 +382,18 @@ func resourceImageRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set(names.AttrName, image.Name) d.Set("os_version", image.OsVersion) if image.OutputResources != nil { - d.Set("output_resources", []interface{}{flattenOutputResources(image.OutputResources)}) + if err := d.Set("output_resources", []interface{}{flattenOutputResources(image.OutputResources)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting output_resources: %s", err) + } } else { d.Set("output_resources", nil) } d.Set("platform", image.Platform) d.Set(names.AttrVersion, image.Version) if image.Workflows != nil { - d.Set("workflow", flattenWorkflowConfigurations(image.Workflows)) + if err := d.Set("workflow", flattenWorkflowConfigurations(image.Workflows)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting workflow: %s", err) + } } else { d.Set("workflow", nil) } @@ -419,13 +415,12 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, meta inter var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteImageInput{ + log.Printf("[DEBUG] Deleting Image Builder Image: %s", d.Id()) + _, err := conn.DeleteImage(ctx, &imagebuilder.DeleteImageInput{ ImageBuildVersionArn: aws.String(d.Id()), - } - - _, err := conn.DeleteImage(ctx, input) + }) - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -436,6 +431,31 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, meta inter return diags } +func findImageByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.Image, error) { + input := &imagebuilder.GetImageInput{ + ImageBuildVersionArn: aws.String(arn), + } + + output, err := conn.GetImage(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.Image == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Image, nil +} + func flattenOutputResources(apiObject *awstypes.OutputResources) map[string]interface{} { if apiObject == nil { return nil diff --git a/internal/service/imagebuilder/image_test.go b/internal/service/imagebuilder/image_test.go index a16d3b163c2..193599ec745 100644 --- a/internal/service/imagebuilder/image_test.go +++ b/internal/service/imagebuilder/image_test.go @@ -9,16 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -358,49 +356,35 @@ func testAccCheckImageDestroy(ctx context.Context) resource.TestCheckFunc { continue } - input := &imagebuilder.GetImageInput{ - ImageBuildVersionArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetImage(ctx, input) + _, err := tfimagebuilder.FindImageByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Image (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Image (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Image %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckImageExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckImageExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImageInput{ - ImageBuildVersionArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetImage(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Image (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindImageByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 0d905831520..29c01e60cac 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -124,7 +124,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceImage, + Factory: resourceImage, TypeName: "aws_imagebuilder_image", Name: "Image", Tags: &types.ServicePackageResourceTags{ From 9496e5f04ab3b2346d9830453c7bd53cc174eb0b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 12:21:01 -0400 Subject: [PATCH 077/112] d/aws_imagebuilder_image: Reduce visibility. --- .../service/imagebuilder/image_data_source.go | 52 +++++++------------ .../imagebuilder/service_package_gen.go | 4 +- 2 files changed, 21 insertions(+), 35 deletions(-) diff --git a/internal/service/imagebuilder/image_data_source.go b/internal/service/imagebuilder/image_data_source.go index 6c23be6b4dc..258755f5bf7 100644 --- a/internal/service/imagebuilder/image_data_source.go +++ b/internal/service/imagebuilder/image_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -17,8 +16,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_image") -func DataSourceImage() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_image", name="Image") +// @Tags +func dataSourceImage() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceImageRead, @@ -181,78 +181,62 @@ func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, meta inter var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImageInput{} - - if v, ok := d.GetOk(names.AttrARN); ok { - input.ImageBuildVersionArn = aws.String(v.(string)) - } - - output, err := conn.GetImage(ctx, input) + arn := d.Get(names.AttrARN).(string) + image, err := findImageByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image: %s", err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image: %s", err) } - if output == nil || output.Image == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image: empty response") - } - - image := output.Image - d.SetId(aws.ToString(image.Arn)) - // To prevent Terraform errors, only reset arn if not configured. // The configured ARN may contain x.x.x wildcards while the API returns // the full build version #.#.#/# suffix. if _, ok := d.GetOk(names.AttrARN); !ok { d.Set(names.AttrARN, image.Arn) } - d.Set("build_version_arn", image.Arn) - d.Set("date_created", image.DateCreated) - if image.ContainerRecipe != nil { d.Set("container_recipe_arn", image.ContainerRecipe.Arn) } - + d.Set("date_created", image.DateCreated) if image.DistributionConfiguration != nil { d.Set("distribution_configuration_arn", image.DistributionConfiguration.Arn) } - d.Set("enhanced_image_metadata_enabled", image.EnhancedImageMetadataEnabled) - if image.ImageRecipe != nil { d.Set("image_recipe_arn", image.ImageRecipe.Arn) } - if image.ImageScanningConfiguration != nil { - d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(image.ImageScanningConfiguration)}) + if err := d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(image.ImageScanningConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image_scanning_configuration: %s", err) + } } else { d.Set("image_scanning_configuration", nil) } - if image.ImageTestsConfiguration != nil { - d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(image.ImageTestsConfiguration)}) + if err := d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(image.ImageTestsConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image_tests_configuration: %s", err) + } } else { d.Set("image_tests_configuration", nil) } - if image.InfrastructureConfiguration != nil { d.Set("infrastructure_configuration_arn", image.InfrastructureConfiguration.Arn) } - d.Set(names.AttrName, image.Name) d.Set("platform", image.Platform) d.Set("os_version", image.OsVersion) - if image.OutputResources != nil { - d.Set("output_resources", []interface{}{flattenOutputResources(image.OutputResources)}) + if err := d.Set("output_resources", []interface{}{flattenOutputResources(image.OutputResources)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting output_resources: %s", err) + } } else { d.Set("output_resources", nil) } - - d.Set(names.AttrTags, KeyValueTags(ctx, image.Tags).IgnoreAWS().IgnoreConfig(meta.(*conns.AWSClient).IgnoreTagsConfig).Map()) d.Set(names.AttrVersion, image.Version) + setTagsOut(ctx, image.Tags) + return diags } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 29c01e60cac..94648dcb247 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -66,8 +66,10 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Distribution Configurations", }, { - Factory: DataSourceImage, + Factory: dataSourceImage, TypeName: "aws_imagebuilder_image", + Name: "Image", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceImagePipeline, From a75e6aea2b71767ef1899fb1547baa2be6f28728 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 12:35:27 -0400 Subject: [PATCH 078/112] r/aws_imagebuilder_image_pipeline: Reduce visibility. --- internal/service/imagebuilder/export_tests.go | 2 + .../service/imagebuilder/image_pipeline.go | 75 ++++++++++++------- .../imagebuilder/image_pipeline_test.go | 36 +++------ .../imagebuilder/service_package_gen.go | 2 +- 4 files changed, 61 insertions(+), 54 deletions(-) diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 69a630f00dd..63d1f245ed0 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -9,11 +9,13 @@ var ( ResourceContainerRecipe = resourceContainerRecipe ResourceDistributionConfiguration = resourceDistributionConfiguration ResourceImage = resourceImage + ResourceImagePipeline = resourceImagePipeline ResourceLifecyclePolicy = newResourceLifecyclePolicy FindComponentByARN = findComponentByARN FindContainerRecipeByARN = findContainerRecipeByARN FindDistributionConfigurationByARN = findDistributionConfigurationByARN FindImageByARN = findImageByARN + FindImagePipelineByARN = findImagePipelineByARN FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/image_pipeline.go b/internal/service/imagebuilder/image_pipeline.go index 7f7b8bee36a..c311ce08253 100644 --- a/internal/service/imagebuilder/image_pipeline.go +++ b/internal/service/imagebuilder/image_pipeline.go @@ -13,6 +13,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -21,18 +22,20 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_image_pipeline", name="Image Pipeline") // @Tags(identifierAttribute="id") -func ResourceImagePipeline() *schema.Resource { +func resourceImagePipeline() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceImagePipelineCreate, ReadWithoutTimeout: resourceImagePipelineRead, UpdateWithoutTimeout: resourceImagePipelineUpdate, DeleteWithoutTimeout: resourceImagePipelineDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -311,10 +314,6 @@ func resourceImagePipelineCreate(ctx context.Context, d *schema.ResourceData, me return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Pipeline: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Pipeline: empty response") - } - d.SetId(aws.ToString(output.ImagePipelineArn)) return append(diags, resourceImagePipelineRead(ctx, d, meta)...) @@ -324,28 +323,18 @@ func resourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImagePipelineInput{ - ImagePipelineArn: aws.String(d.Id()), - } - - output, err := conn.GetImagePipeline(ctx, input) + imagePipeline, err := findImagePipelineByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Image Pipeline (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Pipeline (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Pipeline (%s): %s", d.Id(), err) } - if output == nil || output.ImagePipeline == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Pipeline (%s): empty response", d.Id()) - } - - imagePipeline := output.ImagePipeline - d.Set(names.AttrARN, imagePipeline.Arn) d.Set("container_recipe_arn", imagePipeline.ContainerRecipeArn) d.Set("date_created", imagePipeline.DateCreated) @@ -358,12 +347,16 @@ func resourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta d.Set("execution_role", imagePipeline.ExecutionRole) d.Set("image_recipe_arn", imagePipeline.ImageRecipeArn) if imagePipeline.ImageScanningConfiguration != nil { - d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(imagePipeline.ImageScanningConfiguration)}) + if err := d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(imagePipeline.ImageScanningConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image scanning configuration: %s", err) + } } else { d.Set("image_scanning_configuration", nil) } if imagePipeline.ImageTestsConfiguration != nil { - d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(imagePipeline.ImageTestsConfiguration)}) + if err := d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(imagePipeline.ImageTestsConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image tests configuration: %s", err) + } } else { d.Set("image_tests_configuration", nil) } @@ -371,12 +364,16 @@ func resourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, meta d.Set(names.AttrName, imagePipeline.Name) d.Set("platform", imagePipeline.Platform) if imagePipeline.Schedule != nil { - d.Set(names.AttrSchedule, []interface{}{flattenSchedule(imagePipeline.Schedule)}) + if err := d.Set(names.AttrSchedule, []interface{}{flattenSchedule(imagePipeline.Schedule)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting schedule: %s", err) + } } else { d.Set(names.AttrSchedule, nil) } d.Set(names.AttrStatus, imagePipeline.Status) - d.Set("workflow", flattenWorkflowConfigurations(imagePipeline.Workflows)) + if err := d.Set("workflow", flattenWorkflowConfigurations(imagePipeline.Workflows)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting workflow: %s", err) + } setTagsOut(ctx, imagePipeline.Tags) @@ -463,13 +460,12 @@ func resourceImagePipelineDelete(ctx context.Context, d *schema.ResourceData, me var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteImagePipelineInput{ + log.Printf("[DEBUG] Deleting Image Builder Image Pipeline: %s", d.Id()) + _, err := conn.DeleteImagePipeline(ctx, &imagebuilder.DeleteImagePipelineInput{ ImagePipelineArn: aws.String(d.Id()), - } + }) - _, err := conn.DeleteImagePipeline(ctx, input) - - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -480,6 +476,31 @@ func resourceImagePipelineDelete(ctx context.Context, d *schema.ResourceData, me return diags } +func findImagePipelineByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.ImagePipeline, error) { + input := &imagebuilder.GetImagePipelineInput{ + ImagePipelineArn: aws.String(arn), + } + + output, err := conn.GetImagePipeline(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.ImagePipeline == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.ImagePipeline, nil +} + func expandImageScanningConfiguration(tfMap map[string]interface{}) *awstypes.ImageScanningConfiguration { if tfMap == nil { return nil diff --git a/internal/service/imagebuilder/image_pipeline_test.go b/internal/service/imagebuilder/image_pipeline_test.go index d238fc9701f..6b242880a10 100644 --- a/internal/service/imagebuilder/image_pipeline_test.go +++ b/internal/service/imagebuilder/image_pipeline_test.go @@ -9,16 +9,14 @@ import ( "strings" "testing" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -728,49 +726,35 @@ func testAccCheckImagePipelineDestroy(ctx context.Context) resource.TestCheckFun continue } - input := &imagebuilder.GetImagePipelineInput{ - ImagePipelineArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetImagePipeline(ctx, input) + _, err := tfimagebuilder.FindImagePipelineByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Image Pipeline (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Image Pipeline (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Image Pipeline %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckImagePipelineExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckImagePipelineExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImagePipelineInput{ - ImagePipelineArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetImagePipeline(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Image Pipeline (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindImagePipelineByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 94648dcb247..99a65a3682e 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -134,7 +134,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceImagePipeline, + Factory: resourceImagePipeline, TypeName: "aws_imagebuilder_image_pipeline", Name: "Image Pipeline", Tags: &types.ServicePackageResourceTags{ From 8146dee86a5bbc90c67f0f71b03098017369bb54 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 12:44:01 -0400 Subject: [PATCH 079/112] d/aws_imagebuilder_image_pipeline: Reduce visibility. --- .../image_pipeline_data_source.go | 39 ++++++++----------- .../imagebuilder/service_package_gen.go | 4 +- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/internal/service/imagebuilder/image_pipeline_data_source.go b/internal/service/imagebuilder/image_pipeline_data_source.go index 78af1452e46..3829731a3e0 100644 --- a/internal/service/imagebuilder/image_pipeline_data_source.go +++ b/internal/service/imagebuilder/image_pipeline_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -17,8 +16,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_image_pipeline") -func DataSourceImagePipeline() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_image_pipeline", name="Image Pipeline") +// @Tags +func dataSourceImagePipeline() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceImagePipelineRead, @@ -152,24 +152,13 @@ func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, me var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImagePipelineInput{} - - if v, ok := d.GetOk(names.AttrARN); ok { - input.ImagePipelineArn = aws.String(v.(string)) - } - - output, err := conn.GetImagePipeline(ctx, input) + arn := d.Get(names.AttrARN).(string) + imagePipeline, err := findImagePipelineByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Pipeline: %s", err) - } - - if output == nil || output.ImagePipeline == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Pipeline: empty response") + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Pipeline (%s): %s", arn, err) } - imagePipeline := output.ImagePipeline - d.SetId(aws.ToString(imagePipeline.Arn)) d.Set(names.AttrARN, imagePipeline.Arn) d.Set("container_recipe_arn", imagePipeline.ContainerRecipeArn) @@ -182,12 +171,16 @@ func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, me d.Set("enhanced_image_metadata_enabled", imagePipeline.EnhancedImageMetadataEnabled) d.Set("image_recipe_arn", imagePipeline.ImageRecipeArn) if imagePipeline.ImageScanningConfiguration != nil { - d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(imagePipeline.ImageScanningConfiguration)}) + if err := d.Set("image_scanning_configuration", []interface{}{flattenImageScanningConfiguration(imagePipeline.ImageScanningConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image_scanning_configuration: %s", err) + } } else { d.Set("image_scanning_configuration", nil) } if imagePipeline.ImageTestsConfiguration != nil { - d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(imagePipeline.ImageTestsConfiguration)}) + if err := d.Set("image_tests_configuration", []interface{}{flattenImageTestsConfiguration(imagePipeline.ImageTestsConfiguration)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting image_tests_configuration: %s", err) + } } else { d.Set("image_tests_configuration", nil) } @@ -195,13 +188,15 @@ func dataSourceImagePipelineRead(ctx context.Context, d *schema.ResourceData, me d.Set(names.AttrName, imagePipeline.Name) d.Set("platform", imagePipeline.Platform) if imagePipeline.Schedule != nil { - d.Set(names.AttrSchedule, []interface{}{flattenSchedule(imagePipeline.Schedule)}) + if err := d.Set(names.AttrSchedule, []interface{}{flattenSchedule(imagePipeline.Schedule)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting schedule: %s", err) + } } else { d.Set(names.AttrSchedule, nil) } - d.Set(names.AttrStatus, imagePipeline.Status) - d.Set(names.AttrTags, KeyValueTags(ctx, imagePipeline.Tags).IgnoreAWS().IgnoreConfig(meta.(*conns.AWSClient).IgnoreTagsConfig).Map()) + + setTagsOut(ctx, imagePipeline.Tags) return diags } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 99a65a3682e..b880f0e68c6 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -72,8 +72,10 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceImagePipeline, + Factory: dataSourceImagePipeline, TypeName: "aws_imagebuilder_image_pipeline", + Name: "Image Pipeline", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceImagePipelines, From f2ee00514ce3dd2491a5814ca5a3116f3e9c38eb Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 12:54:11 -0400 Subject: [PATCH 080/112] d/aws_imagebuilder_image_pipelines: Reduce visibility. --- .../service/imagebuilder/image_data_source.go | 2 +- .../image_pipelines_data_source.go | 41 +++++++++++++------ .../imagebuilder/service_package_gen.go | 3 +- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/internal/service/imagebuilder/image_data_source.go b/internal/service/imagebuilder/image_data_source.go index 258755f5bf7..7e7eb2db642 100644 --- a/internal/service/imagebuilder/image_data_source.go +++ b/internal/service/imagebuilder/image_data_source.go @@ -185,7 +185,7 @@ func dataSourceImageRead(ctx context.Context, d *schema.ResourceData, meta inter image, err := findImageByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Image: %s", err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image (%s): %s", arn, err) } d.SetId(aws.ToString(image.Arn)) diff --git a/internal/service/imagebuilder/image_pipelines_data_source.go b/internal/service/imagebuilder/image_pipelines_data_source.go index 43e9abbc502..2df87c2c836 100644 --- a/internal/service/imagebuilder/image_pipelines_data_source.go +++ b/internal/service/imagebuilder/image_pipelines_data_source.go @@ -8,19 +8,22 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" namevaluesfiltersv2 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v2" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_image_pipelines") -func DataSourceImagePipelines() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_image_pipelines", name="Image Pipelines") +func dataSourceImagePipelines() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceImagePipelinesRead, + Schema: map[string]*schema.Schema{ names.AttrARNs: { Type: schema.TypeSet, @@ -47,22 +50,36 @@ func dataSourceImagePipelinesRead(ctx context.Context, d *schema.ResourceData, m input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } - out, err := conn.ListImagePipelines(ctx, input) + imagePipelines, err := findImagePipelines(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Pipelines: %s", err) } - var arns, nms []string - - for _, r := range out.ImagePipelineList { - arns = append(arns, aws.ToString(r.Arn)) - nms = append(nms, aws.ToString(r.Name)) - } - d.SetId(meta.(*conns.AWSClient).Region) - d.Set(names.AttrARNs, arns) - d.Set(names.AttrNames, nms) + d.Set(names.AttrARNs, tfslices.ApplyToAll(imagePipelines, func(v awstypes.ImagePipeline) string { + return aws.ToString(v.Arn) + })) + d.Set(names.AttrNames, tfslices.ApplyToAll(imagePipelines, func(v awstypes.ImagePipeline) string { + return aws.ToString(v.Name) + })) return diags } + +func findImagePipelines(ctx context.Context, conn *imagebuilder.Client, input *imagebuilder.ListImagePipelinesInput) ([]awstypes.ImagePipeline, error) { + var output []awstypes.ImagePipeline + + pages := imagebuilder.NewListImagePipelinesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.ImagePipelineList...) + } + + return output, nil +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index b880f0e68c6..6c5b2c56129 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -78,8 +78,9 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceImagePipelines, + Factory: dataSourceImagePipelines, TypeName: "aws_imagebuilder_image_pipelines", + Name: "Image Pipelines", }, { Factory: DataSourceImageRecipe, From 77432aa4537ce9beb2b844f00e7db6359d02111d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 13:01:02 -0400 Subject: [PATCH 081/112] r/aws_imagebuilder_image_recipe: Reduce visibility. --- internal/service/imagebuilder/export_tests.go | 2 + internal/service/imagebuilder/image_recipe.go | 77 +++++++++++-------- .../service/imagebuilder/image_recipe_test.go | 36 +++------ .../imagebuilder/service_package_gen.go | 2 +- 4 files changed, 60 insertions(+), 57 deletions(-) diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 63d1f245ed0..32b0a6978da 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -10,6 +10,7 @@ var ( ResourceDistributionConfiguration = resourceDistributionConfiguration ResourceImage = resourceImage ResourceImagePipeline = resourceImagePipeline + ResourceImageRecipe = resourceImageRecipe ResourceLifecyclePolicy = newResourceLifecyclePolicy FindComponentByARN = findComponentByARN @@ -17,5 +18,6 @@ var ( FindDistributionConfigurationByARN = findDistributionConfigurationByARN FindImageByARN = findImageByARN FindImagePipelineByARN = findImagePipelineByARN + FindImageRecipeByARN = findImageRecipeByARN FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index a4bdd5aea3e..7c4a47eefed 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -13,6 +13,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -21,18 +22,20 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/sdkv2/types/nullable" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_image_recipe", name="Image Recipe") // @Tags(identifierAttribute="id") -func ResourceImageRecipe() *schema.Resource { +func resourceImageRecipe() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceImageRecipeCreate, ReadWithoutTimeout: resourceImageRecipeRead, UpdateWithoutTimeout: resourceImageRecipeUpdate, DeleteWithoutTimeout: resourceImageRecipeDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -298,10 +301,6 @@ func resourceImageRecipeCreate(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Recipe: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Image Recipe: empty response") - } - d.SetId(aws.ToString(output.ImageRecipeArn)) return append(diags, resourceImageRecipeRead(ctx, d, meta)...) @@ -311,48 +310,42 @@ func resourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta i var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImageRecipeInput{ - ImageRecipeArn: aws.String(d.Id()), - } - - output, err := conn.GetImageRecipe(ctx, input) + imageRecipe, err := findImageRecipeByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Image Recipe (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Recipe (%s): %s", d.Id(), err) - } - - if output == nil || output.ImageRecipe == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Image Recipe (%s): empty response", d.Id()) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): %s", d.Id(), err) } - imageRecipe := output.ImageRecipe - d.Set(names.AttrARN, imageRecipe.Arn) - d.Set("block_device_mapping", flattenInstanceBlockDeviceMappings(imageRecipe.BlockDeviceMappings)) - d.Set("component", flattenComponentConfigurations(imageRecipe.Components)) + if err := d.Set("block_device_mapping", flattenInstanceBlockDeviceMappings(imageRecipe.BlockDeviceMappings)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting block_device_mapping: %s", err) + } + if err := d.Set("component", flattenComponentConfigurations(imageRecipe.Components)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting component: %s", err) + } d.Set("date_created", imageRecipe.DateCreated) d.Set(names.AttrDescription, imageRecipe.Description) d.Set(names.AttrName, imageRecipe.Name) d.Set(names.AttrOwner, imageRecipe.Owner) d.Set("parent_image", imageRecipe.ParentImage) d.Set("platform", imageRecipe.Platform) - - setTagsOut(ctx, imageRecipe.Tags) - if imageRecipe.AdditionalInstanceConfiguration != nil { - d.Set("systems_manager_agent", []interface{}{flattenSystemsManagerAgent(imageRecipe.AdditionalInstanceConfiguration.SystemsManagerAgent)}) + if err := d.Set("systems_manager_agent", []interface{}{flattenSystemsManagerAgent(imageRecipe.AdditionalInstanceConfiguration.SystemsManagerAgent)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting systems_manager_agent: %s", err) + } d.Set("user_data_base64", imageRecipe.AdditionalInstanceConfiguration.UserDataOverride) } - d.Set(names.AttrVersion, imageRecipe.Version) d.Set("working_directory", imageRecipe.WorkingDirectory) + setTagsOut(ctx, imageRecipe.Tags) + return diags } @@ -368,13 +361,12 @@ func resourceImageRecipeDelete(ctx context.Context, d *schema.ResourceData, meta var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteImageRecipeInput{ + log.Printf("[DEBUG] Deleting Image Builder Image Recipe: %s", d.Id()) + _, err := conn.DeleteImageRecipe(ctx, &imagebuilder.DeleteImageRecipeInput{ ImageRecipeArn: aws.String(d.Id()), - } - - _, err := conn.DeleteImageRecipe(ctx, input) + }) - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -385,6 +377,31 @@ func resourceImageRecipeDelete(ctx context.Context, d *schema.ResourceData, meta return diags } +func findImageRecipeByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.ImageRecipe, error) { + input := &imagebuilder.GetImageRecipeInput{ + ImageRecipeArn: aws.String(arn), + } + + output, err := conn.GetImageRecipe(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.ImageRecipe == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.ImageRecipe, nil +} + func expandComponentConfiguration(tfMap map[string]interface{}) *awstypes.ComponentConfiguration { if tfMap == nil { return nil diff --git a/internal/service/imagebuilder/image_recipe_test.go b/internal/service/imagebuilder/image_recipe_test.go index 94ff8a7324c..c5ae9497a75 100644 --- a/internal/service/imagebuilder/image_recipe_test.go +++ b/internal/service/imagebuilder/image_recipe_test.go @@ -9,16 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" itypes "github.com/hashicorp/terraform-provider-aws/internal/types" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -750,49 +748,35 @@ func testAccCheckImageRecipeDestroy(ctx context.Context) resource.TestCheckFunc continue } - input := &imagebuilder.GetImageRecipeInput{ - ImageRecipeArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetImageRecipe(ctx, input) + _, err := tfimagebuilder.FindImageRecipeByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Image Recipe (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Image Recipe (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Image Recipe %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckImageRecipeExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckImageRecipeExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetImageRecipeInput{ - ImageRecipeArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetImageRecipe(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Image Recipe (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindImageRecipeByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 6c5b2c56129..fac36629e34 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -145,7 +145,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceImageRecipe, + Factory: resourceImageRecipe, TypeName: "aws_imagebuilder_image_recipe", Name: "Image Recipe", Tags: &types.ServicePackageResourceTags{ From b98ec776d11f26ae47ff60527b3d3c9f4664232b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 13:09:10 -0400 Subject: [PATCH 082/112] d/aws_imagebuilder_image_recipe: Reduce visibility. --- .../imagebuilder/image_recipe_data_source.go | 42 ++++++++----------- .../imagebuilder/service_package_gen.go | 4 +- 2 files changed, 20 insertions(+), 26 deletions(-) diff --git a/internal/service/imagebuilder/image_recipe_data_source.go b/internal/service/imagebuilder/image_recipe_data_source.go index 75d1aed44c4..9c2740e0074 100644 --- a/internal/service/imagebuilder/image_recipe_data_source.go +++ b/internal/service/imagebuilder/image_recipe_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -17,8 +16,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_image_recipe") -func DataSourceImageRecipe() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_image_recipe", name="Image Recipe") +// @Tags +func dataSourceImageRecipe() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceImageRecipeRead, @@ -140,7 +140,7 @@ func DataSourceImageRecipe() *schema.Resource { Type: schema.TypeString, Computed: true, }, - names.AttrTags: tftags.TagsSchema(), + names.AttrTags: tftags.TagsSchemaComputed(), "user_data_base64": { Type: schema.TypeString, Computed: true, @@ -160,44 +160,36 @@ func DataSourceImageRecipe() *schema.Resource { func dataSourceImageRecipeRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - input := &imagebuilder.GetImageRecipeInput{} - - if v, ok := d.GetOk(names.AttrARN); ok { - input.ImageRecipeArn = aws.String(v.(string)) - } - - output, err := conn.GetImageRecipe(ctx, input) + arn := d.Get(names.AttrARN).(string) + imageRecipe, err := findImageRecipeByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): %s", aws.ToString(input.ImageRecipeArn), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): %s", arn, err) } - if output == nil || output.ImageRecipe == nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipe (%s): empty response", aws.ToString(input.ImageRecipeArn)) + arn = aws.ToString(imageRecipe.Arn) + d.SetId(arn) + d.Set(names.AttrARN, arn) + if err := d.Set("block_device_mapping", flattenInstanceBlockDeviceMappings(imageRecipe.BlockDeviceMappings)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting block_device_mapping: %s", err) + } + if err := d.Set("component", flattenComponentConfigurations(imageRecipe.Components)); err != nil { + return sdkdiag.AppendErrorf(diags, "setting component: %s", err) } - - imageRecipe := output.ImageRecipe - - d.SetId(aws.ToString(imageRecipe.Arn)) - d.Set(names.AttrARN, imageRecipe.Arn) - d.Set("block_device_mapping", flattenInstanceBlockDeviceMappings(imageRecipe.BlockDeviceMappings)) - d.Set("component", flattenComponentConfigurations(imageRecipe.Components)) d.Set("date_created", imageRecipe.DateCreated) d.Set(names.AttrDescription, imageRecipe.Description) d.Set(names.AttrName, imageRecipe.Name) d.Set(names.AttrOwner, imageRecipe.Owner) d.Set("parent_image", imageRecipe.ParentImage) d.Set("platform", imageRecipe.Platform) - d.Set(names.AttrTags, KeyValueTags(ctx, imageRecipe.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) - if imageRecipe.AdditionalInstanceConfiguration != nil { d.Set("user_data_base64", imageRecipe.AdditionalInstanceConfiguration.UserDataOverride) } - d.Set(names.AttrVersion, imageRecipe.Version) d.Set("working_directory", imageRecipe.WorkingDirectory) + setTagsOut(ctx, imageRecipe.Tags) + return diags } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index fac36629e34..cecbc6f1cf7 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -83,8 +83,10 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Image Pipelines", }, { - Factory: DataSourceImageRecipe, + Factory: dataSourceImageRecipe, TypeName: "aws_imagebuilder_image_recipe", + Name: "Image Recipe", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceImageRecipes, From a56200ae6100b4cd4f6df88c17646030f7fb4e4d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 13:12:27 -0400 Subject: [PATCH 083/112] d/aws_imagebuilder_image_recipes: Reduce visibility. --- .../imagebuilder/image_recipes_data_source.go | 46 +++++++++++++------ .../imagebuilder/service_package_gen.go | 2 +- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/internal/service/imagebuilder/image_recipes_data_source.go b/internal/service/imagebuilder/image_recipes_data_source.go index 7b8e32d1214..a4342b16a8b 100644 --- a/internal/service/imagebuilder/image_recipes_data_source.go +++ b/internal/service/imagebuilder/image_recipes_data_source.go @@ -16,13 +16,15 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" namevaluesfiltersv2 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v2" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKDataSource("aws_imagebuilder_image_recipes", name="Image Recipes") -func DataSourceImageRecipes() *schema.Resource { +func dataSourceImageRecipes() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceImageRecipesRead, + Schema: map[string]*schema.Schema{ names.AttrARNs: { Type: schema.TypeSet, @@ -50,30 +52,44 @@ func dataSourceImageRecipesRead(ctx context.Context, d *schema.ResourceData, met input := &imagebuilder.ListImageRecipesInput{} - if v, ok := d.GetOk(names.AttrOwner); ok { - input.Owner = awstypes.Ownership(v.(string)) - } - if v, ok := d.GetOk(names.AttrFilter); ok { input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } - out, err := conn.ListImageRecipes(ctx, input) - - if err != nil { - return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipes: %s", err) + if v, ok := d.GetOk(names.AttrOwner); ok { + input.Owner = awstypes.Ownership(v.(string)) } - var arns, nms []string + imageRecipes, err := findImageRecipes(ctx, conn, input) - for _, r := range out.ImageRecipeSummaryList { - arns = append(arns, aws.ToString(r.Arn)) - nms = append(nms, aws.ToString(r.Name)) + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Image Builder Image Recipes: %s", err) } d.SetId(meta.(*conns.AWSClient).Region) - d.Set(names.AttrARNs, arns) - d.Set(names.AttrNames, nms) + d.Set(names.AttrARNs, tfslices.ApplyToAll(imageRecipes, func(v awstypes.ImageRecipeSummary) string { + return aws.ToString(v.Arn) + })) + d.Set(names.AttrNames, tfslices.ApplyToAll(imageRecipes, func(v awstypes.ImageRecipeSummary) string { + return aws.ToString(v.Name) + })) return diags } + +func findImageRecipes(ctx context.Context, conn *imagebuilder.Client, input *imagebuilder.ListImageRecipesInput) ([]awstypes.ImageRecipeSummary, error) { + var output []awstypes.ImageRecipeSummary + + pages := imagebuilder.NewListImageRecipesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.ImageRecipeSummaryList...) + } + + return output, nil +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index cecbc6f1cf7..3a600abda88 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -89,7 +89,7 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceImageRecipes, + Factory: dataSourceImageRecipes, TypeName: "aws_imagebuilder_image_recipes", Name: "Image Recipes", }, From 3648ec2a75e711d3d1b1f6962329df83e9230a4d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 14:35:59 -0400 Subject: [PATCH 084/112] r/aws_imagebuilder_infrastructure_configuration: Reduce visibility. --- internal/service/imagebuilder/export_tests.go | 30 ++-- .../infrastructure_configuration.go | 131 +++++++++--------- .../infrastructure_configuration_test.go | 36 ++--- .../imagebuilder/service_package_gen.go | 2 +- 4 files changed, 91 insertions(+), 108 deletions(-) diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/export_tests.go index 32b0a6978da..eb8646edac7 100644 --- a/internal/service/imagebuilder/export_tests.go +++ b/internal/service/imagebuilder/export_tests.go @@ -5,19 +5,21 @@ package imagebuilder // Exports for use in tests only. var ( - ResourceComponent = resourceComponent - ResourceContainerRecipe = resourceContainerRecipe - ResourceDistributionConfiguration = resourceDistributionConfiguration - ResourceImage = resourceImage - ResourceImagePipeline = resourceImagePipeline - ResourceImageRecipe = resourceImageRecipe - ResourceLifecyclePolicy = newResourceLifecyclePolicy + ResourceComponent = resourceComponent + ResourceContainerRecipe = resourceContainerRecipe + ResourceDistributionConfiguration = resourceDistributionConfiguration + ResourceImage = resourceImage + ResourceImagePipeline = resourceImagePipeline + ResourceImageRecipe = resourceImageRecipe + ResourceInfrastructureConfiguration = resourceInfrastructureConfiguration + ResourceLifecyclePolicy = newResourceLifecyclePolicy - FindComponentByARN = findComponentByARN - FindContainerRecipeByARN = findContainerRecipeByARN - FindDistributionConfigurationByARN = findDistributionConfigurationByARN - FindImageByARN = findImageByARN - FindImagePipelineByARN = findImagePipelineByARN - FindImageRecipeByARN = findImageRecipeByARN - FindLifecyclePolicyByARN = findLifecyclePolicyByARN + FindComponentByARN = findComponentByARN + FindContainerRecipeByARN = findContainerRecipeByARN + FindDistributionConfigurationByARN = findDistributionConfigurationByARN + FindImageByARN = findImageByARN + FindImagePipelineByARN = findImagePipelineByARN + FindImageRecipeByARN = findImageRecipeByARN + FindInfrastructureConfigurationByARN = findInfrastructureConfigurationByARN + FindLifecyclePolicyByARN = findLifecyclePolicyByARN ) diff --git a/internal/service/imagebuilder/infrastructure_configuration.go b/internal/service/imagebuilder/infrastructure_configuration.go index 8f763d89b10..4df9e261148 100644 --- a/internal/service/imagebuilder/infrastructure_configuration.go +++ b/internal/service/imagebuilder/infrastructure_configuration.go @@ -27,12 +27,13 @@ import ( // @SDKResource("aws_imagebuilder_infrastructure_configuration", name="Infrastructure Configuration") // @Tags(identifierAttribute="id") -func ResourceInfrastructureConfiguration() *schema.Resource { +func resourceInfrastructureConfiguration() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceInfrastructureConfigurationCreate, ReadWithoutTimeout: resourceInfrastructureConfigurationRead, UpdateWithoutTimeout: resourceInfrastructureConfigurationUpdate, DeleteWithoutTimeout: resourceInfrastructureConfigurationDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -208,36 +209,24 @@ func resourceInfrastructureConfigurationCreate(ctx context.Context, d *schema.Re input.SubnetId = aws.String(v.(string)) } - var output *imagebuilder.CreateInfrastructureConfigurationOutput - err := retry.RetryContext(ctx, propagationTimeout, func() *retry.RetryError { - var err error - - output, err = conn.CreateInfrastructureConfiguration(ctx, input) - - if errs.Contains(err, "instance profile does not exist") { - return retry.RetryableError(err) - } - - if err != nil { - return retry.NonRetryableError(err) - } - - return nil - }) + outputRaw, err := tfresource.RetryWhen(ctx, propagationTimeout, + func() (interface{}, error) { + return conn.CreateInfrastructureConfiguration(ctx, input) + }, + func(err error) (bool, error) { + if errs.Contains(err, "instance profile does not exist") { + return true, err + } - if tfresource.TimedOut(err) { - output, err = conn.CreateInfrastructureConfiguration(ctx, input) - } + return false, err + }, + ) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Image Builder Infrastructure Configuration: %s", err) } - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Infrastructure Configuration: empty response") - } - - d.SetId(aws.ToString(output.InfrastructureConfigurationArn)) + d.SetId(aws.ToString(outputRaw.(*imagebuilder.CreateInfrastructureConfigurationOutput).InfrastructureConfigurationArn)) return append(diags, resourceInfrastructureConfigurationRead(ctx, d, meta)...) } @@ -246,46 +235,36 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetInfrastructureConfigurationInput{ - InfrastructureConfigurationArn: aws.String(d.Id()), - } - - output, err := conn.GetInfrastructureConfiguration(ctx, input) + infrastructureConfiguration, err := findInfrastructureConfigurationByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Infrastructure Configuration (%s) not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Infrastructure Configuration (%s): %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Infrastructure Configuration (%s): %s", d.Id(), err) } - if output == nil || output.InfrastructureConfiguration == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Infrastructure Configuration (%s): empty response", d.Id()) - } - - infrastructureConfiguration := output.InfrastructureConfiguration - d.Set(names.AttrARN, infrastructureConfiguration.Arn) d.Set("date_created", infrastructureConfiguration.DateCreated) d.Set("date_updated", infrastructureConfiguration.DateUpdated) d.Set(names.AttrDescription, infrastructureConfiguration.Description) - if infrastructureConfiguration.InstanceMetadataOptions != nil { - d.Set("instance_metadata_options", []interface{}{ - flattenInstanceMetadataOptions(infrastructureConfiguration.InstanceMetadataOptions), - }) + if err := d.Set("instance_metadata_options", []interface{}{flattenInstanceMetadataOptions(infrastructureConfiguration.InstanceMetadataOptions)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting instance_metadata_options: %s", err) + } } else { d.Set("instance_metadata_options", nil) } - d.Set("instance_profile_name", infrastructureConfiguration.InstanceProfileName) d.Set("instance_types", infrastructureConfiguration.InstanceTypes) d.Set("key_pair", infrastructureConfiguration.KeyPair) if infrastructureConfiguration.Logging != nil { - d.Set("logging", []interface{}{flattenLogging(infrastructureConfiguration.Logging)}) + if err := d.Set("logging", []interface{}{flattenLogging(infrastructureConfiguration.Logging)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting logging: %s", err) + } } else { d.Set("logging", nil) } @@ -294,11 +273,10 @@ func resourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Reso d.Set(names.AttrSecurityGroupIDs, infrastructureConfiguration.SecurityGroupIds) d.Set(names.AttrSNSTopicARN, infrastructureConfiguration.SnsTopicArn) d.Set(names.AttrSubnetID, infrastructureConfiguration.SubnetId) + d.Set("terminate_instance_on_failure", infrastructureConfiguration.TerminateInstanceOnFailure) setTagsOut(ctx, infrastructureConfiguration.Tags) - d.Set("terminate_instance_on_failure", infrastructureConfiguration.TerminateInstanceOnFailure) - return diags } @@ -364,23 +342,18 @@ func resourceInfrastructureConfigurationUpdate(ctx context.Context, d *schema.Re input.SubnetId = aws.String(v.(string)) } - err := retry.RetryContext(ctx, propagationTimeout, func() *retry.RetryError { - _, err := conn.UpdateInfrastructureConfiguration(ctx, input) - - if errs.Contains(err, "instance profile does not exist") { - return retry.RetryableError(err) - } - - if err != nil { - return retry.NonRetryableError(err) - } - - return nil - }) + _, err := tfresource.RetryWhen(ctx, propagationTimeout, + func() (interface{}, error) { + return conn.UpdateInfrastructureConfiguration(ctx, input) + }, + func(err error) (bool, error) { + if errs.Contains(err, "instance profile does not exist") { + return true, err + } - if tfresource.TimedOut(err) { - _, err = conn.UpdateInfrastructureConfiguration(ctx, input) - } + return false, err + }, + ) if err != nil { return sdkdiag.AppendErrorf(diags, "updating Image Builder Infrastructure Configuration (%s): %s", d.Id(), err) @@ -394,13 +367,12 @@ func resourceInfrastructureConfigurationDelete(ctx context.Context, d *schema.Re var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteInfrastructureConfigurationInput{ + log.Printf("[DEBUG] Deleting Image Infrastructure Configuration: %s", d.Id()) + _, err := conn.DeleteInfrastructureConfiguration(ctx, &imagebuilder.DeleteInfrastructureConfigurationInput{ InfrastructureConfigurationArn: aws.String(d.Id()), - } - - _, err := conn.DeleteInfrastructureConfiguration(ctx, input) + }) - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -411,6 +383,31 @@ func resourceInfrastructureConfigurationDelete(ctx context.Context, d *schema.Re return diags } +func findInfrastructureConfigurationByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.InfrastructureConfiguration, error) { + input := &imagebuilder.GetInfrastructureConfigurationInput{ + InfrastructureConfigurationArn: aws.String(arn), + } + + output, err := conn.GetInfrastructureConfiguration(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.InfrastructureConfiguration == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.InfrastructureConfiguration, nil +} + func expandInstanceMetadataOptions(tfMap map[string]interface{}) *awstypes.InstanceMetadataOptions { if tfMap == nil { return nil diff --git a/internal/service/imagebuilder/infrastructure_configuration_test.go b/internal/service/imagebuilder/infrastructure_configuration_test.go index b7ee05b8f6b..c73f562e2a6 100644 --- a/internal/service/imagebuilder/infrastructure_configuration_test.go +++ b/internal/service/imagebuilder/infrastructure_configuration_test.go @@ -8,15 +8,13 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -587,49 +585,35 @@ func testAccCheckInfrastructureConfigurationDestroy(ctx context.Context) resourc continue } - input := &imagebuilder.GetInfrastructureConfigurationInput{ - InfrastructureConfigurationArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetInfrastructureConfiguration(ctx, input) + _, err := tfimagebuilder.FindInfrastructureConfigurationByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Infrastructure Configuration (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Infrastructure Configuration (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Infrastructure Configuration %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckInfrastructureConfigurationExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckInfrastructureConfigurationExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetInfrastructureConfigurationInput{ - InfrastructureConfigurationArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetInfrastructureConfiguration(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Infrastructure Configuration (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindInfrastructureConfigurationByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 3a600abda88..7fcb6b7f923 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -155,7 +155,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceInfrastructureConfiguration, + Factory: resourceInfrastructureConfiguration, TypeName: "aws_imagebuilder_infrastructure_configuration", Name: "Infrastructure Configuration", Tags: &types.ServicePackageResourceTags{ From 0efb770da843906fa32a3599ef2c1c9dd4d8fa49 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 14:39:45 -0400 Subject: [PATCH 085/112] d/aws_imagebuilder_infrastructure_configuration: Reduce visibility. --- ...nfrastructure_configuration_data_source.go | 37 +++++++------------ .../imagebuilder/service_package_gen.go | 4 +- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/internal/service/imagebuilder/infrastructure_configuration_data_source.go b/internal/service/imagebuilder/infrastructure_configuration_data_source.go index 6994a164701..dbf00c3389f 100644 --- a/internal/service/imagebuilder/infrastructure_configuration_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configuration_data_source.go @@ -7,7 +7,6 @@ import ( "context" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -17,8 +16,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_infrastructure_configuration") -func DataSourceInfrastructureConfiguration() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_infrastructure_configuration", name="Infrastructure Configuration") +// @Tags +func dataSourceInfrastructureConfiguration() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceInfrastructureConfigurationRead, @@ -123,43 +123,33 @@ func DataSourceInfrastructureConfiguration() *schema.Resource { func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - input := &imagebuilder.GetInfrastructureConfigurationInput{} - - if v, ok := d.GetOk(names.AttrARN); ok { - input.InfrastructureConfigurationArn = aws.String(v.(string)) - } - - output, err := conn.GetInfrastructureConfiguration(ctx, input) + arn := d.Get(names.AttrARN).(string) + infrastructureConfiguration, err := findInfrastructureConfigurationByARN(ctx, conn, arn) if err != nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Infrastructure Configuration (%s): %s", d.Id(), err) - } - - if output == nil || output.InfrastructureConfiguration == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Infrastructure Configuration (%s): empty response", d.Id()) + return sdkdiag.AppendErrorf(diags, "reading Image Builder Infrastructure Configuration (%s): %s", arn, err) } - infrastructureConfiguration := output.InfrastructureConfiguration - d.SetId(aws.ToString(infrastructureConfiguration.Arn)) d.Set(names.AttrARN, infrastructureConfiguration.Arn) d.Set("date_created", infrastructureConfiguration.DateCreated) d.Set("date_updated", infrastructureConfiguration.DateUpdated) d.Set(names.AttrDescription, infrastructureConfiguration.Description) - if infrastructureConfiguration.InstanceMetadataOptions != nil { - d.Set("instance_metadata_options", []interface{}{flattenInstanceMetadataOptions(infrastructureConfiguration.InstanceMetadataOptions)}) + if err := d.Set("instance_metadata_options", []interface{}{flattenInstanceMetadataOptions(infrastructureConfiguration.InstanceMetadataOptions)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting instance_metadata_options: %s", err) + } } else { d.Set("instance_metadata_options", nil) } - d.Set("instance_profile_name", infrastructureConfiguration.InstanceProfileName) d.Set("instance_types", infrastructureConfiguration.InstanceTypes) d.Set("key_pair", infrastructureConfiguration.KeyPair) if infrastructureConfiguration.Logging != nil { - d.Set("logging", []interface{}{flattenLogging(infrastructureConfiguration.Logging)}) + if err := d.Set("logging", []interface{}{flattenLogging(infrastructureConfiguration.Logging)}); err != nil { + return sdkdiag.AppendErrorf(diags, "setting logging: %s", err) + } } else { d.Set("logging", nil) } @@ -168,8 +158,9 @@ func dataSourceInfrastructureConfigurationRead(ctx context.Context, d *schema.Re d.Set(names.AttrSecurityGroupIDs, infrastructureConfiguration.SecurityGroupIds) d.Set(names.AttrSNSTopicARN, infrastructureConfiguration.SnsTopicArn) d.Set(names.AttrSubnetID, infrastructureConfiguration.SubnetId) - d.Set(names.AttrTags, KeyValueTags(ctx, infrastructureConfiguration.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) d.Set("terminate_instance_on_failure", infrastructureConfiguration.TerminateInstanceOnFailure) + setTagsOut(ctx, infrastructureConfiguration.Tags) + return diags } diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 7fcb6b7f923..911a1e762c6 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -94,8 +94,10 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Image Recipes", }, { - Factory: DataSourceInfrastructureConfiguration, + Factory: dataSourceInfrastructureConfiguration, TypeName: "aws_imagebuilder_infrastructure_configuration", + Name: "Infrastructure Configuration", + Tags: &types.ServicePackageResourceTags{}, }, { Factory: DataSourceInfrastructureConfigurations, From d0d38c91f92fbcac687f34e62ad336cdcaf9696d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 14:45:26 -0400 Subject: [PATCH 086/112] d/aws_imagebuilder_infrastructure_configurations: Reduce visibility. --- ...frastructure_configurations_data_source.go | 41 +++++++++++++------ .../imagebuilder/service_package_gen.go | 3 +- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/internal/service/imagebuilder/infrastructure_configurations_data_source.go b/internal/service/imagebuilder/infrastructure_configurations_data_source.go index 12fc1554fb9..e009c2a4576 100644 --- a/internal/service/imagebuilder/infrastructure_configurations_data_source.go +++ b/internal/service/imagebuilder/infrastructure_configurations_data_source.go @@ -8,19 +8,22 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" namevaluesfiltersv2 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v2" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_imagebuilder_infrastructure_configurations") -func DataSourceInfrastructureConfigurations() *schema.Resource { +// @SDKDataSource("aws_imagebuilder_infrastructure_configurations", name="Infrastructure Configurations") +func dataSourceInfrastructureConfigurations() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceInfrastructureConfigurationsRead, + Schema: map[string]*schema.Schema{ names.AttrARNs: { Type: schema.TypeSet, @@ -47,22 +50,36 @@ func dataSourceInfrastructureConfigurationsRead(ctx context.Context, d *schema.R input.Filters = namevaluesfiltersv2.New(v.(*schema.Set)).ImageBuilderFilters() } - out, err := conn.ListInfrastructureConfigurations(ctx, input) + infrastructureConfigurations, err := findInfrastructureConfigurations(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Image Builder Infrastructure Configurations: %s", err) } - var arns, nms []string - - for _, r := range out.InfrastructureConfigurationSummaryList { - arns = append(arns, aws.ToString(r.Arn)) - nms = append(nms, aws.ToString(r.Name)) - } - d.SetId(meta.(*conns.AWSClient).Region) - d.Set(names.AttrARNs, arns) - d.Set(names.AttrNames, nms) + d.Set(names.AttrARNs, tfslices.ApplyToAll(infrastructureConfigurations, func(v awstypes.InfrastructureConfigurationSummary) string { + return aws.ToString(v.Arn) + })) + d.Set(names.AttrNames, tfslices.ApplyToAll(infrastructureConfigurations, func(v awstypes.InfrastructureConfigurationSummary) string { + return aws.ToString(v.Name) + })) return diags } + +func findInfrastructureConfigurations(ctx context.Context, conn *imagebuilder.Client, input *imagebuilder.ListInfrastructureConfigurationsInput) ([]awstypes.InfrastructureConfigurationSummary, error) { + var output []awstypes.InfrastructureConfigurationSummary + + pages := imagebuilder.NewListInfrastructureConfigurationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.InfrastructureConfigurationSummaryList...) + } + + return output, nil +} diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 911a1e762c6..349b77f86fc 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -100,8 +100,9 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceInfrastructureConfigurations, + Factory: dataSourceInfrastructureConfigurations, TypeName: "aws_imagebuilder_infrastructure_configurations", + Name: "Infrastructure Configurations", }, } } From 893bb81b14cb4e98da6e8db3d0e86e0343c2a129 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 14:52:45 -0400 Subject: [PATCH 087/112] r/aws_imagebuilder_image: Tidy up waiting. --- .../{export_tests.go => exports_tests.go} | 0 internal/service/imagebuilder/image.go | 45 ++++++++++++++++++- internal/service/imagebuilder/status.go | 41 ----------------- internal/service/imagebuilder/wait.go | 39 ---------------- 4 files changed, 44 insertions(+), 81 deletions(-) rename internal/service/imagebuilder/{export_tests.go => exports_tests.go} (100%) delete mode 100644 internal/service/imagebuilder/status.go delete mode 100644 internal/service/imagebuilder/wait.go diff --git a/internal/service/imagebuilder/export_tests.go b/internal/service/imagebuilder/exports_tests.go similarity index 100% rename from internal/service/imagebuilder/export_tests.go rename to internal/service/imagebuilder/exports_tests.go diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index 4da9dd7de16..1d7c5e2c79c 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -5,6 +5,7 @@ package imagebuilder import ( "context" + "errors" "log" "time" @@ -449,13 +450,55 @@ func findImageByARN(ctx context.Context, conn *imagebuilder.Client, arn string) return nil, err } - if output == nil || output.Image == nil { + if output == nil || output.Image == nil || output.Image.State == nil { return nil, tfresource.NewEmptyResultError(input) } return output.Image, nil } +func statusImage(ctx context.Context, conn *imagebuilder.Client, arn string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findImageByARN(ctx, conn, arn) + + if tfresource.NotFound(err) { + return nil, string(awstypes.ImageStatusPending), nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State.Status), nil + } +} + +func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, arn string, timeout time.Duration) (*awstypes.Image, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice( + awstypes.ImageStatusBuilding, + awstypes.ImageStatusCreating, + awstypes.ImageStatusDistributing, + awstypes.ImageStatusIntegrating, + awstypes.ImageStatusPending, + awstypes.ImageStatusTesting, + ), + Target: enum.Slice(awstypes.ImageStatusAvailable), + Refresh: statusImage(ctx, conn, arn), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Image); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.State.Reason))) + + return output, err + } + + return nil, err +} + func flattenOutputResources(apiObject *awstypes.OutputResources) map[string]interface{} { if apiObject == nil { return nil diff --git a/internal/service/imagebuilder/status.go b/internal/service/imagebuilder/status.go deleted file mode 100644 index cf69f17a853..00000000000 --- a/internal/service/imagebuilder/status.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package imagebuilder - -import ( - "context" - "fmt" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" -) - -// statusImage fetches the Image and its Status -func statusImage(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - input := &imagebuilder.GetImageInput{ - ImageBuildVersionArn: aws.String(imageBuildVersionArn), - } - - output, err := conn.GetImage(ctx, input) - - if err != nil { - return nil, string(awstypes.ImageStatusPending), err - } - - if output == nil || output.Image == nil || output.Image.State == nil { - return nil, string(awstypes.ImageStatusPending), nil - } - - status := output.Image.State.Status - - if status == awstypes.ImageStatusFailed { - return output.Image, string(status), fmt.Errorf("%s", aws.ToString(output.Image.State.Reason)) - } - - return output.Image, string(status), nil - } -} diff --git a/internal/service/imagebuilder/wait.go b/internal/service/imagebuilder/wait.go deleted file mode 100644 index cc39a9c0bb8..00000000000 --- a/internal/service/imagebuilder/wait.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package imagebuilder - -import ( - "context" - "time" - - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" - awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/enum" -) - -// waitImageStatusAvailable waits for an Image to return Available -func waitImageStatusAvailable(ctx context.Context, conn *imagebuilder.Client, imageBuildVersionArn string, timeout time.Duration) (*awstypes.Image, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice( - awstypes.ImageStatusBuilding, - awstypes.ImageStatusCreating, - awstypes.ImageStatusDistributing, - awstypes.ImageStatusIntegrating, - awstypes.ImageStatusPending, - awstypes.ImageStatusTesting, - ), - Target: enum.Slice(awstypes.ImageStatusAvailable), - Refresh: statusImage(ctx, conn, imageBuildVersionArn), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if v, ok := outputRaw.(*awstypes.Image); ok { - return v, err - } - - return nil, err -} From b69fc23f51236335cf1407b4a6ec2926ff6a8418 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 15:02:33 -0400 Subject: [PATCH 088/112] r/aws_imagebuilder_workflow: Reduce visibility. --- .../service/imagebuilder/exports_tests.go | 2 + .../imagebuilder/service_package_gen.go | 2 +- internal/service/imagebuilder/workflow.go | 67 ++++++++++++------- .../service/imagebuilder/workflow_test.go | 36 +++------- 4 files changed, 55 insertions(+), 52 deletions(-) diff --git a/internal/service/imagebuilder/exports_tests.go b/internal/service/imagebuilder/exports_tests.go index eb8646edac7..3bc08c1ae89 100644 --- a/internal/service/imagebuilder/exports_tests.go +++ b/internal/service/imagebuilder/exports_tests.go @@ -13,6 +13,7 @@ var ( ResourceImageRecipe = resourceImageRecipe ResourceInfrastructureConfiguration = resourceInfrastructureConfiguration ResourceLifecyclePolicy = newResourceLifecyclePolicy + ResourceWorkflow = resourceWorkflow FindComponentByARN = findComponentByARN FindContainerRecipeByARN = findContainerRecipeByARN @@ -22,4 +23,5 @@ var ( FindImageRecipeByARN = findImageRecipeByARN FindInfrastructureConfigurationByARN = findInfrastructureConfigurationByARN FindLifecyclePolicyByARN = findLifecyclePolicyByARN + FindWorkflowByARN = findWorkflowByARN ) diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 349b77f86fc..7c771f32669 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -166,7 +166,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceWorkflow, + Factory: resourceWorkflow, TypeName: "aws_imagebuilder_workflow", Name: "Workflow", Tags: &types.ServicePackageResourceTags{ diff --git a/internal/service/imagebuilder/workflow.go b/internal/service/imagebuilder/workflow.go index df32f18a0bd..4c55e5e984a 100644 --- a/internal/service/imagebuilder/workflow.go +++ b/internal/service/imagebuilder/workflow.go @@ -13,6 +13,7 @@ import ( awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -20,18 +21,20 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) // @SDKResource("aws_imagebuilder_workflow", name="Workflow") // @Tags(identifierAttribute="id") -func ResourceWorkflow() *schema.Resource { +func resourceWorkflow() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceWorkflowCreate, ReadWithoutTimeout: resourceWorkflowRead, UpdateWithoutTimeout: resourceWorkflowUpdate, DeleteWithoutTimeout: resourceWorkflowDelete, + Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, }, @@ -111,9 +114,10 @@ func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta in var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) + name := d.Get(names.AttrName).(string) input := &imagebuilder.CreateWorkflowInput{ ClientToken: aws.String(id.UniqueId()), - Name: aws.String(d.Get(names.AttrName).(string)), + Name: aws.String(name), SemanticVersion: aws.String(d.Get(names.AttrVersion).(string)), Type: awstypes.WorkflowType(d.Get(names.AttrType).(string)), Tags: getTagsIn(ctx), @@ -142,11 +146,7 @@ func resourceWorkflowCreate(ctx context.Context, d *schema.ResourceData, meta in output, err := conn.CreateWorkflow(ctx, input) if err != nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Workflow: %s", err) - } - - if output == nil { - return sdkdiag.AppendErrorf(diags, "creating Image Builder Workflow: empty response") + return sdkdiag.AppendErrorf(diags, "creating Image Builder Workflow (%s): %s", name, err) } d.SetId(aws.ToString(output.WorkflowBuildVersionArn)) @@ -158,24 +158,18 @@ func resourceWorkflowRead(ctx context.Context, d *schema.ResourceData, meta inte var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetWorkflowInput{ - WorkflowBuildVersionArn: aws.String(d.Id()), - } - - output, err := conn.GetWorkflow(ctx, input) + workflow, err := findWorkflowByARN(ctx, conn, d.Id()) - if !d.IsNewResource() && errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Image Builder Workflow (%s) not found, removing from state", d.Id()) d.SetId("") return diags } - if output == nil || output.Workflow == nil { - return sdkdiag.AppendErrorf(diags, "getting Image Builder Workflow (%s): empty response", d.Id()) + if err != nil { + return sdkdiag.AppendErrorf(diags, "reading Image Builder Workflow (%s): %s", d.Id(), err) } - workflow := output.Workflow - d.Set(names.AttrARN, workflow.Arn) d.Set("change_description", workflow.ChangeDescription) d.Set("data", workflow.Data) @@ -184,12 +178,11 @@ func resourceWorkflowRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set(names.AttrName, workflow.Name) d.Set(names.AttrKMSKeyID, workflow.KmsKeyId) d.Set(names.AttrOwner, workflow.Owner) - - setTagsOut(ctx, workflow.Tags) - d.Set(names.AttrType, workflow.Type) d.Set(names.AttrVersion, workflow.Version) + setTagsOut(ctx, workflow.Tags) + return diags } @@ -205,13 +198,12 @@ func resourceWorkflowDelete(ctx context.Context, d *schema.ResourceData, meta in var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.DeleteWorkflowInput{ + log.Printf("[DEBUG] Deleting Image Builder Workflow: %s", d.Id()) + _, err := conn.DeleteWorkflow(ctx, &imagebuilder.DeleteWorkflowInput{ WorkflowBuildVersionArn: aws.String(d.Id()), - } + }) - _, err := conn.DeleteWorkflow(ctx, input) - - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return diags } @@ -221,3 +213,28 @@ func resourceWorkflowDelete(ctx context.Context, d *schema.ResourceData, meta in return diags } + +func findWorkflowByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.Workflow, error) { + input := &imagebuilder.GetWorkflowInput{ + WorkflowBuildVersionArn: aws.String(arn), + } + + output, err := conn.GetWorkflow(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.Workflow == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Workflow, nil +} diff --git a/internal/service/imagebuilder/workflow_test.go b/internal/service/imagebuilder/workflow_test.go index 3d10667a499..25f634925d2 100644 --- a/internal/service/imagebuilder/workflow_test.go +++ b/internal/service/imagebuilder/workflow_test.go @@ -9,16 +9,14 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/imagebuilder" "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/errs" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -247,49 +245,35 @@ func testAccCheckWorkflowDestroy(ctx context.Context) resource.TestCheckFunc { continue } - input := &imagebuilder.GetWorkflowInput{ - WorkflowBuildVersionArn: aws.String(rs.Primary.ID), - } - - output, err := conn.GetWorkflow(ctx, input) + _, err := tfimagebuilder.FindWorkflowByARN(ctx, conn, rs.Primary.ID) - if errs.MessageContains(err, tfimagebuilder.ResourceNotFoundException, "cannot be found") { + if tfresource.NotFound(err) { continue } if err != nil { - return fmt.Errorf("error getting Image Builder Workflow (%s): %w", rs.Primary.ID, err) + return err } - if output != nil { - return fmt.Errorf("Image Builder Workflow (%s) still exists", rs.Primary.ID) - } + return fmt.Errorf("Image Builder Workflow %s still exists", rs.Primary.ID) } return nil } } -func testAccCheckWorkflowExists(ctx context.Context, resourceName string) resource.TestCheckFunc { +func testAccCheckWorkflowExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] + rs, ok := s.RootModule().Resources[n] if !ok { - return fmt.Errorf("resource not found: %s", resourceName) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) - input := &imagebuilder.GetWorkflowInput{ - WorkflowBuildVersionArn: aws.String(rs.Primary.ID), - } - - _, err := conn.GetWorkflow(ctx, input) - - if err != nil { - return fmt.Errorf("error getting Image Builder Workflow (%s): %w", rs.Primary.ID, err) - } + _, err := tfimagebuilder.FindWorkflowByARN(ctx, conn, rs.Primary.ID) - return nil + return err } } From 49214daefe0f8f5c9f8028a87e30abae080924fd Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:17:34 -0400 Subject: [PATCH 089/112] r/aws_imagebuilder_lifecycle_policy: Use AutoFlEx. --- internal/service/imagebuilder/consts.go | 3 - .../service/imagebuilder/exports_tests.go | 2 +- .../service/imagebuilder/lifecycle_policy.go | 1129 ++++------------- .../imagebuilder/lifecycle_policy_test.go | 26 +- .../imagebuilder/service_package_gen.go | 2 +- internal/service/imagebuilder/sweep.go | 2 +- ...magebuilder_lifecycle_policy.html.markdown | 12 +- 7 files changed, 250 insertions(+), 926 deletions(-) diff --git a/internal/service/imagebuilder/consts.go b/internal/service/imagebuilder/consts.go index dcd2f1ad7e6..1d85561bd79 100644 --- a/internal/service/imagebuilder/consts.go +++ b/internal/service/imagebuilder/consts.go @@ -9,7 +9,4 @@ import ( const ( propagationTimeout = 2 * time.Minute - - ResourceNotFoundException = "ResourceNotFoundException" - InvalidParameterValueException = "InvalidParameterValueException" ) diff --git a/internal/service/imagebuilder/exports_tests.go b/internal/service/imagebuilder/exports_tests.go index 3bc08c1ae89..bbe48598121 100644 --- a/internal/service/imagebuilder/exports_tests.go +++ b/internal/service/imagebuilder/exports_tests.go @@ -12,7 +12,7 @@ var ( ResourceImagePipeline = resourceImagePipeline ResourceImageRecipe = resourceImageRecipe ResourceInfrastructureConfiguration = resourceInfrastructureConfiguration - ResourceLifecyclePolicy = newResourceLifecyclePolicy + ResourceLifecyclePolicy = newLifecyclePolicyResource ResourceWorkflow = resourceWorkflow FindComponentByARN = findComponentByARN diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index b2d907bdaab..f364546bc1e 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -5,16 +5,16 @@ package imagebuilder import ( "context" - "errors" + "fmt" + "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" - "github.com/hashicorp/terraform-plugin-framework/attr" - "github.com/hashicorp/terraform-plugin-framework/diag" - "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" @@ -22,13 +22,13 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/schema/validator" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" + sdkid "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "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/fwdiag" "github.com/hashicorp/terraform-provider-aws/internal/framework" - "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" + fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" + fwtypes "github.com/hashicorp/terraform-provider-aws/internal/framework/types" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" @@ -36,89 +36,79 @@ import ( // @FrameworkResource(name="Lifecycle Policy") // @Tags(identifierAttribute="id") -func newResourceLifecyclePolicy(_ context.Context) (resource.ResourceWithConfigure, error) { - return &resourceLifecyclePolicy{}, nil +func newLifecyclePolicyResource(_ context.Context) (resource.ResourceWithConfigure, error) { + return &lifecyclePolicyResource{}, nil } -const ( - ResNameLifecyclePolicy = "Lifecycle Policy" -) - -type resourceLifecyclePolicy struct { +type lifecyclePolicyResource struct { framework.ResourceWithConfigure + framework.WithImportByID } -func (r *resourceLifecyclePolicy) Metadata(_ context.Context, request resource.MetadataRequest, response *resource.MetadataResponse) { +func (*lifecyclePolicyResource) Metadata(_ context.Context, request resource.MetadataRequest, response *resource.MetadataResponse) { response.TypeName = "aws_imagebuilder_lifecycle_policy" } -func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ +func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.SchemaRequest, response *resource.SchemaResponse) { + response.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ names.AttrARN: framework.ARNAttributeComputedOnly(), names.AttrDescription: schema.StringAttribute{ Optional: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), + Validators: []validator.String{ + stringvalidator.LengthBetween(1, 1024), }, }, "execution_role": schema.StringAttribute{ - Required: true, + CustomType: fwtypes.ARNType, + Required: true, }, names.AttrID: framework.IDAttribute(), names.AttrName: schema.StringAttribute{ Required: true, + Validators: []validator.String{ + stringvalidator.RegexMatches(regexache.MustCompile(`^[-_A-Za-z-0-9][-_A-Za-z0-9 ]{1,126}[-_A-Za-z-0-9]$`), ""), + }, PlanModifiers: []planmodifier.String{ stringplanmodifier.RequiresReplace(), }, }, names.AttrResourceType: schema.StringAttribute{ - Optional: true, - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), - }, - Validators: []validator.String{ - enum.FrameworkValidate[awstypes.LifecyclePolicyResourceType](), - }, + CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyResourceType](), + Required: true, }, names.AttrStatus: schema.StringAttribute{ - Optional: true, - Computed: true, - PlanModifiers: []planmodifier.String{ - stringplanmodifier.UseStateForUnknown(), - }, - Validators: []validator.String{ - enum.FrameworkValidate[awstypes.LifecyclePolicyStatus](), - }, + CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyStatus](), + Optional: true, }, names.AttrTags: tftags.TagsAttribute(), names.AttrTagsAll: tftags.TagsAttributeComputedOnly(), }, Blocks: map[string]schema.Block{ - "policy_details": schema.SetNestedBlock{ + "policy_detail": schema.SetNestedBlock{ + CustomType: fwtypes.NewSetNestedObjectTypeOf[lifecyclePolicyDetailModel](ctx), Validators: []validator.Set{ - setvalidator.SizeAtLeast(1), - setvalidator.SizeAtMost(3), + setvalidator.IsRequired(), + setvalidator.SizeBetween(1, 3), }, NestedObject: schema.NestedBlockObject{ Blocks: map[string]schema.Block{ names.AttrAction: schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailActionModel](ctx), Validators: []validator.List{ - listvalidator.SizeAtMost(1), listvalidator.IsRequired(), + listvalidator.SizeAtMost(1), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ names.AttrType: schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - enum.FrameworkValidate[awstypes.LifecyclePolicyDetailActionType](), - }, + CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyDetailActionType](), + Required: true, }, }, Blocks: map[string]schema.Block{ "include_resources": schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailActionIncludeResourcesModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), }, @@ -126,21 +116,18 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem Attributes: map[string]schema.Attribute{ "amis": schema.BoolAttribute{ Optional: true, - Computed: true, PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, }, "containers": schema.BoolAttribute{ Optional: true, - Computed: true, PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, }, "snapshots": schema.BoolAttribute{ Optional: true, - Computed: true, PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, @@ -151,47 +138,22 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, }, }, - names.AttrFilter: schema.ListNestedBlock{ - Validators: []validator.List{ - listvalidator.SizeAtMost(1), - listvalidator.IsRequired(), - }, - NestedObject: schema.NestedBlockObject{ - Attributes: map[string]schema.Attribute{ - names.AttrType: schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - enum.FrameworkValidate[awstypes.LifecyclePolicyDetailFilterType](), - }, - }, - names.AttrValue: schema.Int64Attribute{ - Required: true, - }, - "retain_at_least": schema.Int64Attribute{ - Optional: true, - }, - names.AttrUnit: schema.StringAttribute{ - Optional: true, - Validators: []validator.String{ - enum.FrameworkValidate[awstypes.LifecyclePolicyTimeUnit](), - }, - }, - }, - }, - }, "exclusion_rules": schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailExclusionRulesModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ "tag_map": schema.MapAttribute{ - ElementType: types.StringType, + CustomType: fwtypes.MapOfStringType, Optional: true, + ElementType: types.StringType, }, }, Blocks: map[string]schema.Block{ "amis": schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailExclusionRulesAMIsModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), }, @@ -201,33 +163,38 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem Optional: true, }, "regions": schema.ListAttribute{ + CustomType: fwtypes.ListOfStringType, ElementType: types.StringType, Optional: true, }, "shared_accounts": schema.ListAttribute{ + CustomType: fwtypes.ListOfStringType, ElementType: types.StringType, Optional: true, }, "tag_map": schema.MapAttribute{ - ElementType: types.StringType, + CustomType: fwtypes.MapOfStringType, Optional: true, + ElementType: types.StringType, }, }, Blocks: map[string]schema.Block{ "last_launched": schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailExclusionRulesAmisLastLaunchedModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ names.AttrUnit: schema.StringAttribute{ - Required: true, - Validators: []validator.String{ - enum.FrameworkValidate[awstypes.LifecyclePolicyTimeUnit](), - }, + CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyTimeUnit](), + Required: true, }, names.AttrValue: schema.Int64Attribute{ Required: true, + Validators: []validator.Int64{ + int64validator.Between(1, 365), + }, }, }, }, @@ -238,10 +205,42 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem }, }, }, + names.AttrFilter: schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailFilterModel](ctx), + Validators: []validator.List{ + listvalidator.IsRequired(), + listvalidator.SizeAtMost(1), + }, + NestedObject: schema.NestedBlockObject{ + Attributes: map[string]schema.Attribute{ + "retain_at_least": schema.Int64Attribute{ + Optional: true, + Validators: []validator.Int64{ + int64validator.Between(1, 10), + }, + }, + names.AttrType: schema.StringAttribute{ + CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyDetailFilterType](), + Required: true, + }, + names.AttrUnit: schema.StringAttribute{ + CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyTimeUnit](), + Optional: true, + }, + names.AttrValue: schema.Int64Attribute{ + Required: true, + Validators: []validator.Int64{ + int64validator.Between(1, 1000), + }, + }, + }, + }, + }, }, }, }, "resource_selection": schema.ListNestedBlock{ + CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyResourceSelectionModel](ctx), Validators: []validator.List{ listvalidator.IsRequired(), listvalidator.SizeAtMost(1), @@ -249,23 +248,30 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ "tag_map": schema.MapAttribute{ - ElementType: types.StringType, + CustomType: fwtypes.MapOfStringType, Optional: true, + ElementType: types.StringType, }, }, Blocks: map[string]schema.Block{ - "recipes": schema.SetNestedBlock{ + "recipe": schema.SetNestedBlock{ + CustomType: fwtypes.NewSetNestedObjectTypeOf[lifecyclePolicyResourceSelectionRecipeModel](ctx), Validators: []validator.Set{ - setvalidator.SizeAtLeast(1), setvalidator.SizeAtMost(50), }, NestedObject: schema.NestedBlockObject{ Attributes: map[string]schema.Attribute{ names.AttrName: schema.StringAttribute{ Required: true, + Validators: []validator.String{ + stringvalidator.RegexMatches(regexache.MustCompile(`^[-_A-Za-z-0-9][-_A-Za-z0-9 ]{1,126}[-_A-Za-z-0-9]$`), ""), + }, }, "semantic_version": schema.StringAttribute{ Required: true, + Validators: []validator.String{ + stringvalidator.RegexMatches(regexache.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`), ""), + }, }, }, }, @@ -277,916 +283,243 @@ func (r *resourceLifecyclePolicy) Schema(ctx context.Context, req resource.Schem } } -func (r *resourceLifecyclePolicy) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var plan resourceLifecyclePolicyData - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { +func (r *lifecyclePolicyResource) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) { + var data lifecyclePolicyResourceModel + response.Diagnostics.Append(request.Plan.Get(ctx, &data)...) + if response.Diagnostics.HasError() { return } conn := r.Meta().ImageBuilderClient(ctx) - in := &imagebuilder.CreateLifecyclePolicyInput{ - ClientToken: aws.String(id.UniqueId()), - ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), - Name: aws.String(plan.Name.ValueString()), - ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), - Tags: getTagsIn(ctx), - } - - if !plan.Description.IsNull() { - in.Description = aws.String(plan.Description.ValueString()) - } - - if !plan.PolicyDetails.IsNull() { - var tfList []resourcePolicyDetailsData - resp.Diagnostics.Append(plan.PolicyDetails.ElementsAs(ctx, &tfList, false)...) - if resp.Diagnostics.HasError() { - return - } - - policyDetails, d := expandPolicyDetails(ctx, tfList) - resp.Diagnostics.Append(d...) - if resp.Diagnostics.HasError() { - return - } - in.PolicyDetails = policyDetails - } - - if !plan.ResourceSelection.IsNull() { - var tfList []resourceResourceSelectionData - resp.Diagnostics.Append(plan.ResourceSelection.ElementsAs(ctx, &tfList, false)...) - if resp.Diagnostics.HasError() { - return - } - - resourceSelection, d := expandResourceSelection(ctx, tfList) - resp.Diagnostics.Append(d...) - if resp.Diagnostics.HasError() { - return - } - in.ResourceSelection = resourceSelection + name := fwflex.StringValueFromFramework(ctx, data.Name) + input := &imagebuilder.CreateLifecyclePolicyInput{} + response.Diagnostics.Append(fwflex.Expand(ctx, data, input)...) + if response.Diagnostics.HasError() { + return } - if !plan.Status.IsNull() { - in.Status = awstypes.LifecyclePolicyStatus(plan.Status.ValueString()) - } + // Additional fields. + input.ClientToken = aws.String(sdkid.UniqueId()) + input.Tags = getTagsIn(ctx) - // Include retry handling to allow for IAM propagation - var out *imagebuilder.CreateLifecyclePolicyOutput - err := tfresource.Retry(ctx, propagationTimeout, func() *retry.RetryError { - var err error - out, err = conn.CreateLifecyclePolicy(ctx, in) - if err != nil { - if errs.MessageContains(err, InvalidParameterValueException, "The provided role does not exist or does not have sufficient permissions") { - return retry.RetryableError(err) - } - return retry.NonRetryableError(err) - } - return nil - }) + outputRaw, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.InvalidParameterValueException](ctx, propagationTimeout, func() (interface{}, error) { + return conn.CreateLifecyclePolicy(ctx, input) + }, "The provided role does not exist or does not have sufficient permissions") if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), err), - err.Error(), - ) - return - } - if out == nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), nil), - errors.New("empty output").Error(), - ) - return - } - - plan.ID = flex.StringToFramework(ctx, out.LifecyclePolicyArn) - plan.ARN = flex.StringToFramework(ctx, out.LifecyclePolicyArn) + response.Diagnostics.AddError(fmt.Sprintf("creating Image Builder Lifecycle Policy (%s)", name), err.Error()) - // Read to retrieve computed arguments not part of the create response - readOut, err := findLifecyclePolicyByARN(ctx, conn, plan.ARN.ValueString()) - if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionCreating, ResNameLifecyclePolicy, plan.Name.String(), err), - err.Error(), - ) return } - plan.Status = flex.StringValueToFramework(ctx, readOut.Status) - plan.ResourceType = flex.StringValueToFramework(ctx, readOut.ResourceType) + output := outputRaw.(*imagebuilder.CreateLifecyclePolicyOutput) - policyDetails, d := flattenPolicyDetails(ctx, readOut.PolicyDetails) - resp.Diagnostics.Append(d...) - plan.PolicyDetails = policyDetails + // Set values for unknowns. + data.LifecyclePolicyARN = fwflex.StringToFramework(ctx, output.LifecyclePolicyArn) + data.setID() - resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + response.Diagnostics.Append(response.State.Set(ctx, data)...) } -func (r *resourceLifecyclePolicy) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - conn := r.Meta().ImageBuilderClient(ctx) - - var state resourceLifecyclePolicyData - resp.Diagnostics.Append(req.State.Get(ctx, &state)...) - if resp.Diagnostics.HasError() { +func (r *lifecyclePolicyResource) Read(ctx context.Context, request resource.ReadRequest, response *resource.ReadResponse) { + var data lifecyclePolicyResourceModel + response.Diagnostics.Append(request.State.Get(ctx, &data)...) + if response.Diagnostics.HasError() { return } - out, err := findLifecyclePolicyByARN(ctx, conn, state.ID.ValueString()) + conn := r.Meta().ImageBuilderClient(ctx) + + output, err := findLifecyclePolicyByARN(ctx, conn, data.ID.ValueString()) if tfresource.NotFound(err) { - resp.State.RemoveResource(ctx) + response.Diagnostics.Append(fwdiag.NewResourceNotFoundWarningDiagnostic(err)) + response.State.RemoveResource(ctx) + return } + if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionReading, ResNameLifecyclePolicy, state.Name.String(), nil), - err.Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("reading Image Builder Lifecycle Policy (%s)", data.ID.ValueString()), err.Error()) + return } - state.ARN = flex.StringToFramework(ctx, out.Arn) - state.ID = flex.StringToFramework(ctx, out.Arn) - state.Description = flex.StringToFramework(ctx, out.Description) - state.ExecutionRole = flex.StringToFramework(ctx, out.ExecutionRole) - state.Name = flex.StringToFramework(ctx, out.Name) - - policyDetails, d := flattenPolicyDetails(ctx, out.PolicyDetails) - resp.Diagnostics.Append(d...) - state.PolicyDetails = policyDetails + setTagsOut(ctx, output.Tags) - resourceSelection, d := flattenResourceSelection(ctx, out.ResourceSelection) - resp.Diagnostics.Append(d...) - state.ResourceSelection = resourceSelection - - state.ResourceType = flex.StringValueToFramework(ctx, out.ResourceType) - state.Status = flex.StringValueToFramework(ctx, out.Status) - - setTagsOut(ctx, out.Tags) + // Set attributes for import. + response.Diagnostics.Append(fwflex.Flatten(ctx, output, &data)...) + if response.Diagnostics.HasError() { + return + } - resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) + response.Diagnostics.Append(response.State.Set(ctx, &data)...) } -func (r *resourceLifecyclePolicy) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - conn := r.Meta().ImageBuilderClient(ctx) - - var plan, state resourceLifecyclePolicyData - resp.Diagnostics.Append(req.State.Get(ctx, &state)...) - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { +func (r *lifecyclePolicyResource) Update(ctx context.Context, request resource.UpdateRequest, response *resource.UpdateResponse) { + var old, new lifecyclePolicyResourceModel + response.Diagnostics.Append(request.Plan.Get(ctx, &new)...) + if response.Diagnostics.HasError() { + return + } + response.Diagnostics.Append(request.State.Get(ctx, &old)...) + if response.Diagnostics.HasError() { return } - if !plan.Description.Equal(state.Description) || - !plan.ExecutionRole.Equal(state.ExecutionRole) || - !plan.PolicyDetails.Equal(state.PolicyDetails) || - !plan.ResourceSelection.Equal(state.ResourceSelection) || - !plan.ResourceType.Equal(state.ResourceType) || - !plan.Status.Equal(state.Status) { - in := &imagebuilder.UpdateLifecyclePolicyInput{ - LifecyclePolicyArn: aws.String(plan.ID.ValueString()), - ExecutionRole: aws.String(plan.ExecutionRole.ValueString()), - ResourceType: awstypes.LifecyclePolicyResourceType(plan.ResourceType.ValueString()), - Status: awstypes.LifecyclePolicyStatus(plan.Status.ValueString()), - } - - if !plan.Description.IsNull() { - in.Description = aws.String(plan.Description.ValueString()) - } - - if !plan.PolicyDetails.IsNull() { - var tfList []resourcePolicyDetailsData - resp.Diagnostics.Append(plan.PolicyDetails.ElementsAs(ctx, &tfList, false)...) - if resp.Diagnostics.HasError() { - return - } + conn := r.Meta().ImageBuilderClient(ctx) - policyDetails, d := expandPolicyDetails(ctx, tfList) - resp.Diagnostics.Append(d...) - if resp.Diagnostics.HasError() { - return - } - in.PolicyDetails = policyDetails + if !new.Description.Equal(old.Description) || + !new.ExecutionRole.Equal(old.ExecutionRole) || + !new.PolicyDetails.Equal(old.PolicyDetails) || + !new.ResourceSelection.Equal(old.ResourceSelection) || + !new.ResourceType.Equal(old.ResourceType) || + !new.Status.Equal(old.Status) { + input := &imagebuilder.UpdateLifecyclePolicyInput{} + response.Diagnostics.Append(fwflex.Expand(ctx, new, input)...) + if response.Diagnostics.HasError() { + return } - if !plan.ResourceSelection.IsNull() { - var tfList []resourceResourceSelectionData - resp.Diagnostics.Append(plan.ResourceSelection.ElementsAs(ctx, &tfList, false)...) - if resp.Diagnostics.HasError() { - return - } + // Additional fields. + input.ClientToken = aws.String(sdkid.UniqueId()) - resourceSelection, d := expandResourceSelection(ctx, tfList) - resp.Diagnostics.Append(d...) - if resp.Diagnostics.HasError() { - return - } - in.ResourceSelection = resourceSelection - } - - // Include retry handling to allow for IAM propagation - var out *imagebuilder.UpdateLifecyclePolicyOutput - err := tfresource.Retry(ctx, propagationTimeout, func() *retry.RetryError { - var err error - out, err = conn.UpdateLifecyclePolicy(ctx, in) - if err != nil { - if errs.MessageContains(err, InvalidParameterValueException, "The provided role does not exist or does not have sufficient permissions") { - return retry.RetryableError(err) - } - return retry.NonRetryableError(err) - } - return nil - }) + _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.InvalidParameterValueException](ctx, propagationTimeout, func() (interface{}, error) { + return conn.UpdateLifecyclePolicy(ctx, input) + }, "The provided role does not exist or does not have sufficient permissions") if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionUpdating, ResNameLifecyclePolicy, plan.ID.String(), err), - err.Error(), - ) - return - } - if out == nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionUpdating, ResNameLifecyclePolicy, plan.ID.String(), nil), - errors.New("empty output").Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("updating Image Builder Lifecycle Policy (%s)", new.ID.ValueString()), err.Error()) + return } } - resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) + response.Diagnostics.Append(response.State.Set(ctx, &new)...) } -func (r *resourceLifecyclePolicy) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - conn := r.Meta().ImageBuilderClient(ctx) - - var state resourceLifecyclePolicyData - resp.Diagnostics.Append(req.State.Get(ctx, &state)...) - if resp.Diagnostics.HasError() { +func (r *lifecyclePolicyResource) Delete(ctx context.Context, request resource.DeleteRequest, response *resource.DeleteResponse) { + var data lifecyclePolicyResourceModel + response.Diagnostics.Append(request.State.Get(ctx, &data)...) + if response.Diagnostics.HasError() { return } + conn := r.Meta().ImageBuilderClient(ctx) + _, err := conn.DeleteLifecyclePolicy(ctx, &imagebuilder.DeleteLifecyclePolicyInput{ - LifecyclePolicyArn: aws.String(state.ID.ValueString()), + LifecyclePolicyArn: aws.String(data.ID.ValueString()), }) - if err != nil { - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { - return - } - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.ImageBuilder, create.ErrActionDeleting, ResNameLifecyclePolicy, state.ID.String(), nil), - err.Error(), - ) + if errs.IsA[*awstypes.ResourceNotFoundException](err) { return } -} - -func (r *resourceLifecyclePolicy) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resource.ImportStatePassthroughID(ctx, path.Root(names.AttrID), req, resp) -} -func (r *resourceLifecyclePolicy) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { - r.SetTagsAll(ctx, req, resp) -} - -func findLifecyclePolicyByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.LifecyclePolicy, error) { - in := &imagebuilder.GetLifecyclePolicyInput{ - LifecyclePolicyArn: aws.String(arn), - } - - out, err := conn.GetLifecyclePolicy(ctx, in) if err != nil { - if errs.MessageContains(err, ResourceNotFoundException, "cannot be found") { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: in, - } - } - return nil, err - } - - if out == nil { - return nil, tfresource.NewEmptyResultError(in) - } - - return out.LifecyclePolicy, nil -} - -func expandPolicyDetails(ctx context.Context, tfList []resourcePolicyDetailsData) ([]awstypes.LifecyclePolicyDetail, diag.Diagnostics) { - var diags diag.Diagnostics - - if len(tfList) == 0 { - return nil, diags - } - - apiResult := []awstypes.LifecyclePolicyDetail{} - - for _, policyDetail := range tfList { - apiObject := awstypes.LifecyclePolicyDetail{} - - if !policyDetail.Action.IsNull() { - var tfList []resourceActionData - diags.Append(policyDetail.Action.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags - } - - action, d := expandPolicyDetailAction(ctx, tfList) - diags.Append(d...) - if diags.HasError() { - return nil, diags - } - apiObject.Action = action - } - - if !policyDetail.Filter.IsNull() { - var tfList []resourceFilterData - diags.Append(policyDetail.Filter.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags - } - - apiObject.Filter = expandPolicyDetailFilter(tfList) - } - - if !policyDetail.ExclusionRules.IsNull() { - var tfList []resourceExclusionRulesData - diags.Append(policyDetail.ExclusionRules.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags - } - - exclusionRules, d := expandPolicyDetailExclusionRules(ctx, tfList) - diags.Append(d...) - if diags.HasError() { - return nil, diags - } - apiObject.ExclusionRules = exclusionRules - } - - apiResult = append(apiResult, apiObject) - } - - return apiResult, diags -} - -func expandPolicyDetailAction(ctx context.Context, tfList []resourceActionData) (*awstypes.LifecyclePolicyDetailAction, diag.Diagnostics) { - var diags diag.Diagnostics - - if len(tfList) == 0 { - return nil, diags - } - - tfObj := tfList[0] - - apiObject := awstypes.LifecyclePolicyDetailAction{ - Type: awstypes.LifecyclePolicyDetailActionType(tfObj.Type.ValueString()), - } - - if !tfObj.IncludeResources.IsNull() { - var tfList []resourceIncludeResourcesData - diags.Append(tfObj.IncludeResources.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags - } - - apiObject.IncludeResources = expandPolicyDetailActionIncludeResources(tfList) - } - - return &apiObject, diags -} - -func expandPolicyDetailActionIncludeResources(tfList []resourceIncludeResourcesData) *awstypes.LifecyclePolicyDetailActionIncludeResources { - tfObj := tfList[0] + response.Diagnostics.AddError(fmt.Sprintf("deleting Image Builder Lifecycle Policy (%s)", data.ID.ValueString()), err.Error()) - apiObject := awstypes.LifecyclePolicyDetailActionIncludeResources{ - Amis: tfObj.Amis.ValueBool(), - Containers: tfObj.Containers.ValueBool(), - Snapshots: tfObj.Snapshots.ValueBool(), + return } - - return &apiObject } -func expandPolicyDetailFilter(tfList []resourceFilterData) *awstypes.LifecyclePolicyDetailFilter { - if len(tfList) == 0 { - return nil - } - - tfObj := tfList[0] - - apiObject := awstypes.LifecyclePolicyDetailFilter{} - - if !tfObj.Type.IsNull() { - apiObject.Type = awstypes.LifecyclePolicyDetailFilterType(tfObj.Type.ValueString()) - } - - if !tfObj.Value.IsNull() { - apiObject.Value = aws.Int32(int32(tfObj.Value.ValueInt64())) - } - - if !tfObj.RetainAtLeast.IsNull() { - apiObject.RetainAtLeast = aws.Int32(int32(tfObj.RetainAtLeast.ValueInt64())) - } - - if !tfObj.Unit.IsNull() { - apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Unit.ValueString()) - } - - return &apiObject +func (r *lifecyclePolicyResource) ModifyPlan(ctx context.Context, request resource.ModifyPlanRequest, response *resource.ModifyPlanResponse) { + r.SetTagsAll(ctx, request, response) } -func expandPolicyDetailExclusionRules(ctx context.Context, tfList []resourceExclusionRulesData) (*awstypes.LifecyclePolicyDetailExclusionRules, diag.Diagnostics) { - var diags diag.Diagnostics - - if len(tfList) == 0 { - return nil, diags +func findLifecyclePolicyByARN(ctx context.Context, conn *imagebuilder.Client, arn string) (*awstypes.LifecyclePolicy, error) { + input := &imagebuilder.GetLifecyclePolicyInput{ + LifecyclePolicyArn: aws.String(arn), } - tfObj := tfList[0] - - apiObject := awstypes.LifecyclePolicyDetailExclusionRules{} + output, err := conn.GetLifecyclePolicy(ctx, input) - if !tfObj.AMIs.IsNull() { - var tfList []resourceAMISData - diags.Append(tfObj.AMIs.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags + if errs.IsA[*awstypes.ResourceNotFoundException](err) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } - - Amis, d := expandPolicyDetailExclusionRulesAMIS(ctx, tfList) - diags.Append(d...) - if diags.HasError() { - return nil, diags - } - apiObject.Amis = Amis } - if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) + if output == nil { + return nil, tfresource.NewEmptyResultError(input) } - return &apiObject, diags + return output.LifecyclePolicy, nil } -func expandPolicyDetailExclusionRulesAMIS(ctx context.Context, tfList []resourceAMISData) (*awstypes.LifecyclePolicyDetailExclusionRulesAmis, diag.Diagnostics) { - var diags diag.Diagnostics - - if len(tfList) == 0 { - return nil, diags - } - - tfObj := tfList[0] - - apiObject := awstypes.LifecyclePolicyDetailExclusionRulesAmis{} - - if !tfObj.IsPublic.IsNull() { - apiObject.IsPublic = aws.ToBool(tfObj.IsPublic.ValueBoolPointer()) - } - - if !tfObj.LastLaunched.IsNull() { - var tfList []resourceLastLaunchedData - diags.Append(tfObj.LastLaunched.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags - } - - apiObject.LastLaunched = expandPolicyDetailExclusionRulesAMISLastLaunched(tfList) - } - - if !tfObj.Regions.IsNull() { - apiObject.Regions = flex.ExpandFrameworkStringValueList(ctx, tfObj.Regions) - } - - if !tfObj.SharedAccounts.IsNull() { - apiObject.SharedAccounts = flex.ExpandFrameworkStringValueList(ctx, tfObj.SharedAccounts) - } - - if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) - } - - return &apiObject, diags +type lifecyclePolicyResourceModel struct { + Description types.String `tfsdk:"description"` + ExecutionRole fwtypes.ARN `tfsdk:"execution_role"` + ID types.String `tfsdk:"id"` + LifecyclePolicyARN types.String `tfsdk:"arn"` + Name types.String `tfsdk:"name"` + PolicyDetails fwtypes.SetNestedObjectValueOf[lifecyclePolicyDetailModel] `tfsdk:"policy_detail"` + ResourceSelection fwtypes.ListNestedObjectValueOf[lifecyclePolicyResourceSelectionModel] `tfsdk:"resource_selection"` + ResourceType fwtypes.StringEnum[awstypes.LifecyclePolicyResourceType] `tfsdk:"resource_type"` + Status fwtypes.StringEnum[awstypes.LifecyclePolicyStatus] `tfsdk:"status"` + Tags types.Map `tfsdk:"tags"` + TagsAll types.Map `tfsdk:"tags_all"` } -func expandPolicyDetailExclusionRulesAMISLastLaunched(tfList []resourceLastLaunchedData) *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched { - tfObj := tfList[0] - - apiObject := awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched{} +func (model *lifecyclePolicyResourceModel) InitFromID() error { + model.LifecyclePolicyARN = model.ID - if !tfObj.Unit.IsNull() { - apiObject.Unit = awstypes.LifecyclePolicyTimeUnit(tfObj.Unit.ValueString()) - } - - if !tfObj.Value.IsNull() { - apiObject.Value = aws.Int32(int32(tfObj.Value.ValueInt64())) - } - - return &apiObject + return nil } -func expandResourceSelection(ctx context.Context, tfList []resourceResourceSelectionData) (*awstypes.LifecyclePolicyResourceSelection, diag.Diagnostics) { - var diags diag.Diagnostics - - if len(tfList) == 0 { - return nil, diags - } - - tfObj := tfList[0] - - apiObject := awstypes.LifecyclePolicyResourceSelection{} - - if !tfObj.Recipes.IsNull() { - var tfList []resourceRecipesData - diags.Append(tfObj.Recipes.ElementsAs(ctx, &tfList, false)...) - if diags.HasError() { - return nil, diags - } - - apiObject.Recipes = expandResourceSelectionRecipes(tfList) - } - - if !tfObj.TagMap.IsNull() { - apiObject.TagMap = flex.ExpandFrameworkStringValueMap(ctx, tfObj.TagMap) - } - - return &apiObject, diags +func (model *lifecyclePolicyResourceModel) setID() { + model.ID = model.LifecyclePolicyARN } -func expandResourceSelectionRecipes(tfList []resourceRecipesData) []awstypes.LifecyclePolicyResourceSelectionRecipe { - apiResult := []awstypes.LifecyclePolicyResourceSelectionRecipe{} - - for _, tfObj := range tfList { - apiObject := awstypes.LifecyclePolicyResourceSelectionRecipe{} - - if !tfObj.Name.IsNull() { - apiObject.Name = aws.String(tfObj.Name.ValueString()) - } - if !tfObj.SemanticVersion.IsNull() { - apiObject.SemanticVersion = aws.String(tfObj.SemanticVersion.ValueString()) - } - - apiResult = append(apiResult, apiObject) - } - return apiResult -} - -func flattenPolicyDetails(ctx context.Context, apiObject []awstypes.LifecyclePolicyDetail) (types.Set, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourcePolicyDetailAttrTypes} - - if apiObject == nil { - return types.SetNull(elemType), diags - } - - result := []attr.Value{} - - for _, policyDetail := range apiObject { - action, d := flattenDetailAction(ctx, policyDetail.Action) - diags.Append(d...) - - filter, d := flattenDetailFilter(ctx, policyDetail.Filter) - diags.Append(d...) - - exclusionRules, d := flattenDetailExclusionRules(ctx, policyDetail.ExclusionRules) - diags.Append(d...) - - obj := map[string]attr.Value{ - names.AttrAction: action, - names.AttrFilter: filter, - "exclusion_rules": exclusionRules, - } - - objVal, d := types.ObjectValue(resourcePolicyDetailAttrTypes, obj) - diags.Append(d...) - - result = append(result, objVal) - } - - setVal, d := types.SetValue(elemType, result) - diags.Append(d...) - - return setVal, diags +type lifecyclePolicyDetailModel struct { + Action fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionModel] `tfsdk:"action"` + ExclusionRules fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesModel] `tfsdk:"exclusion_rules"` + Filter fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailFilterModel] `tfsdk:"filter"` } -func flattenDetailAction(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailAction) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceActionAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - includeResources, d := flattenIncludeResources(ctx, apiObject.IncludeResources) - diags.Append(d...) - - obj := map[string]attr.Value{ - "include_resources": includeResources, - names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), - } - - objVal, d := types.ObjectValue(resourceActionAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags +type lifecyclePolicyDetailActionModel struct { + IncludeResources fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionIncludeResourcesModel] `tfsdk:"include_resources"` + Type fwtypes.StringEnum[awstypes.LifecyclePolicyDetailActionType] `tfsdk:"type"` } -func flattenIncludeResources(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailActionIncludeResources) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceIncludeResourcesAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - obj := map[string]attr.Value{ - "amis": flex.BoolToFramework(ctx, aws.Bool(apiObject.Amis)), - "containers": flex.BoolToFramework(ctx, aws.Bool(apiObject.Containers)), - "snapshots": flex.BoolToFramework(ctx, aws.Bool(apiObject.Snapshots)), - } - - objVal, d := types.ObjectValue(resourceIncludeResourcesAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags -} - -func flattenDetailFilter(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailFilter) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceFilterAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - obj := map[string]attr.Value{ - names.AttrType: flex.StringValueToFramework(ctx, apiObject.Type), - names.AttrValue: flex.Int32ToFramework(ctx, apiObject.Value), - "retain_at_least": flex.Int32ToFramework(ctx, apiObject.RetainAtLeast), - names.AttrUnit: flex.StringValueToFramework(ctx, apiObject.Unit), - } - - objVal, d := types.ObjectValue(resourceFilterAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags -} - -func flattenDetailExclusionRules(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRules) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceExclusionRulesAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - amis, d := flattenExclusionRulesAMIS(ctx, apiObject.Amis) - diags.Append(d...) - - obj := map[string]attr.Value{ - "amis": amis, - "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), - } - - objVal, d := types.ObjectValue(resourceExclusionRulesAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags -} - -func flattenExclusionRulesAMIS(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmis) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceAMISAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - lastLaunched, d := flattenExclusionRulesAMISLastLaunched(ctx, apiObject.LastLaunched) - diags.Append(d...) - - obj := map[string]attr.Value{ - "is_public": flex.BoolToFramework(ctx, aws.Bool(apiObject.IsPublic)), - "regions": flex.FlattenFrameworkStringValueList(ctx, apiObject.Regions), - "shared_accounts": flex.FlattenFrameworkStringValueList(ctx, apiObject.SharedAccounts), - "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), - "last_launched": lastLaunched, - } - - objVal, d := types.ObjectValue(resourceAMISAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags -} - -func flattenExclusionRulesAMISLastLaunched(ctx context.Context, apiObject *awstypes.LifecyclePolicyDetailExclusionRulesAmisLastLaunched) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceLastLaunchedAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - obj := map[string]attr.Value{ - names.AttrUnit: flex.StringValueToFramework(ctx, apiObject.Unit), - names.AttrValue: flex.Int32ToFramework(ctx, apiObject.Value), - } - - objVal, d := types.ObjectValue(resourceLastLaunchedAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags -} - -func flattenResourceSelection(ctx context.Context, apiObject *awstypes.LifecyclePolicyResourceSelection) (types.List, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceResourceSelectionAttrTypes} - - if apiObject == nil { - return types.ListNull(elemType), diags - } - - recipes, d := flattenResourceSelectionRecipes(ctx, apiObject.Recipes) - diags.Append(d...) - - obj := map[string]attr.Value{ - "recipes": recipes, - "tag_map": flex.FlattenFrameworkStringValueMap(ctx, apiObject.TagMap), - } - - objVal, d := types.ObjectValue(resourceResourceSelectionAttrTypes, obj) - diags.Append(d...) - - listVal, d := types.ListValue(elemType, []attr.Value{objVal}) - diags.Append(d...) - - return listVal, diags -} - -func flattenResourceSelectionRecipes(ctx context.Context, apiObject []awstypes.LifecyclePolicyResourceSelectionRecipe) (types.Set, diag.Diagnostics) { - var diags diag.Diagnostics - elemType := types.ObjectType{AttrTypes: resourceRecipeAttrTypes} - - if apiObject == nil { - return types.SetNull(elemType), diags - } - - result := []attr.Value{} - - for _, recipe := range apiObject { - obj := map[string]attr.Value{ - names.AttrName: flex.StringToFramework(ctx, recipe.Name), - "semantic_version": flex.StringToFramework(ctx, recipe.SemanticVersion), - } - - objVal, d := types.ObjectValue(resourceRecipeAttrTypes, obj) - diags.Append(d...) - - result = append(result, objVal) - } - - setVal, d := types.SetValue(elemType, result) - diags.Append(d...) - - return setVal, diags -} - -type resourceLifecyclePolicyData struct { - ID types.String `tfsdk:"id"` - ARN types.String `tfsdk:"arn"` - Description types.String `tfsdk:"description"` - Name types.String `tfsdk:"name"` - ExecutionRole types.String `tfsdk:"execution_role"` - ResourceType types.String `tfsdk:"resource_type"` - Status types.String `tfsdk:"status"` - PolicyDetails types.Set `tfsdk:"policy_details"` - ResourceSelection types.List `tfsdk:"resource_selection"` - Tags types.Map `tfsdk:"tags"` - TagsAll types.Map `tfsdk:"tags_all"` -} - -type resourcePolicyDetailsData struct { - Action types.List `tfsdk:"action"` - Filter types.List `tfsdk:"filter"` - ExclusionRules types.List `tfsdk:"exclusion_rules"` -} - -type resourceResourceSelectionData struct { - TagMap types.Map `tfsdk:"tag_map"` - Recipes types.Set `tfsdk:"recipes"` -} - -type resourceRecipesData struct { - Name types.String `tfsdk:"name"` - SemanticVersion types.String `tfsdk:"semantic_version"` -} - -type resourceActionData struct { - Type types.String `tfsdk:"type"` - IncludeResources types.List `tfsdk:"include_resources"` -} - -type resourceIncludeResourcesData struct { - Amis types.Bool `tfsdk:"amis"` +type lifecyclePolicyDetailActionIncludeResourcesModel struct { + AMIs types.Bool `tfsdk:"amis"` Containers types.Bool `tfsdk:"containers"` Snapshots types.Bool `tfsdk:"snapshots"` } -type resourceFilterData struct { - Type types.String `tfsdk:"type"` - Value types.Int64 `tfsdk:"value"` - RetainAtLeast types.Int64 `tfsdk:"retain_at_least"` - Unit types.String `tfsdk:"unit"` -} - -type resourceExclusionRulesData struct { - AMIs types.List `tfsdk:"amis"` - TagMap types.Map `tfsdk:"tag_map"` +type lifecyclePolicyDetailExclusionRulesModel struct { + AMIs fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesAMIsModel] `tfsdk:"amis"` + TagMap fwtypes.MapValueOf[types.String] `tfsdk:"tag_map"` } -type resourceAMISData struct { - IsPublic types.Bool `tfsdk:"is_public"` - LastLaunched types.List `tfsdk:"last_launched"` - Regions types.List `tfsdk:"regions"` - SharedAccounts types.List `tfsdk:"shared_accounts"` - TagMap types.Map `tfsdk:"tag_map"` +type lifecyclePolicyDetailExclusionRulesAMIsModel struct { + IsPublic types.Bool `tfsdk:"is_public"` + LastLaunched fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesAmisLastLaunchedModel] `tfsdk:"last_launched"` + Regions fwtypes.ListValueOf[types.String] `tfsdk:"regions"` + SharedAccounts fwtypes.ListValueOf[types.String] `tfsdk:"shared_accounts"` + TagMap fwtypes.MapValueOf[types.String] `tfsdk:"tag_map"` } -type resourceLastLaunchedData struct { - Unit types.String `tfsdk:"unit"` - Value types.Int64 `tfsdk:"value"` +type lifecyclePolicyDetailExclusionRulesAmisLastLaunchedModel struct { + Unit fwtypes.StringEnum[awstypes.LifecyclePolicyTimeUnit] `tfsdk:"unit"` + Value types.Int64 `tfsdk:"value"` } -var resourcePolicyDetailAttrTypes = map[string]attr.Type{ - names.AttrAction: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceActionAttrTypes}}, - names.AttrFilter: types.ListType{ElemType: types.ObjectType{AttrTypes: resourceFilterAttrTypes}}, - "exclusion_rules": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceExclusionRulesAttrTypes}}, +type lifecyclePolicyDetailFilterModel struct { + RetainAtLeast types.Int64 `tfsdk:"retain_at_least"` + Type fwtypes.StringEnum[awstypes.LifecyclePolicyDetailFilterType] `tfsdk:"type"` + Unit fwtypes.StringEnum[awstypes.LifecyclePolicyTimeUnit] `tfsdk:"unit"` + Value types.Int64 `tfsdk:"value"` } -var resourceActionAttrTypes = map[string]attr.Type{ - names.AttrType: types.StringType, - "include_resources": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceIncludeResourcesAttrTypes}}, +type lifecyclePolicyResourceSelectionModel struct { + Recipes fwtypes.SetNestedObjectValueOf[lifecyclePolicyResourceSelectionRecipeModel] `tfsdk:"recipe"` + TagMap fwtypes.MapValueOf[types.String] `tfsdk:"tag_map"` } -var resourceIncludeResourcesAttrTypes = map[string]attr.Type{ - "amis": types.BoolType, - "containers": types.BoolType, - "snapshots": types.BoolType, -} - -var resourceFilterAttrTypes = map[string]attr.Type{ - names.AttrType: types.StringType, - names.AttrValue: types.Int64Type, - "retain_at_least": types.Int64Type, - names.AttrUnit: types.StringType, -} - -var resourceExclusionRulesAttrTypes = map[string]attr.Type{ - "amis": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceAMISAttrTypes}}, - "tag_map": types.MapType{ElemType: types.StringType}, -} - -var resourceAMISAttrTypes = map[string]attr.Type{ - "is_public": types.BoolType, - "last_launched": types.ListType{ElemType: types.ObjectType{AttrTypes: resourceLastLaunchedAttrTypes}}, - "regions": types.ListType{ElemType: types.StringType}, - "shared_accounts": types.ListType{ElemType: types.StringType}, - "tag_map": types.MapType{ElemType: types.StringType}, -} - -var resourceLastLaunchedAttrTypes = map[string]attr.Type{ - names.AttrUnit: types.StringType, - names.AttrValue: types.Int64Type, -} - -var resourceResourceSelectionAttrTypes = map[string]attr.Type{ - "recipes": types.SetType{ElemType: types.ObjectType{AttrTypes: resourceRecipeAttrTypes}}, - "tag_map": types.MapType{ElemType: types.StringType}, -} - -var resourceRecipeAttrTypes = map[string]attr.Type{ - names.AttrName: types.StringType, - "semantic_version": types.StringType, +type lifecyclePolicyResourceSelectionRecipeModel struct { + Name types.String `tfsdk:"name"` + SemanticVersion types.String `tfsdk:"semantic_version"` } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 7aa051bf6ee..edaadad1d9f 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -5,7 +5,6 @@ package imagebuilder_test import ( "context" - "errors" "fmt" "testing" @@ -15,7 +14,6 @@ import ( "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/create" tfimagebuilder "github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" @@ -241,24 +239,18 @@ func TestAccImageBuilderLifecyclePolicy_disappears(t *testing.T) { }) } -func testAccCheckLifecyclePolicyExists(ctx context.Context, name string) resource.TestCheckFunc { +func testAccCheckLifecyclePolicyExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] + rs, ok := s.RootModule().Resources[n] if !ok { - return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, name, errors.New("not found")) - } - - if rs.Primary.ID == "" { - return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, name, errors.New("not set")) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).ImageBuilderClient(ctx) + _, err := tfimagebuilder.FindLifecyclePolicyByARN(ctx, conn, rs.Primary.ID) - if err != nil { - return create.Error(names.ImageBuilder, create.ErrActionCheckingExistence, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, err) - } - return nil + return err } } @@ -272,14 +264,16 @@ func testAccCheckLifecyclePolicyDestroy(ctx context.Context) resource.TestCheckF } _, err := tfimagebuilder.FindLifecyclePolicyByARN(ctx, conn, rs.Primary.ID) + if tfresource.NotFound(err) { - return nil + continue } + if err != nil { - return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, err) + return err } - return create.Error(names.ImageBuilder, create.ErrActionCheckingDestroyed, tfimagebuilder.ResNameLifecyclePolicy, rs.Primary.ID, errors.New("not destroyed")) + return fmt.Errorf("Image Builder Lifecycle Policy %s still exists", rs.Primary.ID) } return nil diff --git a/internal/service/imagebuilder/service_package_gen.go b/internal/service/imagebuilder/service_package_gen.go index 7c771f32669..769cc57c474 100644 --- a/internal/service/imagebuilder/service_package_gen.go +++ b/internal/service/imagebuilder/service_package_gen.go @@ -21,7 +21,7 @@ func (p *servicePackage) FrameworkDataSources(ctx context.Context) []*types.Serv func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.ServicePackageFrameworkResource { return []*types.ServicePackageFrameworkResource{ { - Factory: newResourceLifecyclePolicy, + Factory: newLifecyclePolicyResource, Name: "Lifecycle Policy", Tags: &types.ServicePackageResourceTags{ IdentifierAttribute: names.AttrID, diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index 89d3685950d..77fc313215e 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -383,7 +383,7 @@ func sweepLifecyclePolicies(region string) error { } for _, v := range page.LifecyclePolicySummaryList { - sweepResources = append(sweepResources, framework.NewSweepResource(newResourceLifecyclePolicy, client, framework.NewAttribute(names.AttrARN, v.Arn))) + sweepResources = append(sweepResources, framework.NewSweepResource(newLifecyclePolicyResource, client, framework.NewAttribute(names.AttrARN, v.Arn))) } } diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index d24c712ff66..fd3e3392dff 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -41,7 +41,7 @@ resource "aws_imagebuilder_lifecycle_policy" "example" { description = "Example description" execution_role = aws_iam_role.example.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" } @@ -69,8 +69,8 @@ The following arguments are required: * `name` - (Required) The name of the lifecycle policy to create. * `resource_type` - (Required) The type of Image Builder resource that the lifecycle policy applies to. Valid values: `AMI_IMAGE` or `CONTAINER_IMAGE`. -* `execution_role` - (Required) The name or Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. More information about this role can be found [`here`](https://docs.aws.amazon.com/imagebuilder/latest/userguide/image-lifecycle-prerequisites.html#image-lifecycle-prereq-role). -* `policy_details` - (Required) Configuration block with policy details. Detailed below. +* `execution_role` - (Required) The Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. More information about this role can be found [`here`](https://docs.aws.amazon.com/imagebuilder/latest/userguide/image-lifecycle-prerequisites.html#image-lifecycle-prereq-role). +* `policy_detail` - (Required) Configuration block with policy details. Detailed below. * `resource_selection` - (Required) Selection criteria for the resources that the lifecycle policy applies to. Detailed below. The following arguments are optional: @@ -78,7 +78,7 @@ The following arguments are optional: * `description` - (Optional) description for the lifecycle policy. * `tags` - (Optional) Key-value map of resource tags for the Image Builder Lifecycle Policy. If configured with a provider [`default_tags` configuration block](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. -### policy_details +### policy_detail The following arguments are required: @@ -147,10 +147,10 @@ The following arguments are required: The following arguments are optional: -* `recipes` - (Optional) A list of recipes that are used as selection criteria for the output images that the lifecycle policy applies to. Detailed below. +* `recipe` - (Optional) A list of recipes that are used as selection criteria for the output images that the lifecycle policy applies to. Detailed below. * `tag_map` - (Optional) A list of tags that are used as selection criteria for the Image Builder image resources that the lifecycle policy applies to. -### recipes +### recipe The following arguments are required: From 942ab4f554eafd453dddb7263c2b11ab1746d12b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:25:03 -0400 Subject: [PATCH 090/112] imagebuilder: Tidy up sweepers. --- internal/service/imagebuilder/sweep.go | 71 +++++++++++--------------- 1 file changed, 30 insertions(+), 41 deletions(-) diff --git a/internal/service/imagebuilder/sweep.go b/internal/service/imagebuilder/sweep.go index 77fc313215e..2c3ac2906db 100644 --- a/internal/service/imagebuilder/sweep.go +++ b/internal/service/imagebuilder/sweep.go @@ -66,11 +66,9 @@ func sweepComponents(region string) error { return fmt.Errorf("error getting client: %s", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListComponentsInput{ Owner: types.OwnershipSelf, } - sweepResources := make([]sweep.Sweepable, 0) pages := imagebuilder.NewListComponentsPaginator(conn, input) @@ -78,12 +76,12 @@ func sweepComponents(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Components sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Component sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Components (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Components (%s): %w", region, err) } for _, v := range page.ComponentVersionList { @@ -98,7 +96,7 @@ func sweepComponents(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Components (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Components (%s): %w", region, err) } return nil @@ -111,7 +109,6 @@ func sweepDistributionConfigurations(region string) error { return fmt.Errorf("error getting client: %s", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListDistributionConfigurationsInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -120,16 +117,16 @@ func sweepDistributionConfigurations(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Distribution Configuration Summary sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Distribution Configuration sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Distribution Configuration Summary (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Distribution Configurations (%s): %w", region, err) } for _, v := range page.DistributionConfigurationSummaryList { - r := ResourceDistributionConfiguration() + r := resourceDistributionConfiguration() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) @@ -140,7 +137,7 @@ func sweepDistributionConfigurations(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Distribution Configuration Summary (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Distribution Configuration Summary (%s): %w", region, err) } return nil @@ -153,7 +150,6 @@ func sweepImagePipelines(region string) error { return fmt.Errorf("error getting client: %w", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListImagePipelinesInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -162,16 +158,16 @@ func sweepImagePipelines(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Image Pipelines sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Image Pipeline sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Image Pipelines (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Image Pipelines (%s): %w", region, err) } for _, v := range page.ImagePipelineList { - r := ResourceImagePipeline() + r := resourceImagePipeline() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) @@ -182,7 +178,7 @@ func sweepImagePipelines(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Image Pipelines (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Image Pipelines (%s): %w", region, err) } return nil @@ -195,7 +191,6 @@ func sweepImageRecipes(region string) error { return fmt.Errorf("error getting client: %w", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListImageRecipesInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -204,16 +199,16 @@ func sweepImageRecipes(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Image Recipes sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Image Recipe sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Image Recipes (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Image Recipes (%s): %w", region, err) } for _, v := range page.ImageRecipeSummaryList { - r := ResourceImageRecipe() + r := resourceImageRecipe() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) @@ -224,7 +219,7 @@ func sweepImageRecipes(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Image Recipes (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Image Recipes (%s): %w", region, err) } return nil @@ -237,7 +232,6 @@ func sweepContainerRecipes(region string) error { return fmt.Errorf("error getting client: %w", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListContainerRecipesInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -246,16 +240,16 @@ func sweepContainerRecipes(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Container Recipes sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Container Recipe sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Container Recipes (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Container Recipes (%s): %w", region, err) } for _, v := range page.ContainerRecipeSummaryList { - r := ResourceContainerRecipe() + r := resourceContainerRecipe() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) @@ -266,7 +260,7 @@ func sweepContainerRecipes(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Container Recipes (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Container Recipes (%s): %w", region, err) } return nil @@ -275,13 +269,10 @@ func sweepContainerRecipes(region string) error { func sweepImages(region string) error { ctx := sweep.Context(region) client, err := sweep.SharedRegionalSweepClient(ctx, region) - if err != nil { return fmt.Errorf("error getting client: %w", err) } - conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListImagesInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -290,16 +281,16 @@ func sweepImages(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Images sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Image sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Images (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Images (%s): %w", region, err) } for _, v := range page.ImageVersionList { - r := ResourceImage() + r := resourceImage() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) @@ -310,7 +301,7 @@ func sweepImages(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Images (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Images (%s): %w", region, err) } return nil @@ -323,7 +314,6 @@ func sweepInfrastructureConfigurations(region string) error { return fmt.Errorf("error getting client: %s", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListInfrastructureConfigurationsInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -332,16 +322,16 @@ func sweepInfrastructureConfigurations(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Infrastructure Configurations sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Infrastructure Configuration sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Infrastructure Configurations (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Infrastructure Configurations (%s): %w", region, err) } for _, v := range page.InfrastructureConfigurationSummaryList { - r := ResourceInfrastructureConfiguration() + r := resourceInfrastructureConfiguration() d := r.Data(nil) d.SetId(aws.ToString(v.Arn)) @@ -352,7 +342,7 @@ func sweepInfrastructureConfigurations(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Infrastructure Configurations (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Infrastructure Configurations (%s): %w", region, err) } return nil @@ -365,7 +355,6 @@ func sweepLifecyclePolicies(region string) error { return fmt.Errorf("error getting client: %s", err) } conn := client.ImageBuilderClient(ctx) - input := &imagebuilder.ListLifecyclePoliciesInput{} sweepResources := make([]sweep.Sweepable, 0) @@ -374,12 +363,12 @@ func sweepLifecyclePolicies(region string) error { page, err := pages.NextPage(ctx) if awsv2.SkipSweepError(err) { - log.Printf("[WARN] Skipping ImageBuilder Lifecycle Policies sweep for %s: %s", region, err) + log.Printf("[WARN] Skipping Image Builder Lifecycle Policy sweep for %s: %s", region, err) return nil } if err != nil { - return fmt.Errorf("error listing ImageBuilder Lifecycle Policies (%s): %w", region, err) + return fmt.Errorf("error listing Image Builder Lifecycle Policies (%s): %w", region, err) } for _, v := range page.LifecyclePolicySummaryList { @@ -390,7 +379,7 @@ func sweepLifecyclePolicies(region string) error { err = sweep.SweepOrchestrator(ctx, sweepResources) if err != nil { - return fmt.Errorf("error sweeping ImageBuilder Lifecycle Policies (%s): %w", region, err) + return fmt.Errorf("error sweeping Image Builder Lifecycle Policies (%s): %w", region, err) } return nil From efe4fea1f8202781b17681e0b1270954bf04416b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:28:54 -0400 Subject: [PATCH 091/112] Add CHANGELOG entry. --- .changelog/35674.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .changelog/35674.txt diff --git a/.changelog/35674.txt b/.changelog/35674.txt new file mode 100644 index 00000000000..586f7a26d97 --- /dev/null +++ b/.changelog/35674.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +aws_imagebuilder_lifecycle_policy +``` \ No newline at end of file From e261457254056469a1c1937f98543391c32f1f9d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:31:39 -0400 Subject: [PATCH 092/112] r/aws_imagebuilder_lifecycle_policy: 'policy_details' -> 'policy_detail'. --- .../imagebuilder/lifecycle_policy_test.go | 104 +++++++++--------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index edaadad1d9f..12b1d62302b 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -38,14 +38,14 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, names.AttrDescription, "Used for setting lifecycle policies"), resource.TestCheckResourceAttrSet(resourceName, "execution_role"), resource.TestCheckResourceAttr(resourceName, names.AttrName, rName), - resource.TestCheckResourceAttr(resourceName, "policy_details.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", acctest.Ct10), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", "6"), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.retain_at_least", acctest.Ct10), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.%", acctest.Ct2), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.tag_map.key1", acctest.CtValue1), @@ -77,24 +77,24 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { Config: testAccLifecyclePolicyConfig_policyDetails(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "policy_details.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", "6"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.retain_at_least", "5"), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", "6"), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.retain_at_least", "5"), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.unit", string(awstypes.LifecyclePolicyTimeUnitYears)), ), }, { @@ -106,25 +106,25 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName), Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), - resource.TestCheckResourceAttr(resourceName, "policy_details.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.amis", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.action.0.include_resources.0.snapshots", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.regions.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.last_launched.0.value", acctest.Ct2), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct2), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.exclusion_rules.0.amis.0.tag_map.key2", acctest.CtValue2), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeCount)), - resource.TestCheckResourceAttr(resourceName, "policy_details.0.filter.0.value", acctest.Ct10), + resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.snapshots", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.regions.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.value", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key2", acctest.CtValue2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeCount)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", acctest.Ct10), ), }, }, @@ -340,7 +340,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { description = "Used for setting lifecycle policies" execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" } @@ -372,7 +372,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { description = "Used for setting lifecycle policies" execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DISABLE" include_resources { @@ -419,7 +419,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { description = "Used for setting lifecycle policies" execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" include_resources { @@ -478,7 +478,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { description = "Used for setting lifecycle policies" execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" } @@ -521,7 +521,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { description = "Used for setting lifecycle policies" execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" } @@ -552,7 +552,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" } @@ -585,7 +585,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn resource_type = "AMI_IMAGE" - policy_details { + policy_detail { action { type = "DELETE" } From a5ea69b77cf4f5d8d494f0ab3749c78b5f1f5b4d Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:33:20 -0400 Subject: [PATCH 093/112] r/aws_imagebuilder_lifecycle_policy: 'include_resources' -> 'include_resource'. --- internal/service/imagebuilder/lifecycle_policy.go | 4 ++-- .../service/imagebuilder/lifecycle_policy_test.go | 14 +++++++------- .../r/imagebuilder_lifecycle_policy.html.markdown | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index f364546bc1e..9e67d49a3df 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -107,7 +107,7 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S }, }, Blocks: map[string]schema.Block{ - "include_resources": schema.ListNestedBlock{ + "include_resource": schema.ListNestedBlock{ CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailActionIncludeResourcesModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), @@ -479,7 +479,7 @@ type lifecyclePolicyDetailModel struct { } type lifecyclePolicyDetailActionModel struct { - IncludeResources fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionIncludeResourcesModel] `tfsdk:"include_resources"` + IncludeResources fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionIncludeResourcesModel] `tfsdk:"include_resource"` Type fwtypes.StringEnum[awstypes.LifecyclePolicyDetailActionType] `tfsdk:"type"` } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 12b1d62302b..02134ef8cac 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -80,8 +80,8 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), @@ -109,9 +109,9 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.amis", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.snapshots", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.snapshots", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), @@ -375,7 +375,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { policy_detail { action { type = "DISABLE" - include_resources { + include_resource { amis = true } } @@ -422,7 +422,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { policy_detail { action { type = "DELETE" - include_resources { + include_resource { amis = true snapshots = true } diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index fd3e3392dff..b5939776aeb 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -97,9 +97,9 @@ The following arguments are required: The following arguments are optional: -* `include_resources` - (Optional) Specifies the resources that the lifecycle policy applies to. Detailed below. +* `include_resource` - (Optional) Specifies the resources that the lifecycle policy applies to. Detailed below. -### include_resources +### include_resource The following arguments are optional: From 054886916024784b3c40b6e983eaa76a0bc6ba51 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:34:26 -0400 Subject: [PATCH 094/112] r/aws_imagebuilder_lifecycle_policy: 'exclusion_rules' -> 'exclusion_rule'. --- .../service/imagebuilder/lifecycle_policy.go | 4 +- .../imagebuilder/lifecycle_policy_test.go | 40 +++++++++---------- ...magebuilder_lifecycle_policy.html.markdown | 4 +- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 9e67d49a3df..47904dc3617 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -138,7 +138,7 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S }, }, }, - "exclusion_rules": schema.ListNestedBlock{ + "exclusion_rule": schema.ListNestedBlock{ CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailExclusionRulesModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), @@ -474,7 +474,7 @@ func (model *lifecyclePolicyResourceModel) setID() { type lifecyclePolicyDetailModel struct { Action fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionModel] `tfsdk:"action"` - ExclusionRules fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesModel] `tfsdk:"exclusion_rules"` + ExclusionRules fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesModel] `tfsdk:"exclusion_rule"` Filter fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailFilterModel] `tfsdk:"filter"` } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 02134ef8cac..ca5a5d77055 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -82,14 +82,14 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.is_public", acctest.CtFalse), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.value", "7"), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.%", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.key1", acctest.CtValue1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", "6"), @@ -112,16 +112,16 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.snapshots", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.regions.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.value", acctest.Ct2), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct2), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key2", acctest.CtValue2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.is_public", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.regions.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.value", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.%", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.key2", acctest.CtValue2), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeCount)), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", acctest.Ct10), @@ -379,7 +379,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { amis = true } } - exclusion_rules { + exclusion_rule { amis { is_public = false last_launched { @@ -427,7 +427,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { snapshots = true } } - exclusion_rules { + exclusion_rule { amis { is_public = true regions = ["${data.aws_region.current.name}"] diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index b5939776aeb..acae7f4f15d 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -87,7 +87,7 @@ The following arguments are required: The following arguments are optional: -* `exclusion_rules` - (Optional) Additional rules to specify resources that should be exempt from policy actions. +* `exclusion_rule` - (Optional) Additional rules to specify resources that should be exempt from policy actions. ### action @@ -119,7 +119,7 @@ The following arguments are optional: * `retain_at_least` - (Optional) For age-based filters, this is the number of resources to keep on hand after the lifecycle DELETE action is applied. Impacted resources are only deleted if you have more than this number of resources. If you have fewer resources than this number, the impacted resource is not deleted. * `unit` - (Optional) Defines the unit of time that the lifecycle policy uses to determine impacted resources. This is required for age-based rules. Valid values: `DAYS`, `WEEKS`, `MONTHS` or `YEARS`. -### exclusion_rules +### exclusion_rule The following arguments are optional: From 720c1bd65e4da7d467d97ba58841c760c8275a9a Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:35:26 -0400 Subject: [PATCH 095/112] r/aws_imagebuilder_lifecycle_policy: 'recipes' -> 'recipe'. --- .../imagebuilder/lifecycle_policy_test.go | 16 ++++++++-------- .../imagebuilder_lifecycle_policy.html.markdown | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index ca5a5d77055..1671a02b9ef 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -147,9 +147,9 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.name", rName), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.semantic_version", "1.0.0"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.0.name", rName), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.0.semantic_version", "1.0.0"), ), }, { @@ -162,9 +162,9 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.name", rName), - resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipes.0.semantic_version", "2.0.0"), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.0.name", rName), + resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.0.semantic_version", "2.0.0"), ), }, }, @@ -490,7 +490,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { } } resource_selection { - recipes { + recipe { name = aws_imagebuilder_image_recipe.test.name semantic_version = aws_imagebuilder_image_recipe.test.version } @@ -533,7 +533,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { } } resource_selection { - recipes { + recipe { name = aws_imagebuilder_image_recipe.test.name semantic_version = aws_imagebuilder_image_recipe.test.version } diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index acae7f4f15d..104dc413d38 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -147,7 +147,7 @@ The following arguments are required: The following arguments are optional: -* `recipe` - (Optional) A list of recipes that are used as selection criteria for the output images that the lifecycle policy applies to. Detailed below. +* `recipe` - (Optional) A list of recipe that are used as selection criteria for the output images that the lifecycle policy applies to. Detailed below. * `tag_map` - (Optional) A list of tags that are used as selection criteria for the Image Builder image resources that the lifecycle policy applies to. ### recipe From e86decfe8a0befe3bd587577e9163c940089cbb8 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:39:02 -0400 Subject: [PATCH 096/112] r/aws_imagebuilder_lifecycle_policy: 'exclusion_rule' -> 'exclusion_rules'. --- .../service/imagebuilder/lifecycle_policy.go | 4 +- .../imagebuilder/lifecycle_policy_test.go | 40 +++++++++---------- ...magebuilder_lifecycle_policy.html.markdown | 4 +- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 47904dc3617..9e67d49a3df 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -138,7 +138,7 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S }, }, }, - "exclusion_rule": schema.ListNestedBlock{ + "exclusion_rules": schema.ListNestedBlock{ CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailExclusionRulesModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), @@ -474,7 +474,7 @@ func (model *lifecyclePolicyResourceModel) setID() { type lifecyclePolicyDetailModel struct { Action fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionModel] `tfsdk:"action"` - ExclusionRules fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesModel] `tfsdk:"exclusion_rule"` + ExclusionRules fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailExclusionRulesModel] `tfsdk:"exclusion_rules"` Filter fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailFilterModel] `tfsdk:"filter"` } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 1671a02b9ef..5e779043f8e 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -82,14 +82,14 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.is_public", acctest.CtFalse), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.value", "7"), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.%", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitDays)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.value", "7"), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeAge)), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", "6"), @@ -112,16 +112,16 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.snapshots", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.is_public", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.regions.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.last_launched.0.value", acctest.Ct2), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.%", acctest.Ct2), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.key1", acctest.CtValue1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rule.0.amis.0.tag_map.key2", acctest.CtValue2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.regions.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.unit", string(awstypes.LifecyclePolicyTimeUnitWeeks)), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.last_launched.0.value", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.%", acctest.Ct2), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key1", acctest.CtValue1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.tag_map.key2", acctest.CtValue2), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.type", string(awstypes.LifecyclePolicyDetailFilterTypeCount)), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.filter.0.value", acctest.Ct10), @@ -379,7 +379,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { amis = true } } - exclusion_rule { + exclusion_rules { amis { is_public = false last_launched { @@ -427,7 +427,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { snapshots = true } } - exclusion_rule { + exclusion_rules { amis { is_public = true regions = ["${data.aws_region.current.name}"] diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index 104dc413d38..77626339db9 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -87,7 +87,7 @@ The following arguments are required: The following arguments are optional: -* `exclusion_rule` - (Optional) Additional rules to specify resources that should be exempt from policy actions. +* `exclusion_rules` - (Optional) Additional rules to specify resources that should be exempt from policy actions. ### action @@ -119,7 +119,7 @@ The following arguments are optional: * `retain_at_least` - (Optional) For age-based filters, this is the number of resources to keep on hand after the lifecycle DELETE action is applied. Impacted resources are only deleted if you have more than this number of resources. If you have fewer resources than this number, the impacted resource is not deleted. * `unit` - (Optional) Defines the unit of time that the lifecycle policy uses to determine impacted resources. This is required for age-based rules. Valid values: `DAYS`, `WEEKS`, `MONTHS` or `YEARS`. -### exclusion_rule +### exclusion_rules The following arguments are optional: From 0969e5a5fa4559447b811377b753e7208c20e1e2 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 16:39:42 -0400 Subject: [PATCH 097/112] r/aws_imagebuilder_lifecycle_policy: 'include_resource' -> 'include_resources'. --- internal/service/imagebuilder/lifecycle_policy.go | 4 ++-- .../service/imagebuilder/lifecycle_policy_test.go | 14 +++++++------- .../r/imagebuilder_lifecycle_policy.html.markdown | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 9e67d49a3df..f364546bc1e 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -107,7 +107,7 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S }, }, Blocks: map[string]schema.Block{ - "include_resource": schema.ListNestedBlock{ + "include_resources": schema.ListNestedBlock{ CustomType: fwtypes.NewListNestedObjectTypeOf[lifecyclePolicyDetailActionIncludeResourcesModel](ctx), Validators: []validator.List{ listvalidator.SizeAtMost(1), @@ -479,7 +479,7 @@ type lifecyclePolicyDetailModel struct { } type lifecyclePolicyDetailActionModel struct { - IncludeResources fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionIncludeResourcesModel] `tfsdk:"include_resource"` + IncludeResources fwtypes.ListNestedObjectValueOf[lifecyclePolicyDetailActionIncludeResourcesModel] `tfsdk:"include_resources"` Type fwtypes.StringEnum[awstypes.LifecyclePolicyDetailActionType] `tfsdk:"type"` } diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 5e779043f8e..23b59cc217a 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -80,8 +80,8 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDisable)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.amis", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtFalse), @@ -109,9 +109,9 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.type", string(awstypes.LifecyclePolicyDetailActionTypeDelete)), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.#", acctest.Ct1), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.amis", acctest.CtTrue), - resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resource.0.snapshots", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.#", acctest.Ct1), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.amis", acctest.CtTrue), + resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.0.include_resources.0.snapshots", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.exclusion_rules.0.amis.0.is_public", acctest.CtTrue), @@ -375,7 +375,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { policy_detail { action { type = "DISABLE" - include_resource { + include_resources { amis = true } } @@ -422,7 +422,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { policy_detail { action { type = "DELETE" - include_resource { + include_resources { amis = true snapshots = true } diff --git a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown index 77626339db9..9503d859344 100644 --- a/website/docs/r/imagebuilder_lifecycle_policy.html.markdown +++ b/website/docs/r/imagebuilder_lifecycle_policy.html.markdown @@ -97,9 +97,9 @@ The following arguments are required: The following arguments are optional: -* `include_resource` - (Optional) Specifies the resources that the lifecycle policy applies to. Detailed below. +* `include_resources` - (Optional) Specifies the resources that the lifecycle policy applies to. Detailed below. -### include_resource +### include_resources The following arguments are optional: From 8d7cfffe8b29811b2b56010bc592f1c829a1c849 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Mon, 5 Aug 2024 17:01:13 -0400 Subject: [PATCH 098/112] r/aws_imagebuilder_lifecycle_policy: Fixes after some testing. --- internal/service/imagebuilder/errors.go | 13 ++++++ .../service/imagebuilder/lifecycle_policy.go | 29 +++++++++---- .../imagebuilder/lifecycle_policy_test.go | 42 +++++++------------ 3 files changed, 50 insertions(+), 34 deletions(-) create mode 100644 internal/service/imagebuilder/errors.go diff --git a/internal/service/imagebuilder/errors.go b/internal/service/imagebuilder/errors.go new file mode 100644 index 00000000000..bed62e4db99 --- /dev/null +++ b/internal/service/imagebuilder/errors.go @@ -0,0 +1,13 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package imagebuilder + +import ( + awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" +) + +var ( + errCodeInvalidParameterValueException = (*awstypes.InvalidParameterValueException)(nil).ErrorCode() + errCodeResourceNotFoundException = (*awstypes.ResourceNotFoundException)(nil).ErrorCode() +) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index f364546bc1e..ecf8e83a313 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" "github.com/hashicorp/terraform-plugin-framework-validators/setvalidator" @@ -24,7 +25,6 @@ import ( "github.com/hashicorp/terraform-plugin-framework/types" sdkid "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/fwdiag" "github.com/hashicorp/terraform-provider-aws/internal/framework" fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" @@ -50,6 +50,8 @@ func (*lifecyclePolicyResource) Metadata(_ context.Context, request resource.Met } func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.SchemaRequest, response *resource.SchemaResponse) { + lifecyclePolicyStatusType := fwtypes.StringEnumType[awstypes.LifecyclePolicyStatus]() + response.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ names.AttrARN: framework.ARNAttributeComputedOnly(), @@ -78,8 +80,13 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S Required: true, }, names.AttrStatus: schema.StringAttribute{ - CustomType: fwtypes.StringEnumType[awstypes.LifecyclePolicyStatus](), + CustomType: lifecyclePolicyStatusType, Optional: true, + Computed: true, + Default: lifecyclePolicyStatusType.AttributeDefault(awstypes.LifecyclePolicyStatusEnabled), + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, }, names.AttrTags: tftags.TagsAttribute(), names.AttrTagsAll: tftags.TagsAttributeComputedOnly(), @@ -303,9 +310,9 @@ func (r *lifecyclePolicyResource) Create(ctx context.Context, request resource.C input.ClientToken = aws.String(sdkid.UniqueId()) input.Tags = getTagsIn(ctx) - outputRaw, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.InvalidParameterValueException](ctx, propagationTimeout, func() (interface{}, error) { + outputRaw, err := tfresource.RetryWhenAWSErrMessageContains(ctx, propagationTimeout, func() (interface{}, error) { return conn.CreateLifecyclePolicy(ctx, input) - }, "The provided role does not exist or does not have sufficient permissions") + }, errCodeInvalidParameterValueException, "The provided role does not exist or does not have sufficient permissions") if err != nil { response.Diagnostics.AddError(fmt.Sprintf("creating Image Builder Lifecycle Policy (%s)", name), err.Error()) @@ -329,6 +336,12 @@ func (r *lifecyclePolicyResource) Read(ctx context.Context, request resource.Rea return } + if err := data.InitFromID(); err != nil { + response.Diagnostics.AddError("parsing resource ID", err.Error()) + + return + } + conn := r.Meta().ImageBuilderClient(ctx) output, err := findLifecyclePolicyByARN(ctx, conn, data.ID.ValueString()) @@ -385,9 +398,9 @@ func (r *lifecyclePolicyResource) Update(ctx context.Context, request resource.U // Additional fields. input.ClientToken = aws.String(sdkid.UniqueId()) - _, err := tfresource.RetryWhenIsAErrorMessageContains[*awstypes.InvalidParameterValueException](ctx, propagationTimeout, func() (interface{}, error) { + _, err := tfresource.RetryWhenAWSErrMessageContains(ctx, propagationTimeout, func() (interface{}, error) { return conn.UpdateLifecyclePolicy(ctx, input) - }, "The provided role does not exist or does not have sufficient permissions") + }, errCodeInvalidParameterValueException, "The provided role does not exist or does not have sufficient permissions") if err != nil { response.Diagnostics.AddError(fmt.Sprintf("updating Image Builder Lifecycle Policy (%s)", new.ID.ValueString()), err.Error()) @@ -412,7 +425,7 @@ func (r *lifecyclePolicyResource) Delete(ctx context.Context, request resource.D LifecyclePolicyArn: aws.String(data.ID.ValueString()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return } @@ -434,7 +447,7 @@ func findLifecyclePolicyByARN(ctx context.Context, conn *imagebuilder.Client, ar output, err := conn.GetLifecyclePolicy(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 23b59cc217a..a5f1cb75f09 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -32,7 +32,7 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccLifecyclePolicyConfig_basic(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), acctest.CheckResourceAttrRegionalARN(resourceName, names.AttrARN, "imagebuilder", fmt.Sprintf("lifecycle-policy/%s", rName)), resource.TestCheckResourceAttr(resourceName, names.AttrDescription, "Used for setting lifecycle policies"), @@ -75,7 +75,7 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccLifecyclePolicyConfig_policyDetails(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), @@ -104,7 +104,7 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { }, { Config: testAccLifecyclePolicyConfig_policyDetailsUpdated(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "policy_detail.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "policy_detail.0.action.#", acctest.Ct1), @@ -144,7 +144,7 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccLifecyclePolicyConfig_resourceSelection(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.#", acctest.Ct1), @@ -159,7 +159,7 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { }, { Config: testAccLifecyclePolicyConfig_resourceSelectionUpdated(rName), - Check: resource.ComposeTestCheckFunc( + Check: resource.ComposeAggregateTestCheckFunc( testAccCheckLifecyclePolicyExists(ctx, resourceName), resource.TestCheckResourceAttr(resourceName, "resource_selection.#", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "resource_selection.0.recipe.#", acctest.Ct1), @@ -280,7 +280,7 @@ func testAccCheckLifecyclePolicyDestroy(ctx context.Context) resource.TestCheckF } } -func testAccLifecyclePolicyBaseConfig(rName string) string { +func testAccLifecyclePolicyConfig_base(rName string) string { return fmt.Sprintf(` data "aws_region" "current" {} @@ -307,7 +307,7 @@ resource "aws_iam_role_policy_attachment" "test" { `, rName) } -func testAccLifecyclePolicyBaseConfigComponent(rName string) string { +func testAccLifecyclePolicyConfig_baseComponent(rName string) string { return fmt.Sprintf(` resource "aws_imagebuilder_component" "test" { data = yamlencode({ @@ -332,9 +332,7 @@ resource "aws_imagebuilder_component" "test" { } func testAccLifecyclePolicyConfig_basic(rName string) string { - return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - fmt.Sprintf(` + return acctest.ConfigCompose(testAccLifecyclePolicyConfig_base(rName), fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q description = "Used for setting lifecycle policies" @@ -364,9 +362,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { } func testAccLifecyclePolicyConfig_policyDetails(rName string) string { - return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - fmt.Sprintf(` + return acctest.ConfigCompose(testAccLifecyclePolicyConfig_base(rName), fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q description = "Used for setting lifecycle policies" @@ -411,9 +407,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { } func testAccLifecyclePolicyConfig_policyDetailsUpdated(rName string) string { - return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - fmt.Sprintf(` + return acctest.ConfigCompose(testAccLifecyclePolicyConfig_base(rName), fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q description = "Used for setting lifecycle policies" @@ -460,8 +454,8 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { func testAccLifecyclePolicyConfig_resourceSelection(rName string) string { return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - testAccLifecyclePolicyBaseConfigComponent(rName), + testAccLifecyclePolicyConfig_base(rName), + testAccLifecyclePolicyConfig_baseComponent(rName), fmt.Sprintf(` resource "aws_imagebuilder_image_recipe" "test" { component { @@ -503,8 +497,8 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { func testAccLifecyclePolicyConfig_resourceSelectionUpdated(rName string) string { return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - testAccLifecyclePolicyBaseConfigComponent(rName), + testAccLifecyclePolicyConfig_base(rName), + testAccLifecyclePolicyConfig_baseComponent(rName), fmt.Sprintf(` resource "aws_imagebuilder_image_recipe" "test" { component { @@ -545,9 +539,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { } func testAccLifecyclePolicyConfig_tags1(rName string, tagKey1 string, tagValue1 string) string { - return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - fmt.Sprintf(` + return acctest.ConfigCompose(testAccLifecyclePolicyConfig_base(rName), fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn @@ -578,9 +570,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { } func testAccLifecyclePolicyConfig_tags2(rName string, tagKey1 string, tagValue1 string, tagKey2 string, tagValue2 string) string { - return acctest.ConfigCompose( - testAccLifecyclePolicyBaseConfig(rName), - fmt.Sprintf(` + return acctest.ConfigCompose(testAccLifecyclePolicyConfig_base(rName), fmt.Sprintf(` resource "aws_imagebuilder_lifecycle_policy" "test" { name = %[1]q execution_role = aws_iam_role.test.arn From 393322354aef7cfeffc9f19c12977882c8fc6dec Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 6 Aug 2024 09:17:25 -0400 Subject: [PATCH 099/112] r/aws_imagebuilder_lifecycle_policy: Use 'ParallelTest'. --- internal/service/imagebuilder/lifecycle_policy_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index a5f1cb75f09..9635ac26697 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -24,7 +24,7 @@ func TestAccImageBuilderLifecyclePolicy_basic(t *testing.T) { resourceName := "aws_imagebuilder_lifecycle_policy.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resource.Test(t, resource.TestCase{ + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, @@ -67,7 +67,7 @@ func TestAccImageBuilderLifecyclePolicy_policyDetails(t *testing.T) { resourceName := "aws_imagebuilder_lifecycle_policy.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resource.Test(t, resource.TestCase{ + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, @@ -136,7 +136,7 @@ func TestAccImageBuilderLifecyclePolicy_resourceSelection(t *testing.T) { resourceName := "aws_imagebuilder_lifecycle_policy.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) - resource.Test(t, resource.TestCase{ + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.ImageBuilderServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, From 2ee5141a84c70e96e7f6bfb3c0b7f00d0599bbac Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 6 Aug 2024 09:18:13 -0400 Subject: [PATCH 100/112] r/aws_imagebuilder_lifecycle_policy: 'policy_detail.action.include_resources' defaults. --- internal/service/imagebuilder/lifecycle_policy.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index ecf8e83a313..bb3fe46cac1 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -18,6 +18,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" @@ -123,18 +124,24 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S Attributes: map[string]schema.Attribute{ "amis": schema.BoolAttribute{ Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, }, "containers": schema.BoolAttribute{ Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, }, "snapshots": schema.BoolAttribute{ Optional: true, + Computed: true, + Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, From ce9651ad826d0a76907d78df40f901e9970402b7 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 6 Aug 2024 10:10:12 -0400 Subject: [PATCH 101/112] r/aws_imagebuilder_lifecycle_policy: Fixes after some more testing. --- .../service/imagebuilder/lifecycle_policy.go | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index bb3fe46cac1..9644778908c 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" "github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" @@ -125,7 +124,6 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S "amis": schema.BoolAttribute{ Optional: true, Computed: true, - Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, @@ -133,7 +131,6 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S "containers": schema.BoolAttribute{ Optional: true, Computed: true, - Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, @@ -141,7 +138,6 @@ func (r *lifecyclePolicyResource) Schema(ctx context.Context, request resource.S "snapshots": schema.BoolAttribute{ Optional: true, Computed: true, - Default: booldefault.StaticBool(false), PlanModifiers: []planmodifier.Bool{ boolplanmodifier.UseStateForUnknown(), }, @@ -333,6 +329,20 @@ func (r *lifecyclePolicyResource) Create(ctx context.Context, request resource.C data.LifecyclePolicyARN = fwflex.StringToFramework(ctx, output.LifecyclePolicyArn) data.setID() + // Read to retrieve computed arguments not part of the create response. + policy, err := findLifecyclePolicyByARN(ctx, conn, data.ID.ValueString()) + + if err != nil { + response.Diagnostics.AddError(fmt.Sprintf("reading Image Builder Lifecycle Policy (%s)", data.ID.ValueString()), err.Error()) + + return + } + + response.Diagnostics.Append(fwflex.Flatten(ctx, policy, &data)...) + if response.Diagnostics.HasError() { + return + } + response.Diagnostics.Append(response.State.Set(ctx, data)...) } @@ -351,7 +361,7 @@ func (r *lifecyclePolicyResource) Read(ctx context.Context, request resource.Rea conn := r.Meta().ImageBuilderClient(ctx) - output, err := findLifecyclePolicyByARN(ctx, conn, data.ID.ValueString()) + policy, err := findLifecyclePolicyByARN(ctx, conn, data.ID.ValueString()) if tfresource.NotFound(err) { response.Diagnostics.Append(fwdiag.NewResourceNotFoundWarningDiagnostic(err)) @@ -366,10 +376,10 @@ func (r *lifecyclePolicyResource) Read(ctx context.Context, request resource.Rea return } - setTagsOut(ctx, output.Tags) + setTagsOut(ctx, policy.Tags) // Set attributes for import. - response.Diagnostics.Append(fwflex.Flatten(ctx, output, &data)...) + response.Diagnostics.Append(fwflex.Flatten(ctx, policy, &data)...) if response.Diagnostics.HasError() { return } From 7b6e1175fbfef5d2be44acf8089219c8d12d3d95 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 6 Aug 2024 10:10:21 -0400 Subject: [PATCH 102/112] Acceptance test output: % make testacc TESTARGS='-run=TestAccImageBuilderLifecyclePolicy_' PKG=imagebuilder ACCTEST_PARALLELISM=3 make: Verifying source code with gofmt... ==> Checking that code complies with gofmt requirements... TF_ACC=1 go1.22.5 test ./internal/service/imagebuilder/... -v -count 1 -parallel 3 -run=TestAccImageBuilderLifecyclePolicy_ -timeout 360m === RUN TestAccImageBuilderLifecyclePolicy_basic === PAUSE TestAccImageBuilderLifecyclePolicy_basic === RUN TestAccImageBuilderLifecyclePolicy_policyDetails === PAUSE TestAccImageBuilderLifecyclePolicy_policyDetails === RUN TestAccImageBuilderLifecyclePolicy_resourceSelection === PAUSE TestAccImageBuilderLifecyclePolicy_resourceSelection === RUN TestAccImageBuilderLifecyclePolicy_tags === PAUSE TestAccImageBuilderLifecyclePolicy_tags === RUN TestAccImageBuilderLifecyclePolicy_disappears === PAUSE TestAccImageBuilderLifecyclePolicy_disappears === CONT TestAccImageBuilderLifecyclePolicy_basic === CONT TestAccImageBuilderLifecyclePolicy_tags === CONT TestAccImageBuilderLifecyclePolicy_resourceSelection --- PASS: TestAccImageBuilderLifecyclePolicy_basic (22.53s) === CONT TestAccImageBuilderLifecyclePolicy_policyDetails --- PASS: TestAccImageBuilderLifecyclePolicy_resourceSelection (31.12s) === CONT TestAccImageBuilderLifecyclePolicy_disappears --- PASS: TestAccImageBuilderLifecyclePolicy_tags (33.25s) --- PASS: TestAccImageBuilderLifecyclePolicy_policyDetails (29.03s) --- PASS: TestAccImageBuilderLifecyclePolicy_disappears (20.49s) PASS ok github.com/hashicorp/terraform-provider-aws/internal/service/imagebuilder 56.367s From 134e6dfb64703861888e855d065b1ba7f12a2c1a Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 6 Aug 2024 11:51:29 -0400 Subject: [PATCH 103/112] imagebuilder: Use 'tfawserr.ErrCodeEquals', not 'errs.IsA'. --- internal/service/imagebuilder/component.go | 6 +++--- internal/service/imagebuilder/container_recipe.go | 6 +++--- internal/service/imagebuilder/distribution_configuration.go | 6 +++--- internal/service/imagebuilder/image.go | 6 +++--- internal/service/imagebuilder/image_pipeline.go | 6 +++--- internal/service/imagebuilder/image_recipe.go | 6 +++--- .../service/imagebuilder/infrastructure_configuration.go | 5 +++-- internal/service/imagebuilder/workflow.go | 6 +++--- 8 files changed, 24 insertions(+), 23 deletions(-) diff --git a/internal/service/imagebuilder/component.go b/internal/service/imagebuilder/component.go index 75f9b7e8f6b..a392e27c6b4 100644 --- a/internal/service/imagebuilder/component.go +++ b/internal/service/imagebuilder/component.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -17,7 +18,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -247,7 +247,7 @@ func resourceComponentDelete(ctx context.Context, d *schema.ResourceData, meta i ComponentBuildVersionArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -265,7 +265,7 @@ func findComponentByARN(ctx context.Context, conn *imagebuilder.Client, arn stri output, err := conn.GetComponent(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/container_recipe.go b/internal/service/imagebuilder/container_recipe.go index 3bbcc7b522d..ff0205da6eb 100644 --- a/internal/service/imagebuilder/container_recipe.go +++ b/internal/service/imagebuilder/container_recipe.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -18,7 +19,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/sdkv2/types/nullable" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -428,7 +428,7 @@ func resourceContainerRecipeDelete(ctx context.Context, d *schema.ResourceData, ContainerRecipeArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -446,7 +446,7 @@ func findContainerRecipeByARN(ctx context.Context, conn *imagebuilder.Client, ar output, err := conn.GetContainerRecipe(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 79bb816bcce..53ed42ef016 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -11,13 +11,13 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-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/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -394,7 +394,7 @@ func resourceDistributionConfigurationDelete(ctx context.Context, d *schema.Reso DistributionConfigurationArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -412,7 +412,7 @@ func findDistributionConfigurationByARN(ctx context.Context, conn *imagebuilder. output, err := conn.GetDistributionConfiguration(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/image.go b/internal/service/imagebuilder/image.go index 1d7c5e2c79c..dc6f261eb85 100644 --- a/internal/service/imagebuilder/image.go +++ b/internal/service/imagebuilder/image.go @@ -13,6 +13,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -20,7 +21,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -421,7 +421,7 @@ func resourceImageDelete(ctx context.Context, d *schema.ResourceData, meta inter ImageBuildVersionArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -439,7 +439,7 @@ func findImageByARN(ctx context.Context, conn *imagebuilder.Client, arn string) output, err := conn.GetImage(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/image_pipeline.go b/internal/service/imagebuilder/image_pipeline.go index c311ce08253..167634f2cc0 100644 --- a/internal/service/imagebuilder/image_pipeline.go +++ b/internal/service/imagebuilder/image_pipeline.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -18,7 +19,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -465,7 +465,7 @@ func resourceImagePipelineDelete(ctx context.Context, d *schema.ResourceData, me ImagePipelineArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -483,7 +483,7 @@ func findImagePipelineByARN(ctx context.Context, conn *imagebuilder.Client, arn output, err := conn.GetImagePipeline(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/image_recipe.go b/internal/service/imagebuilder/image_recipe.go index 7c4a47eefed..3f61cb1c45f 100644 --- a/internal/service/imagebuilder/image_recipe.go +++ b/internal/service/imagebuilder/image_recipe.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -18,7 +19,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/sdkv2/types/nullable" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -366,7 +366,7 @@ func resourceImageRecipeDelete(ctx context.Context, d *schema.ResourceData, meta ImageRecipeArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -384,7 +384,7 @@ func findImageRecipeByARN(ctx context.Context, conn *imagebuilder.Client, arn st output, err := conn.GetImageRecipe(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/infrastructure_configuration.go b/internal/service/imagebuilder/infrastructure_configuration.go index 4df9e261148..e623435d254 100644 --- a/internal/service/imagebuilder/infrastructure_configuration.go +++ b/internal/service/imagebuilder/infrastructure_configuration.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -372,7 +373,7 @@ func resourceInfrastructureConfigurationDelete(ctx context.Context, d *schema.Re InfrastructureConfigurationArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -390,7 +391,7 @@ func findInfrastructureConfigurationByARN(ctx context.Context, conn *imagebuilde output, err := conn.GetInfrastructureConfiguration(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, diff --git a/internal/service/imagebuilder/workflow.go b/internal/service/imagebuilder/workflow.go index 4c55e5e984a..e89d9e9fec7 100644 --- a/internal/service/imagebuilder/workflow.go +++ b/internal/service/imagebuilder/workflow.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/imagebuilder" awstypes "github.com/aws/aws-sdk-go-v2/service/imagebuilder/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -18,7 +19,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/errs" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -203,7 +203,7 @@ func resourceWorkflowDelete(ctx context.Context, d *schema.ResourceData, meta in WorkflowBuildVersionArn: aws.String(d.Id()), }) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return diags } @@ -221,7 +221,7 @@ func findWorkflowByARN(ctx context.Context, conn *imagebuilder.Client, arn strin output, err := conn.GetWorkflow(ctx, input) - if errs.IsA[*awstypes.ResourceNotFoundException](err) { + if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { return nil, &retry.NotFoundError{ LastError: err, LastRequest: input, From 1af104e35f8fbd220a92f55cbceff20f09d6edd1 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 6 Aug 2024 11:55:28 -0400 Subject: [PATCH 104/112] Fix 'TestAccImageBuilderContainerRecipe_InstanceConfiguration_Image'. --- internal/service/imagebuilder/container_recipe_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/container_recipe_test.go b/internal/service/imagebuilder/container_recipe_test.go index 420d859ca82..9a4f3d65bfa 100644 --- a/internal/service/imagebuilder/container_recipe_test.go +++ b/internal/service/imagebuilder/container_recipe_test.go @@ -1370,7 +1370,7 @@ data "aws_ami" "test" { filter { name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] + values = ["amzn2-ami-hvm-*-x86_64-gp2"] } } From 30d5697d7aae2c6a25b27c38c7c65350451f9f93 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 3 Sep 2024 14:10:15 -0400 Subject: [PATCH 105/112] No more AWS SDK for Go v1 'namevaluesfilters'. --- .../generate/namevaluesfilters/v1/file.tmpl | 38 ------------ .../generate/namevaluesfilters/v1/main.go | 59 ------------------- internal/namevaluesfilters/v1/README.md | 5 -- internal/namevaluesfilters/v1/generate.go | 7 --- .../v1/name_values_filters.go | 16 ----- .../v1/service_filters_gen.go | 9 --- .../v1/service_generation_customizations.go | 42 ------------- 7 files changed, 176 deletions(-) delete mode 100644 internal/generate/namevaluesfilters/v1/file.tmpl delete mode 100644 internal/generate/namevaluesfilters/v1/main.go delete mode 100644 internal/namevaluesfilters/v1/README.md delete mode 100644 internal/namevaluesfilters/v1/generate.go delete mode 100644 internal/namevaluesfilters/v1/name_values_filters.go delete mode 100644 internal/namevaluesfilters/v1/service_filters_gen.go delete mode 100644 internal/namevaluesfilters/v1/service_generation_customizations.go diff --git a/internal/generate/namevaluesfilters/v1/file.tmpl b/internal/generate/namevaluesfilters/v1/file.tmpl deleted file mode 100644 index 7d1c17124d5..00000000000 --- a/internal/generate/namevaluesfilters/v1/file.tmpl +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by generators/servicefilters/main.go; DO NOT EDIT. - -package v1 - -import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports - "github.com/aws/aws-sdk-go/aws" -{{- range .SliceServiceNames }} -{{- if eq . (. | FilterPackage) }} - "github.com/aws/aws-sdk-go/service/{{ . }}" -{{- end }} -{{- end }} -) - -// []*SERVICE.Filter handling -{{- range .SliceServiceNames }} - -// {{ . | ProviderNameUpper }}Filters returns {{ . }} service filters. -func (filters NameValuesFilters) {{ . | ProviderNameUpper }}Filters() []*{{ . | FilterPackage }}.{{ . | FilterType }} { - m := filters.Map() - - if len(m) == 0 { - return nil - } - - result := make([]*{{ . | FilterPackage }}.{{ . | FilterType }}, 0, len(m)) - - for k, v := range m { - filter := &{{ . | FilterPackage }}.{{ . | FilterType }}{ - {{ . | FilterTypeNameField }}: aws.String(k), - {{ . | FilterTypeValuesField }}: aws.StringSlice(v), - } - - result = append(result, filter) - } - - return result -} -{{- end }} diff --git a/internal/generate/namevaluesfilters/v1/main.go b/internal/generate/namevaluesfilters/v1/main.go deleted file mode 100644 index 1b77c9be756..00000000000 --- a/internal/generate/namevaluesfilters/v1/main.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -//go:build generate -// +build generate - -package main - -import ( - _ "embed" - "sort" - "text/template" - - "github.com/hashicorp/terraform-provider-aws/internal/generate/common" - namevaluesfiltersv1 "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters/v1" - "github.com/hashicorp/terraform-provider-aws/names" -) - -type TemplateData struct { - SliceServiceNames []string -} - -func main() { - const ( - filename = `service_filters_gen.go` - ) - g := common.NewGenerator() - - g.Infof("Generating internal/namevaluesfilters/v1/%s", filename) - - // Representing types such as []*fsx.Filter, []*rds.Filter, ... - sliceServiceNames := []string{} - // Always sort to reduce any potential generation churn - sort.Strings(sliceServiceNames) - - td := TemplateData{ - SliceServiceNames: sliceServiceNames, - } - templateFuncMap := template.FuncMap{ - "FilterPackage": namevaluesfiltersv1.ServiceFilterPackage, - "FilterType": namevaluesfiltersv1.ServiceFilterType, - "FilterTypeNameField": namevaluesfiltersv1.ServiceFilterTypeNameField, - "FilterTypeValuesField": namevaluesfiltersv1.ServiceFilterTypeValuesField, - "ProviderNameUpper": names.ProviderNameUpper, - } - - d := g.NewGoFileDestination(filename) - - if err := d.WriteTemplate("namevaluesfilters", tmpl, td, templateFuncMap); err != nil { - g.Fatalf("generating file (%s): %s", filename, err) - } - - if err := d.Write(); err != nil { - g.Fatalf("generating file (%s): %s", filename, err) - } -} - -//go:embed file.tmpl -var tmpl string diff --git a/internal/namevaluesfilters/v1/README.md b/internal/namevaluesfilters/v1/README.md deleted file mode 100644 index 3793f5a824f..00000000000 --- a/internal/namevaluesfilters/v1/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# namevaluesfilters - -The `namevaluesfilters/v1` package is designed to provide a consistent interface for handling AWS resource filtering with AWS SDK for Go v1. - -This package implements a single `NameValuesFilters` type, which covers all filter handling logic, such as merging filters, via functions on the single type. The underlying implementation is compatible with Go operations such as `len()`. diff --git a/internal/namevaluesfilters/v1/generate.go b/internal/namevaluesfilters/v1/generate.go deleted file mode 100644 index e5639504819..00000000000 --- a/internal/namevaluesfilters/v1/generate.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -//go:generate go run ../../generate/namevaluesfilters/v1/main.go -// ONLY generate directives and package declaration! Do not add anything else to this file. - -package v1 diff --git a/internal/namevaluesfilters/v1/name_values_filters.go b/internal/namevaluesfilters/v1/name_values_filters.go deleted file mode 100644 index c8b81fabb46..00000000000 --- a/internal/namevaluesfilters/v1/name_values_filters.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package v1 - -import ( - "github.com/hashicorp/terraform-provider-aws/internal/namevaluesfilters" -) - -type NameValuesFilters struct { - namevaluesfilters.NameValuesFilters -} - -func New(i interface{}) NameValuesFilters { - return NameValuesFilters{NameValuesFilters: namevaluesfilters.New(i)} -} diff --git a/internal/namevaluesfilters/v1/service_filters_gen.go b/internal/namevaluesfilters/v1/service_filters_gen.go deleted file mode 100644 index 51b746cbe7f..00000000000 --- a/internal/namevaluesfilters/v1/service_filters_gen.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by generators/servicefilters/main.go; DO NOT EDIT. - -package v1 - -import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports - "github.com/aws/aws-sdk-go/aws" -) - -// []*SERVICE.Filter handling diff --git a/internal/namevaluesfilters/v1/service_generation_customizations.go b/internal/namevaluesfilters/v1/service_generation_customizations.go deleted file mode 100644 index 9af370ab50b..00000000000 --- a/internal/namevaluesfilters/v1/service_generation_customizations.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -// This file contains code generation customizations for each AWS Go SDK service. - -package v1 - -// ServiceFilterPackage determines the service filter type package. -func ServiceFilterPackage(serviceName string) string { - switch serviceName { - default: - return serviceName - } -} - -// ServiceFilterType determines the service filter type. -func ServiceFilterType(serviceName string) string { - switch serviceName { - case "resourcegroupstaggingapi": - return "TagFilter" - default: - return "Filter" - } -} - -// ServiceFilterTypeNameField determines the service filter type name field. -func ServiceFilterTypeNameField(serviceName string) string { - switch serviceName { - case "resourcegroupstaggingapi", "secretsmanager": - return "Key" - default: - return "Name" - } -} - -// ServiceFilterTypeValuesField determines the service filter type values field. -func ServiceFilterTypeValuesField(serviceName string) string { - switch serviceName { - default: - return "Values" - } -} From 4aad53c48befc297c15ba0f8103553321971aa32 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 13 Sep 2024 11:01:49 -0400 Subject: [PATCH 106/112] Fix semgrep 'ci.semgrep.framework.model-tag-types'. --- internal/service/imagebuilder/lifecycle_policy.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 9644778908c..633a49de7cb 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -488,8 +488,8 @@ type lifecyclePolicyResourceModel struct { ResourceSelection fwtypes.ListNestedObjectValueOf[lifecyclePolicyResourceSelectionModel] `tfsdk:"resource_selection"` ResourceType fwtypes.StringEnum[awstypes.LifecyclePolicyResourceType] `tfsdk:"resource_type"` Status fwtypes.StringEnum[awstypes.LifecyclePolicyStatus] `tfsdk:"status"` - Tags types.Map `tfsdk:"tags"` - TagsAll types.Map `tfsdk:"tags_all"` + Tags tftags.Map `tfsdk:"tags"` + TagsAll tftags.Map `tfsdk:"tags_all"` } func (model *lifecyclePolicyResourceModel) InitFromID() error { From c9b6615a31ab11c0eec68fb8b6c03759ed67eab1 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Fri, 20 Sep 2024 10:37:15 -0400 Subject: [PATCH 107/112] Fix semgrep 'ci.semgrep.framework.flex-type-from-framework'. --- internal/service/imagebuilder/lifecycle_policy.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/lifecycle_policy.go b/internal/service/imagebuilder/lifecycle_policy.go index 633a49de7cb..de77993cb4f 100644 --- a/internal/service/imagebuilder/lifecycle_policy.go +++ b/internal/service/imagebuilder/lifecycle_policy.go @@ -439,7 +439,7 @@ func (r *lifecyclePolicyResource) Delete(ctx context.Context, request resource.D conn := r.Meta().ImageBuilderClient(ctx) _, err := conn.DeleteLifecyclePolicy(ctx, &imagebuilder.DeleteLifecyclePolicyInput{ - LifecyclePolicyArn: aws.String(data.ID.ValueString()), + LifecyclePolicyArn: data.ID.ValueStringPointer(), }) if tfawserr.ErrCodeEquals(err, errCodeResourceNotFoundException) { From c1cfc0c6dbe9d852a0031b0f8306e57029d5cf0f Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Tue, 24 Sep 2024 14:28:12 -0400 Subject: [PATCH 108/112] tfresource: Remove AWS SDK for Go v1 error handling. --- internal/tfresource/retry.go | 9 ++-- internal/tfresource/retry_test.go | 78 ------------------------------- 2 files changed, 4 insertions(+), 83 deletions(-) diff --git a/internal/tfresource/retry.go b/internal/tfresource/retry.go index 923a16b9d49..6aeccc2525b 100644 --- a/internal/tfresource/retry.go +++ b/internal/tfresource/retry.go @@ -11,8 +11,7 @@ import ( "sync" "time" - tfawserr_sdkv1 "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" - tfawserr_sdkv2 "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) @@ -96,7 +95,7 @@ func RetryGWhen[T any](ctx context.Context, timeout time.Duration, f func() (T, // RetryWhenAWSErrCodeEquals retries the specified function when it returns one of the specified AWS error codes. func RetryWhenAWSErrCodeEquals(ctx context.Context, timeout time.Duration, f func() (interface{}, error), codes ...string) (interface{}, error) { // nosemgrep:ci.aws-in-func-name return RetryWhen(ctx, timeout, f, func(err error) (bool, error) { - if tfawserr_sdkv1.ErrCodeEquals(err, codes...) || tfawserr_sdkv2.ErrCodeEquals(err, codes...) { + if tfawserr.ErrCodeEquals(err, codes...) { return true, err } @@ -107,7 +106,7 @@ func RetryWhenAWSErrCodeEquals(ctx context.Context, timeout time.Duration, f fun // RetryWhenAWSErrCodeContains retries the specified function when it returns an AWS error containing the specified code. func RetryWhenAWSErrCodeContains(ctx context.Context, timeout time.Duration, f func() (interface{}, error), code string) (interface{}, error) { // nosemgrep:ci.aws-in-func-name return RetryWhen(ctx, timeout, f, func(err error) (bool, error) { - if tfawserr_sdkv1.ErrCodeContains(err, code) || tfawserr_sdkv2.ErrCodeContains(err, code) { + if tfawserr.ErrCodeContains(err, code) { return true, err } @@ -118,7 +117,7 @@ func RetryWhenAWSErrCodeContains(ctx context.Context, timeout time.Duration, f f // RetryWhenAWSErrMessageContains retries the specified function when it returns an AWS error containing the specified message. func RetryWhenAWSErrMessageContains(ctx context.Context, timeout time.Duration, f func() (interface{}, error), code, message string) (interface{}, error) { // nosemgrep:ci.aws-in-func-name return RetryWhen(ctx, timeout, f, func(err error) (bool, error) { - if tfawserr_sdkv1.ErrMessageContains(err, code, message) || tfawserr_sdkv2.ErrMessageContains(err, code, message) { + if tfawserr.ErrMessageContains(err, code, message) { return true, err } diff --git a/internal/tfresource/retry_test.go b/internal/tfresource/retry_test.go index 7c095fdd689..33031199d8e 100644 --- a/internal/tfresource/retry_test.go +++ b/internal/tfresource/retry_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -21,8 +20,6 @@ func TestRetryWhenAWSErrCodeEquals(t *testing.T) { // nosemgrep:ci.aws-in-func-n ctx := acctest.Context(t) t.Parallel() - var retryCount int32 - testCases := []struct { Name string F func() (interface{}, error) @@ -41,36 +38,10 @@ func TestRetryWhenAWSErrCodeEquals(t *testing.T) { // nosemgrep:ci.aws-in-func-n }, ExpectError: true, }, - { - Name: "non-retryable AWS error", - F: func() (interface{}, error) { - return nil, awserr.New("Testing", "Testing", nil) - }, - ExpectError: true, - }, - { - Name: "retryable AWS error timeout", - F: func() (interface{}, error) { - return nil, awserr.New("TestCode1", "TestMessage", nil) - }, - ExpectError: true, - }, - { - Name: "retryable AWS error success", - F: func() (interface{}, error) { - if atomic.CompareAndSwapInt32(&retryCount, 0, 1) { - return nil, awserr.New("TestCode2", "TestMessage", nil) - } - - return nil, nil - }, - }, } for _, testCase := range testCases { //nolint:paralleltest t.Run(testCase.Name, func(t *testing.T) { - retryCount = 0 - _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, 5*time.Second, testCase.F, "TestCode1", "TestCode2") if testCase.ExpectError && err == nil { @@ -87,8 +58,6 @@ func TestRetryWhenAWSErrMessageContains(t *testing.T) { // nosemgrep:ci.aws-in-f ctx := acctest.Context(t) t.Parallel() - var retryCount int32 - testCases := []struct { Name string F func() (interface{}, error) @@ -107,36 +76,10 @@ func TestRetryWhenAWSErrMessageContains(t *testing.T) { // nosemgrep:ci.aws-in-f }, ExpectError: true, }, - { - Name: "non-retryable AWS error", - F: func() (interface{}, error) { - return nil, awserr.New("TestCode1", "Testing", nil) - }, - ExpectError: true, - }, - { - Name: "retryable AWS error timeout", - F: func() (interface{}, error) { - return nil, awserr.New("TestCode1", "TestMessage1", nil) - }, - ExpectError: true, - }, - { - Name: "retryable AWS error success", - F: func() (interface{}, error) { - if atomic.CompareAndSwapInt32(&retryCount, 0, 1) { - return nil, awserr.New("TestCode1", "TestMessage1", nil) - } - - return nil, nil - }, - }, } for _, testCase := range testCases { //nolint:paralleltest t.Run(testCase.Name, func(t *testing.T) { - retryCount = 0 - _, err := tfresource.RetryWhenAWSErrMessageContains(ctx, 5*time.Second, testCase.F, "TestCode1", "TestMessage1") if testCase.ExpectError && err == nil { @@ -188,13 +131,6 @@ func TestRetryWhenNewResourceNotFound(t *testing.T) { //nolint:tparallel NewResource: true, ExpectError: true, }, - { - Name: "non-retryable AWS error", - F: func() (interface{}, error) { - return nil, awserr.New("Testing", "Testing", nil) - }, - ExpectError: true, - }, { Name: "retryable NotFoundError not new resource", F: func() (interface{}, error) { @@ -262,13 +198,6 @@ func TestRetryWhenNotFound(t *testing.T) { //nolint:tparallel }, ExpectError: true, }, - { - Name: "non-retryable AWS error", - F: func() (interface{}, error) { - return nil, awserr.New("Testing", "Testing", nil) - }, - ExpectError: true, - }, { Name: "retryable NotFoundError timeout", F: func() (interface{}, error) { @@ -328,13 +257,6 @@ func TestRetryUntilNotFound(t *testing.T) { //nolint:tparallel }, ExpectError: true, }, - { - Name: "AWS error", - F: func() (interface{}, error) { - return nil, awserr.New("Testing", "Testing", nil) - }, - ExpectError: true, - }, { Name: "NotFoundError", F: func() (interface{}, error) { From abb7df468092f424ae3514194c526b957abdd49b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 9 Oct 2024 08:46:34 -0400 Subject: [PATCH 109/112] Fix 'Warning: [Fixable] Interpolation-only expressions are deprecated in Terraform v0.12.14 (terraform_deprecated_interpolation)'. --- internal/service/imagebuilder/lifecycle_policy_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/imagebuilder/lifecycle_policy_test.go b/internal/service/imagebuilder/lifecycle_policy_test.go index 9635ac26697..72eb6bf1ff4 100644 --- a/internal/service/imagebuilder/lifecycle_policy_test.go +++ b/internal/service/imagebuilder/lifecycle_policy_test.go @@ -424,7 +424,7 @@ resource "aws_imagebuilder_lifecycle_policy" "test" { exclusion_rules { amis { is_public = true - regions = ["${data.aws_region.current.name}"] + regions = [data.aws_region.current.name] last_launched { unit = "WEEKS" value = 2 From 1dfd05aa0baea1470da8638674b4862a84a3816b Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 16 Oct 2024 16:21:31 -0400 Subject: [PATCH 110/112] github.com/aws/aws-sdk-go-v2/service/imagebuilder@v1.37.3 --- go.mod | 2 +- go.sum | 4 ++-- internal/service/imagebuilder/distribution_configuration.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index c3523998dae..73963937a1c 100644 --- a/go.mod +++ b/go.mod @@ -133,7 +133,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/healthlake v1.28.2 github.com/aws/aws-sdk-go-v2/service/iam v1.37.2 github.com/aws/aws-sdk-go-v2/service/identitystore v1.27.2 - github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.37.2 + github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.37.3 github.com/aws/aws-sdk-go-v2/service/inspector v1.25.2 github.com/aws/aws-sdk-go-v2/service/inspector2 v1.32.2 github.com/aws/aws-sdk-go-v2/service/internetmonitor v1.19.2 diff --git a/go.sum b/go.sum index 4bd9d15667a..0eeea31613b 100644 --- a/go.sum +++ b/go.sum @@ -278,8 +278,8 @@ github.com/aws/aws-sdk-go-v2/service/iam v1.37.2 h1:E7vCDUFeDN8uOk8Nb2d4E1howWS1 github.com/aws/aws-sdk-go-v2/service/iam v1.37.2/go.mod h1:QzMecFrIFYJ1cyxjlUoIFRzYSDX19gdqYUd0Tyws2J8= github.com/aws/aws-sdk-go-v2/service/identitystore v1.27.2 h1:QSrf6HsounqUtlFAwArhVNHPt3WXmSm0pz7RtojjBdo= github.com/aws/aws-sdk-go-v2/service/identitystore v1.27.2/go.mod h1:PtkL4CXOQy84zudggyFtyJFXCGDRY8igg9Nfo9df1sU= -github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.37.2 h1:SVVUk9vbUPWZEeM2ji9fOBOlBFf22jLiGU5xwt5oZ5M= -github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.37.2/go.mod h1:hqe5ZWGAMgZC14I2GrXc+tUPpucDfGb94RB/7IOdQ/o= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.37.3 h1:Pdh3M/+3nyVJIEqD7UrbiBrtUIcC1uTk/NIrI6M/d3I= +github.com/aws/aws-sdk-go-v2/service/imagebuilder v1.37.3/go.mod h1:hqe5ZWGAMgZC14I2GrXc+tUPpucDfGb94RB/7IOdQ/o= github.com/aws/aws-sdk-go-v2/service/inspector v1.25.2 h1:xiQ70pTvXs9PFYmewDgeICVxRpiQP+cWQZmunV5uYKk= github.com/aws/aws-sdk-go-v2/service/inspector v1.25.2/go.mod h1:sDcAla3dh7DO6AAdh+29e+rowLaIcw2fxuwNFCIlBuA= github.com/aws/aws-sdk-go-v2/service/inspector2 v1.32.2 h1:D0nDW7y3KLPGShqF7gaKFRswY8ekG8jsfN4r3CWqAjQ= diff --git a/internal/service/imagebuilder/distribution_configuration.go b/internal/service/imagebuilder/distribution_configuration.go index 53ed42ef016..913ed40c853 100644 --- a/internal/service/imagebuilder/distribution_configuration.go +++ b/internal/service/imagebuilder/distribution_configuration.go @@ -727,7 +727,7 @@ func expandLaunchTemplateConfiguration(tfMap map[string]interface{}) *awstypes.L } if v, ok := tfMap["default"].(bool); ok { - apiObject.SetDefaultVersion = v + apiObject.SetDefaultVersion = aws.Bool(v) } if v, ok := tfMap[names.AttrAccountID].(string); ok && v != "" { From b0d0e13f3fe9c42371090b0125fd7fae9ec5c0c9 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 16 Oct 2024 17:15:20 -0400 Subject: [PATCH 111/112] 'component/update-linux/1.0.0' -> 'component/update-linux/1.0.2'. --- internal/service/imagebuilder/image_data_source_test.go | 4 ++-- internal/service/imagebuilder/image_test.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/service/imagebuilder/image_data_source_test.go b/internal/service/imagebuilder/image_data_source_test.go index b4e92b73778..6bd5236f945 100644 --- a/internal/service/imagebuilder/image_data_source_test.go +++ b/internal/service/imagebuilder/image_data_source_test.go @@ -129,7 +129,7 @@ data "aws_imagebuilder_image" "test" { func testAccImageDataSourceConfig_arnSelf(rName string) string { return fmt.Sprintf(` data "aws_imagebuilder_component" "update-linux" { - arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.0" + arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.2" } data "aws_region" "current" {} @@ -330,7 +330,7 @@ resource "aws_ecr_repository" "test" { } data "aws_imagebuilder_component" "update-linux" { - arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.0" + arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.2" } resource "aws_imagebuilder_container_recipe" "test" { diff --git a/internal/service/imagebuilder/image_test.go b/internal/service/imagebuilder/image_test.go index 193599ec745..1d0cee59615 100644 --- a/internal/service/imagebuilder/image_test.go +++ b/internal/service/imagebuilder/image_test.go @@ -391,7 +391,7 @@ func testAccCheckImageExists(ctx context.Context, n string) resource.TestCheckFu func testAccImageBaseConfig(rName string) string { return fmt.Sprintf(` data "aws_imagebuilder_component" "update-linux" { - arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.0" + arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.2" } data "aws_region" "current" {} @@ -923,7 +923,7 @@ resource "aws_ecr_repository" "test" { } data "aws_imagebuilder_component" "update-linux" { - arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.0" + arn = "arn:${data.aws_partition.current.partition}:imagebuilder:${data.aws_region.current.name}:aws:component/update-linux/1.0.2" } resource "aws_imagebuilder_container_recipe" "test" { From a3d3cf6a11672349fce690579cc51f7f5558a5d6 Mon Sep 17 00:00:00 2001 From: Kit Ewbank Date: Wed, 16 Oct 2024 18:33:47 -0400 Subject: [PATCH 112/112] Fix 'TestAccImageBuilderDistributionConfiguration_DistributionFastLaunchConfiguration_launchTemplate'. --- .../service/imagebuilder/distribution_configuration_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/imagebuilder/distribution_configuration_test.go b/internal/service/imagebuilder/distribution_configuration_test.go index a512b061b4b..212f8d4b62a 100644 --- a/internal/service/imagebuilder/distribution_configuration_test.go +++ b/internal/service/imagebuilder/distribution_configuration_test.go @@ -1315,7 +1315,7 @@ data "aws_caller_identity" "current" {} resource "aws_launch_template" "test" { instance_type = "t2.micro" - name = %[1]q + name = "%[1]s-1" } resource "aws_imagebuilder_distribution_configuration" "test" { @@ -1346,7 +1346,7 @@ data "aws_caller_identity" "current" {} resource "aws_launch_template" "test2" { instance_type = "t2.micro" - name = %[1]q + name = "%[1]s-2" } resource "aws_imagebuilder_distribution_configuration" "test" {