diff --git a/internal/acctest/acctest.go b/internal/acctest/acctest.go index 41bfa6fb825..8899c722dcc 100644 --- a/internal/acctest/acctest.go +++ b/internal/acctest/acctest.go @@ -29,7 +29,7 @@ import ( dstypes "github.com/aws/aws-sdk-go-v2/service/directoryservice/types" ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go-v2/service/iam" - awstypes "github.com/aws/aws-sdk-go-v2/service/iam/types" + iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types" "github.com/aws/aws-sdk-go-v2/service/inspector2" inspector2types "github.com/aws/aws-sdk-go-v2/service/inspector2/types" organizationstypes "github.com/aws/aws-sdk-go-v2/service/organizations/types" @@ -40,7 +40,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/outposts" "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" @@ -1188,7 +1187,7 @@ func PreCheckIAMServiceLinkedRoleWithProvider(ctx context.Context, t *testing.T, input := &iam.ListRolesInput{ PathPrefix: aws.String(pathPrefix), } - var role awstypes.Role + var role iamtypes.Role pages := iam.NewListRolesPaginator(conn, input) for pages.HasMorePages() { @@ -2231,7 +2230,7 @@ data "aws_ec2_instance_type_offering" "%[1]s" { `, name, strings.Join(preferredInstanceTypes, "\", \"")) } -func configLatestAmazonLinux2HVMEBSAMI(architecture string) string { +func configLatestAmazonLinux2HVMEBSAMI(architecture ec2types.ArchitectureValues) string { return fmt.Sprintf(` data "aws_ami" "amzn2-ami-minimal-hvm-ebs-%[1]s" { most_recent = true @@ -2259,14 +2258,14 @@ data "aws_ami" "amzn2-ami-minimal-hvm-ebs-%[1]s" { // describes the latest Amazon Linux 2 x86_64 AMI using HVM virtualization and an EBS root device. // The data source is named 'amzn2-ami-minimal-hvm-ebs-x86_64'. func ConfigLatestAmazonLinux2HVMEBSX8664AMI() string { - return configLatestAmazonLinux2HVMEBSAMI(ec2.ArchitectureValuesX8664) + return configLatestAmazonLinux2HVMEBSAMI(ec2types.ArchitectureValuesX8664) } // ConfigLatestAmazonLinux2HVMEBSARM64AMI returns the configuration for a data source that // describes the latest Amazon Linux 2 arm64 AMI using HVM virtualization and an EBS root device. // The data source is named 'amzn2-ami-minimal-hvm-ebs-arm64'. func ConfigLatestAmazonLinux2HVMEBSARM64AMI() string { - return configLatestAmazonLinux2HVMEBSAMI(ec2.ArchitectureValuesArm64) + return configLatestAmazonLinux2HVMEBSAMI(ec2types.ArchitectureValuesArm64) } func ConfigLambdaBase(policyName, roleName, sgName string) string { @@ -2494,32 +2493,7 @@ resource "aws_subnet" "test" { ) } -func CheckVPCExists(ctx context.Context, n string, v *ec2.Vpc) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("no VPC ID is set") - } - - conn := Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) - - output, err := tfec2.FindVPCByID(ctx, conn, rs.Primary.ID) - - if err != nil { - return err - } - - *v = *output - - return nil - } -} - -func CheckVPCExistsV2(ctx context.Context, n string, v *ec2types.Vpc) resource.TestCheckFunc { +func CheckVPCExists(ctx context.Context, n string, v *ec2types.Vpc) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -2532,7 +2506,7 @@ func CheckVPCExistsV2(ctx context.Context, n string, v *ec2types.Vpc) resource.T conn := Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindVPCByIDV2(ctx, conn, rs.Primary.ID) + output, err := tfec2.FindVPCByID(ctx, conn, rs.Primary.ID) if err != nil { return err diff --git a/internal/conns/awsclient_gen.go b/internal/conns/awsclient_gen.go index 803afa93c39..8168052fa39 100644 --- a/internal/conns/awsclient_gen.go +++ b/internal/conns/awsclient_gen.go @@ -210,7 +210,6 @@ import ( chime_sdkv1 "github.com/aws/aws-sdk-go/service/chime" connect_sdkv1 "github.com/aws/aws-sdk-go/service/connect" directconnect_sdkv1 "github.com/aws/aws-sdk-go/service/directconnect" - ec2_sdkv1 "github.com/aws/aws-sdk-go/service/ec2" elasticsearchservice_sdkv1 "github.com/aws/aws-sdk-go/service/elasticsearchservice" elastictranscoder_sdkv1 "github.com/aws/aws-sdk-go/service/elastictranscoder" emr_sdkv1 "github.com/aws/aws-sdk-go/service/emr" @@ -586,10 +585,6 @@ func (c *AWSClient) DynamoDBClient(ctx context.Context) *dynamodb_sdkv2.Client { return errs.Must(client[*dynamodb_sdkv2.Client](ctx, c, names.DynamoDB, make(map[string]any))) } -func (c *AWSClient) EC2Conn(ctx context.Context) *ec2_sdkv1.EC2 { - return errs.Must(conn[*ec2_sdkv1.EC2](ctx, c, names.EC2, make(map[string]any))) -} - func (c *AWSClient) EC2Client(ctx context.Context) *ec2_sdkv2.Client { return errs.Must(client[*ec2_sdkv2.Client](ctx, c, names.EC2, make(map[string]any))) } diff --git a/internal/framework/flex/string.go b/internal/framework/flex/string.go index e48f2b9dd04..9a22e4372bb 100644 --- a/internal/framework/flex/string.go +++ b/internal/framework/flex/string.go @@ -22,6 +22,16 @@ func StringFromFramework(ctx context.Context, v basetypes.StringValuable) *strin return output } +// StringValueFromFramework converts a Framework String value to a string. +// A null String is converted to an empty string. +func StringValueFromFramework(ctx context.Context, v basetypes.StringValuable) string { + var output string + + must(Expand(ctx, v, &output)) + + return output +} + // StringFromFramework converts a single Framework String value to a string pointer slice. // A null String is converted to a nil slice. func StringSliceFromFramework(ctx context.Context, v basetypes.StringValuable) []*string { @@ -32,6 +42,16 @@ func StringSliceFromFramework(ctx context.Context, v basetypes.StringValuable) [ return []*string{StringFromFramework(ctx, v)} } +// StringSliceValueFromFramework converts a single Framework String value to a string slice. +// A null String is converted to a nil slice. +func StringSliceValueFromFramework(ctx context.Context, v basetypes.StringValuable) []string { + if v.IsNull() || v.IsUnknown() { + return nil + } + + return []string{StringValueFromFramework(ctx, v)} +} + // StringValueToFramework converts a string value to a Framework String value. // An empty string is converted to a null String. func StringValueToFramework[T ~string](ctx context.Context, v T) types.String { diff --git a/internal/generate/namevaluesfilters/README.md b/internal/generate/namevaluesfilters/README.md index 7a7a3a370fa..757e5294809 100644 --- a/internal/generate/namevaluesfilters/README.md +++ b/internal/generate/namevaluesfilters/README.md @@ -8,7 +8,7 @@ Full documentation for this package can be found on [GoDoc](https://godoc.org/gi Many AWS Go SDK services that support resource filtering have their service-specific Go type conversion functions to and from `NameValuesFilters` code generated. Converting from `NameValuesFilters` to AWS Go SDK types is done via `{SERVICE}Filters()` functions on the type. For more information about this code generation, see the [`generators/servicefilters` README](generators/servicefilters/README.md). -Any filtering functions that cannot be generated should be hand implemented in a service-specific source file (e.g. `ec2_filters.go`) and follow the format of similar generated code wherever possible. The first line of the source file should be `// +build !generate`. This prevents the file's inclusion during the code generation phase. +Any filtering functions that cannot be generated should be hand implemented in a service-specific source file and follow the format of similar generated code wherever possible. The first line of the source file should be `// +build !generate`. This prevents the file's inclusion during the code generation phase. ## Code Structure diff --git a/internal/generate/namevaluesfilters/ec2_filters.go b/internal/generate/namevaluesfilters/ec2_filters.go deleted file mode 100644 index 5cbccf1bee0..00000000000 --- a/internal/generate/namevaluesfilters/ec2_filters.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -//go:build !generate -// +build !generate - -package namevaluesfilters - -import ( - "fmt" -) - -// Custom EC2 filter functions. - -// EC2Tags creates NameValuesFilters from a map of keyvalue tags. -func EC2Tags(tags map[string]string) NameValuesFilters { - m := make(map[string]string, len(tags)) - - for k, v := range tags { - m[fmt.Sprintf("tag:%s", k)] = v - } - - return New(m) -} diff --git a/internal/generate/namevaluesfilters/ec2_filters_test.go b/internal/generate/namevaluesfilters/ec2_filters_test.go deleted file mode 100644 index c272358b0c6..00000000000 --- a/internal/generate/namevaluesfilters/ec2_filters_test.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package namevaluesfilters_test - -import ( - "testing" - - "github.com/hashicorp/terraform-provider-aws/internal/acctest" - "github.com/hashicorp/terraform-provider-aws/internal/generate/namevaluesfilters" -) - -func TestNameValuesFiltersEC2Tags(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - filters namevaluesfilters.NameValuesFilters - want map[string][]string - }{ - { - name: "nil", - filters: namevaluesfilters.EC2Tags(nil), - want: map[string][]string{}, - }, - { - name: "nil", - filters: namevaluesfilters.EC2Tags(map[string]string{}), - want: map[string][]string{}, - }, - { - name: "tags", - filters: namevaluesfilters.EC2Tags(map[string]string{ - "Name": acctest.ResourcePrefix, - "Purpose": "testing", - }), - want: map[string][]string{ - "tag:Name": {acctest.ResourcePrefix}, - "tag:Purpose": {"testing"}, - }, - }, - } - - for _, testCase := range testCases { - testCase := testCase - t.Run(testCase.name, func(t *testing.T) { - t.Parallel() - - got := testCase.filters.Map() - - testNameValuesFiltersVerifyMap(t, got, testCase.want) - }) - } -} diff --git a/internal/generate/namevaluesfilters/generators/servicefilters/main.go b/internal/generate/namevaluesfilters/generators/servicefilters/main.go index 0846ad33710..1c734fc7e02 100644 --- a/internal/generate/namevaluesfilters/generators/servicefilters/main.go +++ b/internal/generate/namevaluesfilters/generators/servicefilters/main.go @@ -17,12 +17,11 @@ import ( const filename = `service_filters_gen.go` -// Representing types such as []*ec2.Filter, []*rds.Filter, ... +// Representing types such as []*fsx.Filter, []*rds.Filter, ... var sliceServiceNames = []string{ "autoscaling", "databasemigrationservice", "docdb", - "ec2", "elasticinference", "elasticsearchservice", "fsx", diff --git a/internal/generate/namevaluesfilters/service_filters_gen.go b/internal/generate/namevaluesfilters/service_filters_gen.go index 4332fa53eb7..737bce86a01 100644 --- a/internal/generate/namevaluesfilters/service_filters_gen.go +++ b/internal/generate/namevaluesfilters/service_filters_gen.go @@ -7,7 +7,6 @@ import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/databasemigrationservice" "github.com/aws/aws-sdk-go/service/docdb" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/elasticinference" "github.com/aws/aws-sdk-go/service/elasticsearchservice" "github.com/aws/aws-sdk-go/service/fsx" @@ -87,28 +86,6 @@ func (filters NameValuesFilters) DocDBFilters() []*docdb.Filter { return result } -// EC2Filters returns ec2 service filters. -func (filters NameValuesFilters) EC2Filters() []*ec2.Filter { - m := filters.Map() - - if len(m) == 0 { - return nil - } - - result := make([]*ec2.Filter, 0, len(m)) - - for k, v := range m { - filter := &ec2.Filter{ - Name: aws.String(k), - Values: aws.StringSlice(v), - } - - result = append(result, filter) - } - - return result -} - // ElasticinferenceFilters returns elasticinference service filters. func (filters NameValuesFilters) ElasticinferenceFilters() []*elasticinference.Filter { m := filters.Map() diff --git a/internal/generate/tagresource/resource.tmpl b/internal/generate/tagresource/resource.tmpl index ff9cb2342c0..b26a765f76b 100644 --- a/internal/generate/tagresource/resource.tmpl +++ b/internal/generate/tagresource/resource.tmpl @@ -55,7 +55,7 @@ func resourceTagCreate(ctx context.Context, d *schema.ResourceData, meta interfa value := d.Get(names.AttrValue).(string) {{ if eq .ServicePackage "ec2" }} - if err := createTagsV2(ctx, conn, identifier, TagsV2(tftags.New(ctx, map[string]string{key: value}))); err != nil { + if err := createTags(ctx, conn, identifier, Tags(tftags.New(ctx, map[string]string{key: value}))); err != nil { {{- else }} if err := {{ .UpdateTagsFunc }}(ctx, conn, identifier, nil, map[string]string{key: value}); err != nil { {{- end }} diff --git a/internal/service/batch/job_queue_test.go b/internal/service/batch/job_queue_test.go index 867c66441f6..397a6010035 100644 --- a/internal/service/batch/job_queue_test.go +++ b/internal/service/batch/job_queue_test.go @@ -9,9 +9,9 @@ import ( "log" "testing" + "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/batch" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -802,15 +802,15 @@ resource "aws_batch_compute_environment" "more" { func testAccCheckLaunchTemplateDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_launch_template" { continue } - resp, err := conn.DescribeLaunchTemplatesWithContext(ctx, &ec2.DescribeLaunchTemplatesInput{ - LaunchTemplateIds: []*string{aws.String(rs.Primary.ID)}, + resp, err := conn.DescribeLaunchTemplates(ctx, &ec2.DescribeLaunchTemplatesInput{ + LaunchTemplateIds: []string{rs.Primary.ID}, }) if err == nil { diff --git a/internal/service/comprehend/common_model.go b/internal/service/comprehend/common_model.go index ec25319fe24..e32d14708af 100644 --- a/internal/service/comprehend/common_model.go +++ b/internal/service/comprehend/common_model.go @@ -11,9 +11,11 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/comprehend/types" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/flex" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" "github.com/hashicorp/terraform-provider-aws/names" @@ -38,18 +40,18 @@ func (m *safeMutex) Unlock() { var modelVPCENILock safeMutex -func findNetworkInterfaces(ctx context.Context, conn *ec2.EC2, securityGroups []string, subnets []string) ([]*ec2.NetworkInterface, error) { +func findNetworkInterfaces(ctx context.Context, conn *ec2.Client, securityGroups []string, subnets []string) ([]ec2types.NetworkInterface, error) { networkInterfaces, err := tfec2.FindNetworkInterfaces(ctx, conn, &ec2.DescribeNetworkInterfacesInput{ - Filters: []*ec2.Filter{ + Filters: []ec2types.Filter{ tfec2.NewFilter("group-id", securityGroups), tfec2.NewFilter("subnet-id", subnets), }, }) if err != nil { - return []*ec2.NetworkInterface{}, err + return []ec2types.NetworkInterface{}, err } - comprehendENIs := make([]*ec2.NetworkInterface, 0, len(networkInterfaces)) + comprehendENIs := make([]ec2types.NetworkInterface, 0, len(networkInterfaces)) for _, v := range networkInterfaces { if strings.HasSuffix(aws.ToString(v.RequesterId), ":Comprehend") { comprehendENIs = append(comprehendENIs, v) @@ -59,10 +61,10 @@ func findNetworkInterfaces(ctx context.Context, conn *ec2.EC2, securityGroups [] return comprehendENIs, nil } -func waitNetworkInterfaceCreated(ctx context.Context, conn *ec2.EC2, initialENIIds map[string]bool, securityGroups []string, subnets []string, timeout time.Duration) (*ec2.NetworkInterface, error) { +func waitNetworkInterfaceCreated(ctx context.Context, conn *ec2.Client, initialENIIds map[string]bool, securityGroups []string, subnets []string, timeout time.Duration) (*ec2types.NetworkInterface, error) { stateConf := &retry.StateChangeConf{ Pending: []string{}, - Target: []string{ec2.NetworkInterfaceStatusInUse}, + Target: enum.Slice(ec2types.NetworkInterfaceStatusInUse), Refresh: statusNetworkInterfaces(ctx, conn, initialENIIds, securityGroups, subnets), Delay: 4 * time.Minute, MinTimeout: 10 * time.Second, @@ -71,21 +73,21 @@ func waitNetworkInterfaceCreated(ctx context.Context, conn *ec2.EC2, initialENII outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NetworkInterface); ok { - return output, err + if output, ok := outputRaw.(ec2types.NetworkInterface); ok { + return &output, err } return nil, err } -func statusNetworkInterfaces(ctx context.Context, conn *ec2.EC2, initialENIs map[string]bool, securityGroups []string, subnets []string) retry.StateRefreshFunc { +func statusNetworkInterfaces(ctx context.Context, conn *ec2.Client, initialENIs map[string]bool, securityGroups []string, subnets []string) retry.StateRefreshFunc { return func() (interface{}, string, error) { out, err := findNetworkInterfaces(ctx, conn, securityGroups, subnets) if err != nil { return nil, "", err } - var added *ec2.NetworkInterface + var added ec2types.NetworkInterface for _, v := range out { if _, ok := initialENIs[aws.ToString(v.NetworkInterfaceId)]; !ok { added = v @@ -93,11 +95,11 @@ func statusNetworkInterfaces(ctx context.Context, conn *ec2.EC2, initialENIs map } } - if added == nil { + if added.NetworkInterfaceId == nil { return nil, "", nil } - return added, aws.ToString(added.Status), nil + return added, string(added.Status), nil } } diff --git a/internal/service/comprehend/document_classifier.go b/internal/service/comprehend/document_classifier.go index 8e9541985fb..b6e28090b97 100644 --- a/internal/service/comprehend/document_classifier.go +++ b/internal/service/comprehend/document_classifier.go @@ -17,9 +17,8 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/ratelimit" "github.com/aws/aws-sdk-go-v2/service/comprehend" "github.com/aws/aws-sdk-go-v2/service/comprehend/types" - ec2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2" ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" @@ -422,9 +421,9 @@ func resourceDocumentClassifierDelete(ctx context.Context, d *schema.ResourceDat } ec2Conn := meta.(*conns.AWSClient).EC2Client(ctx) - networkInterfaces, err := tfec2.FindNetworkInterfacesV2(ctx, ec2Conn, &ec2_sdkv2.DescribeNetworkInterfacesInput{ + networkInterfaces, err := tfec2.FindNetworkInterfaces(ctx, ec2Conn, &ec2.DescribeNetworkInterfacesInput{ Filters: []ec2types.Filter{ - tfec2.NewFilterV2("tag:"+documentClassifierTagKey, []string{aws.ToString(v.DocumentClassifierArn)}), + tfec2.NewFilter("tag:"+documentClassifierTagKey, []string{aws.ToString(v.DocumentClassifierArn)}), }, }) if err != nil { @@ -549,7 +548,7 @@ func documentClassifierPublishVersion(ctx context.Context, conn *comprehend.Clie if in.VpcConfig != nil { g.Go(func() error { - ec2Conn := awsClient.EC2Conn(ctx) + ec2Conn := awsClient.EC2Client(ctx) enis, err := findNetworkInterfaces(waitCtx, ec2Conn, in.VpcConfig.SecurityGroupIds, in.VpcConfig.Subnets) if err != nil { diags = sdkdiag.AppendWarningf(diags, "waiting for Amazon Comprehend Document Classifier (%s) %s: %s", d.Id(), tobe, err) @@ -572,9 +571,9 @@ func documentClassifierPublishVersion(ctx context.Context, conn *comprehend.Clie modelVPCENILock.Unlock() - _, err = ec2Conn.CreateTagsWithContext(waitCtx, &ec2.CreateTagsInput{ - Resources: []*string{newENI.NetworkInterfaceId}, - Tags: []*ec2.Tag{ + _, err = ec2Conn.CreateTags(waitCtx, &ec2.CreateTagsInput{ // nosemgrep:ci.semgrep.migrate.aws-api-context + Resources: []string{aws.ToString(newENI.NetworkInterfaceId)}, + Tags: []ec2types.Tag{ { Key: aws.String(documentClassifierTagKey), Value: aws.String(d.Id()), diff --git a/internal/service/comprehend/document_classifier_test.go b/internal/service/comprehend/document_classifier_test.go index 6b05b9b0c49..ed9fa2b78d1 100644 --- a/internal/service/comprehend/document_classifier_test.go +++ b/internal/service/comprehend/document_classifier_test.go @@ -2755,7 +2755,7 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - count = length(aws_subnet.test) + count = %[2]d subnet_id = aws_subnet.test[count.index].id route_table_id = aws_route_table.test.id @@ -2799,7 +2799,7 @@ data "aws_iam_policy_document" "s3_endpoint" { ] } } -`, rName)) +`, rName, subnetCount)) } func testAccDocumentClassifierConfig_vpcConfig_Update(rName string) string { @@ -2863,7 +2863,7 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - count = length(aws_subnet.test) + count = %[2]d subnet_id = aws_subnet.test[count.index].id route_table_id = aws_route_table.test.id @@ -2907,7 +2907,7 @@ data "aws_iam_policy_document" "s3_endpoint" { ] } } -`, rName)) +`, rName, subnetCount)) } func testAccDocumentClassifierConfig_vpcConfig_None(rName string) string { diff --git a/internal/service/comprehend/entity_recognizer.go b/internal/service/comprehend/entity_recognizer.go index 05d609dbad9..e22146d6e67 100644 --- a/internal/service/comprehend/entity_recognizer.go +++ b/internal/service/comprehend/entity_recognizer.go @@ -16,9 +16,8 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/ratelimit" "github.com/aws/aws-sdk-go-v2/service/comprehend" "github.com/aws/aws-sdk-go-v2/service/comprehend/types" - ec2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2" ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" @@ -452,9 +451,9 @@ func resourceEntityRecognizerDelete(ctx context.Context, d *schema.ResourceData, } ec2Conn := meta.(*conns.AWSClient).EC2Client(ctx) - networkInterfaces, err := tfec2.FindNetworkInterfacesV2(ctx, ec2Conn, &ec2_sdkv2.DescribeNetworkInterfacesInput{ + networkInterfaces, err := tfec2.FindNetworkInterfaces(ctx, ec2Conn, &ec2.DescribeNetworkInterfacesInput{ Filters: []ec2types.Filter{ - tfec2.NewFilterV2("tag:"+entityRecognizerTagKey, []string{aws.ToString(v.EntityRecognizerArn)}), + tfec2.NewFilter("tag:"+entityRecognizerTagKey, []string{aws.ToString(v.EntityRecognizerArn)}), }, }) if err != nil { @@ -577,7 +576,7 @@ func entityRecognizerPublishVersion(ctx context.Context, conn *comprehend.Client if in.VpcConfig != nil { g.Go(func() error { - ec2Conn := awsClient.EC2Conn(ctx) + ec2Conn := awsClient.EC2Client(ctx) enis, err := findNetworkInterfaces(waitCtx, ec2Conn, in.VpcConfig.SecurityGroupIds, in.VpcConfig.Subnets) if err != nil { diags = sdkdiag.AppendWarningf(diags, "waiting for Amazon Comprehend Entity Recognizer (%s) %s: %s", d.Id(), tobe, err) @@ -600,9 +599,9 @@ func entityRecognizerPublishVersion(ctx context.Context, conn *comprehend.Client modelVPCENILock.Unlock() - _, err = ec2Conn.CreateTagsWithContext(waitCtx, &ec2.CreateTagsInput{ - Resources: []*string{newENI.NetworkInterfaceId}, - Tags: []*ec2.Tag{ + _, err = ec2Conn.CreateTags(waitCtx, &ec2.CreateTagsInput{ // nosemgrep:ci.semgrep.migrate.aws-api-context + Resources: []string{aws.ToString(newENI.NetworkInterfaceId)}, + Tags: []ec2types.Tag{ { Key: aws.String(entityRecognizerTagKey), Value: aws.String(d.Id()), diff --git a/internal/service/comprehend/entity_recognizer_test.go b/internal/service/comprehend/entity_recognizer_test.go index e856d9e59f3..b6036cb6b18 100644 --- a/internal/service/comprehend/entity_recognizer_test.go +++ b/internal/service/comprehend/entity_recognizer_test.go @@ -2081,7 +2081,7 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - count = length(aws_subnet.test) + count = %[2]d subnet_id = aws_subnet.test[count.index].id route_table_id = aws_route_table.test.id @@ -2125,7 +2125,7 @@ data "aws_iam_policy_document" "s3_endpoint" { ] } } -`, rName)) +`, rName, subnetCount)) } func testAccEntityRecognizerConfig_vpcConfig_Update(rName string) string { @@ -2202,7 +2202,7 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - count = length(aws_subnet.test) + count = %[2]d subnet_id = aws_subnet.test[count.index].id route_table_id = aws_route_table.test.id @@ -2246,7 +2246,7 @@ data "aws_iam_policy_document" "s3_endpoint" { ] } } -`, rName)) +`, rName, subnetCount)) } func testAccEntityRecognizerConfig_vpcConfig_None(rName string) string { diff --git a/internal/service/directconnect/sweep.go b/internal/service/directconnect/sweep.go index d9c884a4384..984968c62b3 100644 --- a/internal/service/directconnect/sweep.go +++ b/internal/service/directconnect/sweep.go @@ -7,10 +7,11 @@ import ( "fmt" "log" + "github.com/aws/aws-sdk-go-v2/service/ec2" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go-v2/service/secretsmanager" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directconnect" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/sweep" @@ -242,15 +243,18 @@ func sweepGatewayAssociations(region string) error { // these within the service itself so they can only be found // via AssociatedGatewayId of the EC2 Transit Gateway since the // DirectConnectGatewayId lives in the other account. - ec2conn := client.EC2Conn(ctx) + ec2conn := client.EC2Client(ctx) - err = ec2conn.DescribeTransitGatewaysPagesWithContext(ctx, &ec2.DescribeTransitGatewaysInput{}, func(page *ec2.DescribeTransitGatewaysOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := ec2.NewDescribeTransitGatewaysPaginator(ec2conn, &ec2.DescribeTransitGatewaysInput{}) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing EC2 Transit Gateways (%s): %w", region, err)) } for _, transitGateway := range page.TransitGateways { - if aws.StringValue(transitGateway.State) == ec2.TransitGatewayStateDeleted { + if transitGateway.State == ec2types.TransitGatewayStateDeleted { continue } @@ -288,12 +292,6 @@ func sweepGatewayAssociations(region string) error { sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing Direct Connect Gateway Associations (%s): %w", region, err)) } } - - return !lastPage - }) - - if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error listing EC2 Transit Gateways (%s): %w", region, err)) } err = sweep.SweepOrchestrator(ctx, sweepResources) diff --git a/internal/service/ec2/consts.go b/internal/service/ec2/consts.go index 862e8bc5468..266f3e76fea 100644 --- a/internal/service/ec2/consts.go +++ b/internal/service/ec2/consts.go @@ -5,45 +5,45 @@ package ec2 import ( awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/names" ) const ( // https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreditSpecificationRequest.html#API_CreditSpecificationRequest_Contents - CPUCreditsStandard = "standard" - CPUCreditsUnlimited = "unlimited" + cpuCreditsStandard = "standard" + cpuCreditsUnlimited = "unlimited" ) -func CPUCredits_Values() []string { +func cpuCredits_Values() []string { return []string{ - CPUCreditsStandard, - CPUCreditsUnlimited, + cpuCreditsStandard, + cpuCreditsUnlimited, } } const ( - // The AWS SDK constant ec2.FleetOnDemandAllocationStrategyLowestPrice is incorrect. - FleetOnDemandAllocationStrategyLowestPrice = "lowestPrice" + // The AWS SDK constant ec2.fleetOnDemandAllocationStrategyLowestPrice is incorrect. + fleetOnDemandAllocationStrategyLowestPrice = "lowestPrice" ) -func FleetOnDemandAllocationStrategy_Values() []string { +func fleetOnDemandAllocationStrategy_Values() []string { return append( - slices.RemoveAll(ec2.FleetOnDemandAllocationStrategy_Values(), ec2.FleetOnDemandAllocationStrategyLowestPrice), - FleetOnDemandAllocationStrategyLowestPrice, + slices.RemoveAll(enum.Values[awstypes.FleetOnDemandAllocationStrategy](), string(awstypes.FleetOnDemandAllocationStrategyLowestPrice)), + fleetOnDemandAllocationStrategyLowestPrice, ) } const ( - // The AWS SDK constant ec2.SpotAllocationStrategyLowestPrice is incorrect. - SpotAllocationStrategyLowestPrice = "lowestPrice" + // The AWS SDK constant ec2.spotAllocationStrategyLowestPrice is incorrect. + spotAllocationStrategyLowestPrice = "lowestPrice" ) -func SpotAllocationStrategy_Values() []string { +func spotAllocationStrategy_Values() []string { return append( - slices.RemoveAll(ec2.SpotAllocationStrategy_Values(), ec2.SpotAllocationStrategyLowestPrice), - SpotAllocationStrategyLowestPrice, + slices.RemoveAll(enum.Values[awstypes.SpotAllocationStrategy](), string(awstypes.SpotAllocationStrategyLowestPrice)), + spotAllocationStrategyLowestPrice, ) } @@ -70,37 +70,37 @@ const ( // See https://docs.aws.amazon.com/vm-import/latest/userguide/vmimport-image-import.html#check-import-task-status const ( - EBSSnapshotImportStateActive = "active" - EBSSnapshotImportStateDeleting = "deleting" - EBSSnapshotImportStateDeleted = "deleted" - EBSSnapshotImportStateUpdating = "updating" - EBSSnapshotImportStateValidating = "validating" - EBSSnapshotImportStateValidated = "validated" - EBSSnapshotImportStateConverting = "converting" - EBSSnapshotImportStateCompleted = "completed" + ebsSnapshotImportStateActive = "active" + ebsSnapshotImportStateDeleting = "deleting" + ebsSnapshotImportStateDeleted = "deleted" + ebsSnapshotImportStateUpdating = "updating" + ebsSnapshotImportStateValidating = "validating" + ebsSnapshotImportStateValidated = "validated" + ebsSnapshotImportStateConverting = "converting" + ebsSnapshotImportStateCompleted = "completed" ) // See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkInterface.html#API_CreateNetworkInterface_Example_2_Response. const ( - NetworkInterfaceStatusPending = "pending" + networkInterfaceStatusPending = "pending" ) // See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInternetGateways.html#API_DescribeInternetGateways_Example_1_Response. const ( - InternetGatewayAttachmentStateAvailable = "available" + internetGatewayAttachmentStateAvailable = "available" ) // See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CustomerGateway.html#API_CustomerGateway_Contents. const ( - CustomerGatewayStateAvailable = "available" - CustomerGatewayStateDeleted = "deleted" - CustomerGatewayStateDeleting = "deleting" - CustomerGatewayStatePending = "pending" + customerGatewayStateAvailable = "available" + customerGatewayStateDeleted = "deleted" + customerGatewayStateDeleting = "deleting" + customerGatewayStatePending = "pending" ) // See https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-address-attribute.html#examples. const ( - PTRUpdateStatusPending = "PENDING" + ptrUpdateStatusPending = "PENDING" ) const ( @@ -247,39 +247,39 @@ const ( ) const ( - DefaultDHCPOptionsID = "default" + defaultDHCPOptionsID = "default" ) const ( - DefaultSecurityGroupName = "default" + defaultSecurityGroupName = "default" ) const ( - DefaultSnapshotImportRoleName = "vmimport" + defaultSnapshotImportRoleName = "vmimport" ) const ( - LaunchTemplateVersionDefault = "$Default" - LaunchTemplateVersionLatest = "$Latest" + launchTemplateVersionDefault = "$Default" + launchTemplateVersionLatest = "$Latest" ) const ( - SriovNetSupportSimple = "simple" + sriovNetSupportSimple = "simple" ) const ( - TargetStorageTierStandard awstypes.TargetStorageTier = "standard" + targetStorageTierStandard awstypes.TargetStorageTier = "standard" ) const ( - OutsideIPAddressTypePrivateIPv4 = "PrivateIpv4" - OutsideIPAddressTypePublicIPv4 = "PublicIpv4" + outsideIPAddressTypePrivateIPv4 = "PrivateIpv4" + outsideIPAddressTypePublicIPv4 = "PublicIpv4" ) func outsideIPAddressType_Values() []string { return []string{ - OutsideIPAddressTypePrivateIPv4, - OutsideIPAddressTypePublicIPv4, + outsideIPAddressTypePrivateIPv4, + outsideIPAddressTypePublicIPv4, } } @@ -297,11 +297,6 @@ func (securityGroupRuleType) Values() []securityGroupRuleType { } } -const ( - ResInstance = "Instance" - ResInstanceState = "Instance State" -) - const ( gatewayIDLocal = "local" gatewayIDVPCLattice = "VpcLattice" diff --git a/internal/service/ec2/ebs_snapshot.go b/internal/service/ec2/ebs_snapshot.go index 40292970ce6..4d320a56cf9 100644 --- a/internal/service/ec2/ebs_snapshot.go +++ b/internal/service/ec2/ebs_snapshot.go @@ -91,7 +91,7 @@ func resourceEBSSnapshot() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice(enum.Slice(append(awstypes.TargetStorageTier.Values(""), TargetStorageTierStandard)...), false), + ValidateFunc: validation.StringInSlice(enum.Slice(append(awstypes.TargetStorageTier.Values(""), targetStorageTierStandard)...), false), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -118,7 +118,7 @@ func resourceEBSSnapshotCreate(ctx context.Context, d *schema.ResourceData, meta volumeID := d.Get("volume_id").(string) input := &ec2.CreateSnapshotInput{ - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeSnapshot), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeSnapshot), VolumeId: aws.String(volumeID), } @@ -207,7 +207,7 @@ func resourceEBSSnapshotRead(ctx context.Context, d *schema.ResourceData, meta i d.Set("volume_id", snapshot.VolumeId) d.Set(names.AttrVolumeSize, snapshot.VolumeSize) - setTagsOutV2(ctx, snapshot.Tags) + setTagsOut(ctx, snapshot.Tags) return diags } diff --git a/internal/service/ec2/ebs_snapshot_copy.go b/internal/service/ec2/ebs_snapshot_copy.go index 7794f203e71..8e4a3b0a275 100644 --- a/internal/service/ec2/ebs_snapshot_copy.go +++ b/internal/service/ec2/ebs_snapshot_copy.go @@ -93,7 +93,7 @@ func resourceEBSSnapshotCopy() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice(enum.Slice(append(awstypes.TargetStorageTier.Values(""), TargetStorageTierStandard)...), false), + ValidateFunc: validation.StringInSlice(enum.Slice(append(awstypes.TargetStorageTier.Values(""), targetStorageTierStandard)...), false), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -120,7 +120,7 @@ func resourceEBSSnapshotCopyCreate(ctx context.Context, d *schema.ResourceData, input := &ec2.CopySnapshotInput{ SourceRegion: aws.String(d.Get("source_region").(string)), SourceSnapshotId: aws.String(d.Get("source_snapshot_id").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeSnapshot), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeSnapshot), } if v, ok := d.GetOk(names.AttrDescription); ok { diff --git a/internal/service/ec2/ebs_snapshot_create_volume_permission.go b/internal/service/ec2/ebs_snapshot_create_volume_permission.go index 8d94d60232c..8d6c84d74f7 100644 --- a/internal/service/ec2/ebs_snapshot_create_volume_permission.go +++ b/internal/service/ec2/ebs_snapshot_create_volume_permission.go @@ -57,7 +57,7 @@ func resourceSnapshotCreateVolumePermissionCreate(ctx context.Context, d *schema snapshotID := d.Get(names.AttrSnapshotID).(string) accountID := d.Get(names.AttrAccountID).(string) - id := EBSSnapshotCreateVolumePermissionCreateResourceID(snapshotID, accountID) + id := ebsSnapshotCreateVolumePermissionCreateResourceID(snapshotID, accountID) input := &ec2.ModifySnapshotAttributeInput{ Attribute: awstypes.SnapshotAttributeNameCreateVolumePermission, CreateVolumePermission: &awstypes.CreateVolumePermissionModifications{ @@ -91,10 +91,9 @@ func resourceSnapshotCreateVolumePermissionRead(ctx context.Context, d *schema.R var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - snapshotID, accountID, err := EBSSnapshotCreateVolumePermissionParseResourceID(d.Id()) - + snapshotID, accountID, err := ebsSnapshotCreateVolumePermissionParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading EBS Snapshot CreateVolumePermission (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } _, err = findCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx, conn, snapshotID, accountID) @@ -116,10 +115,9 @@ func resourceSnapshotCreateVolumePermissionDelete(ctx context.Context, d *schema var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - snapshotID, accountID, err := EBSSnapshotCreateVolumePermissionParseResourceID(d.Id()) - + snapshotID, accountID, err := ebsSnapshotCreateVolumePermissionParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting EBS Snapshot CreateVolumePermission (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } log.Printf("[DEBUG] Deleting EBS Snapshot CreateVolumePermission: %s", d.Id()) @@ -174,14 +172,14 @@ func resourceSnapshotCreateVolumePermissionCustomizeDiff(ctx context.Context, di const ebsSnapshotCreateVolumePermissionIDSeparator = "-" -func EBSSnapshotCreateVolumePermissionCreateResourceID(snapshotID, accountID string) string { +func ebsSnapshotCreateVolumePermissionCreateResourceID(snapshotID, accountID string) string { parts := []string{snapshotID, accountID} id := strings.Join(parts, ebsSnapshotCreateVolumePermissionIDSeparator) return id } -func EBSSnapshotCreateVolumePermissionParseResourceID(id string) (string, string, error) { +func ebsSnapshotCreateVolumePermissionParseResourceID(id string) (string, string, error) { parts := strings.SplitN(id, ebsSnapshotCreateVolumePermissionIDSeparator, 3) if len(parts) != 3 || parts[0] != "snap" || parts[1] == "" || parts[2] == "" { diff --git a/internal/service/ec2/ebs_snapshot_create_volume_permission_test.go b/internal/service/ec2/ebs_snapshot_create_volume_permission_test.go index e45105ba0ef..2dbcd9090e8 100644 --- a/internal/service/ec2/ebs_snapshot_create_volume_permission_test.go +++ b/internal/service/ec2/ebs_snapshot_create_volume_permission_test.go @@ -98,13 +98,7 @@ func testAccCheckSnapshotCreateVolumePermissionDestroy(ctx context.Context) reso continue } - snapshotID, accountID, err := tfec2.EBSSnapshotCreateVolumePermissionParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx, conn, snapshotID, accountID) + _, err := tfec2.FindCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx, conn, rs.Primary.Attributes[names.AttrSnapshotID], rs.Primary.Attributes[names.AttrAccountID]) if tfresource.NotFound(err) { continue @@ -128,19 +122,9 @@ func testAccSnapshotCreateVolumePermissionExists(ctx context.Context, n string) return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No EBS Snapshot CreateVolumePermission ID is set") - } - - snapshotID, accountID, err := tfec2.EBSSnapshotCreateVolumePermissionParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - _, err = tfec2.FindCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx, conn, snapshotID, accountID) + _, err := tfec2.FindCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx, conn, rs.Primary.Attributes[names.AttrSnapshotID], rs.Primary.Attributes[names.AttrAccountID]) return err } diff --git a/internal/service/ec2/ebs_snapshot_data_source.go b/internal/service/ec2/ebs_snapshot_data_source.go index c8f45c72348..dcde24d0660 100644 --- a/internal/service/ec2/ebs_snapshot_data_source.go +++ b/internal/service/ec2/ebs_snapshot_data_source.go @@ -129,7 +129,7 @@ func dataSourceEBSSnapshotRead(ctx context.Context, d *schema.ResourceData, meta input.SnapshotIds = flex.ExpandStringValueList(v.([]interface{})) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -181,7 +181,7 @@ func dataSourceEBSSnapshotRead(ctx context.Context, d *schema.ResourceData, meta d.Set("volume_id", snapshot.VolumeId) d.Set(names.AttrVolumeSize, snapshot.VolumeSize) - setTagsOutV2(ctx, snapshot.Tags) + setTagsOut(ctx, snapshot.Tags) return diags } diff --git a/internal/service/ec2/ebs_snapshot_ids_data_source.go b/internal/service/ec2/ebs_snapshot_ids_data_source.go index 228c5e39e86..697cbb9d7cc 100644 --- a/internal/service/ec2/ebs_snapshot_ids_data_source.go +++ b/internal/service/ec2/ebs_snapshot_ids_data_source.go @@ -62,7 +62,7 @@ func dataSourceEBSSnapshotIDsRead(ctx context.Context, d *schema.ResourceData, m input.RestorableByUserIds = flex.ExpandStringValueList(v.([]interface{})) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/ebs_snapshot_import.go b/internal/service/ec2/ebs_snapshot_import.go index e9c6f70a166..3efc43a25fa 100644 --- a/internal/service/ec2/ebs_snapshot_import.go +++ b/internal/service/ec2/ebs_snapshot_import.go @@ -168,13 +168,13 @@ func resourceEBSSnapshotImport() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: DefaultSnapshotImportRoleName, + Default: defaultSnapshotImportRoleName, }, "storage_tier": { Type: schema.TypeString, Optional: true, Computed: true, - ValidateFunc: validation.StringInSlice(enum.Slice(append(awstypes.TargetStorageTier.Values(""), TargetStorageTierStandard)...), false), + ValidateFunc: validation.StringInSlice(enum.Slice(append(awstypes.TargetStorageTier.Values(""), targetStorageTierStandard)...), false), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -200,7 +200,7 @@ func resourceEBSSnapshotImportCreate(ctx context.Context, d *schema.ResourceData input := &ec2.ImportSnapshotInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeImportSnapshotTask), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeImportSnapshotTask), } if v, ok := d.GetOk("client_data"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { @@ -246,7 +246,7 @@ func resourceEBSSnapshotImportCreate(ctx context.Context, d *schema.ResourceData d.SetId(aws.ToString(output.SnapshotId)) - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EBS Snapshot Import (%s) tags: %s", d.Id(), err) } @@ -302,7 +302,7 @@ func resourceEBSSnapshotImportRead(ctx context.Context, d *schema.ResourceData, d.Set("storage_tier", snapshot.StorageTier) d.Set(names.AttrVolumeSize, snapshot.VolumeSize) - setTagsOutV2(ctx, snapshot.Tags) + setTagsOut(ctx, snapshot.Tags) return diags } diff --git a/internal/service/ec2/ebs_volume.go b/internal/service/ec2/ebs_volume.go index e181397d9ab..4751830e03a 100644 --- a/internal/service/ec2/ebs_volume.go +++ b/internal/service/ec2/ebs_volume.go @@ -133,7 +133,7 @@ func resourceEBSVolumeCreate(ctx context.Context, d *schema.ResourceData, meta i input := &ec2.CreateVolumeInput{ AvailabilityZone: aws.String(d.Get(names.AttrAvailabilityZone).(string)), ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeVolume), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVolume), } if value, ok := d.GetOk(names.AttrEncrypted); ok { @@ -222,7 +222,7 @@ func resourceEBSVolumeRead(ctx context.Context, d *schema.ResourceData, meta int d.Set(names.AttrThroughput, volume.Throughput) d.Set(names.AttrType, volume.VolumeType) - setTagsOutV2(ctx, volume.Tags) + setTagsOut(ctx, volume.Tags) return diags } diff --git a/internal/service/ec2/ebs_volume_attachment.go b/internal/service/ec2/ebs_volume_attachment.go index 5c0c793d259..bf131253d6d 100644 --- a/internal/service/ec2/ebs_volume_attachment.go +++ b/internal/service/ec2/ebs_volume_attachment.go @@ -106,7 +106,7 @@ func resourceVolumeAttachmentCreate(ctx context.Context, d *schema.ResourceData, // This handles the situation where the instance is created by // a spot request and whilst the request has been fulfilled the // instance is not running yet. - if _, err := waitVolumeAttachmentInstanceReady(ctx, conn, instanceID, InstanceReadyTimeout); err != nil { + if _, err := waitVolumeAttachmentInstanceReady(ctx, conn, instanceID, instanceReadyTimeout); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Instance (%s) to be ready: %s", instanceID, err) } @@ -169,7 +169,7 @@ func resourceVolumeAttachmentDelete(ctx context.Context, d *schema.ResourceData, volumeID := d.Get("volume_id").(string) if _, ok := d.GetOk("stop_instance_before_detaching"); ok { - if err := stopVolumeAttachmentInstance(ctx, conn, instanceID, false, InstanceStopTimeout); err != nil { + if err := stopVolumeAttachmentInstance(ctx, conn, instanceID, false, instanceStopTimeout); err != nil { return sdkdiag.AppendErrorf(diags, "deleting EBS Volume (%s) Attachment (%s): %s", volumeID, instanceID, err) } } @@ -210,7 +210,7 @@ func volumeAttachmentID(name, volumeID, instanceID string) string { func findVolumeAttachment(ctx context.Context, conn *ec2.Client, volumeID, instanceID, deviceName string) (*awstypes.VolumeAttachment, error) { input := &ec2.DescribeVolumesInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "attachment.device": deviceName, "attachment.instance-id": instanceID, }), diff --git a/internal/service/ec2/ebs_volume_data_source.go b/internal/service/ec2/ebs_volume_data_source.go index 9c870431c42..cf25ee99bc4 100644 --- a/internal/service/ec2/ebs_volume_data_source.go +++ b/internal/service/ec2/ebs_volume_data_source.go @@ -98,7 +98,7 @@ func dataSourceEBSVolumeRead(ctx context.Context, d *schema.ResourceData, meta i input := &ec2.DescribeVolumesInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -154,7 +154,7 @@ func dataSourceEBSVolumeRead(ctx context.Context, d *schema.ResourceData, meta i d.Set("volume_id", volume.VolumeId) d.Set(names.AttrVolumeType, volume.VolumeType) - setTagsOutV2(ctx, volume.Tags) + setTagsOut(ctx, volume.Tags) return diags } diff --git a/internal/service/ec2/ebs_volume_test.go b/internal/service/ec2/ebs_volume_test.go index 130ad1fe014..05df4248c2b 100644 --- a/internal/service/ec2/ebs_volume_test.go +++ b/internal/service/ec2/ebs_volume_test.go @@ -965,7 +965,7 @@ func testAccCheckVolumeFinalSnapshotExists(ctx context.Context, v *awstypes.Volu conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSnapshotsInput{ - Filters: tfec2.NewAttributeFilterListV2(map[string]string{ + Filters: tfec2.NewAttributeFilterList(map[string]string{ "volume-id": aws.ToString(v.VolumeId), names.AttrStatus: string(awstypes.SnapshotStateCompleted), }), diff --git a/internal/service/ec2/ebs_volumes_data_source.go b/internal/service/ec2/ebs_volumes_data_source.go index e6bde642856..1d9b4037561 100644 --- a/internal/service/ec2/ebs_volumes_data_source.go +++ b/internal/service/ec2/ebs_volumes_data_source.go @@ -44,11 +44,11 @@ func dataSourceEBSVolumesRead(ctx context.Context, d *schema.ResourceData, meta input := &ec2.DescribeVolumesInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/ec2_ami.go b/internal/service/ec2/ec2_ami.go index ba9a31d33b3..db94edb7017 100644 --- a/internal/service/ec2/ec2_ami.go +++ b/internal/service/ec2/ec2_ami.go @@ -267,7 +267,7 @@ func resourceAMI() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: SriovNetSupportSimple, + Default: sriovNetSupportSimple, }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -370,7 +370,7 @@ func resourceAMICreate(ctx context.Context, d *schema.ResourceData, meta interfa d.SetId(aws.ToString(output.ImageId)) - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EC2 AMI (%s) tags: %s", d.Id(), err) } @@ -459,7 +459,7 @@ func resourceAMIRead(ctx context.Context, d *schema.ResourceData, meta interface return sdkdiag.AppendErrorf(diags, "setting ephemeral_block_device: %s", err) } - setTagsOutV2(ctx, image.Tags) + setTagsOut(ctx, image.Tags) return diags } diff --git a/internal/service/ec2/ec2_ami_copy.go b/internal/service/ec2/ec2_ami_copy.go index 35544e282c3..9dc9148fd69 100644 --- a/internal/service/ec2/ec2_ami_copy.go +++ b/internal/service/ec2/ec2_ami_copy.go @@ -302,7 +302,7 @@ func resourceAMICopyCreate(ctx context.Context, d *schema.ResourceData, meta int d.SetId(aws.ToString(output.ImageId)) d.Set("manage_ebs_snapshots", true) - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EC2 AMI (%s) tags: %s", d.Id(), err) } diff --git a/internal/service/ec2/ec2_ami_data_source.go b/internal/service/ec2/ec2_ami_data_source.go index e019d699312..0020ce696be 100644 --- a/internal/service/ec2/ec2_ami_data_source.go +++ b/internal/service/ec2/ec2_ami_data_source.go @@ -242,7 +242,7 @@ func dataSourceAMIRead(ctx context.Context, d *schema.ResourceData, meta interfa } if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } if v, ok := d.GetOk("owners"); ok && len(v.([]interface{})) > 0 { @@ -339,7 +339,7 @@ func dataSourceAMIRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("usage_operation", image.UsageOperation) d.Set("virtualization_type", image.VirtualizationType) - setTagsOutV2(ctx, image.Tags) + setTagsOut(ctx, image.Tags) return diags } diff --git a/internal/service/ec2/ec2_ami_from_instance.go b/internal/service/ec2/ec2_ami_from_instance.go index 5260732e272..be928cdaf77 100644 --- a/internal/service/ec2/ec2_ami_from_instance.go +++ b/internal/service/ec2/ec2_ami_from_instance.go @@ -263,7 +263,7 @@ func resourceAMIFromInstanceCreate(ctx context.Context, d *schema.ResourceData, InstanceId: aws.String(instanceID), Name: aws.String(name), NoReboot: aws.Bool(d.Get("snapshot_without_reboot").(bool)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeImage), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeImage), } output, err := conn.CreateImage(ctx, input) diff --git a/internal/service/ec2/ec2_ami_ids_data_source.go b/internal/service/ec2/ec2_ami_ids_data_source.go index c596760499b..93e9eaeb2ae 100644 --- a/internal/service/ec2/ec2_ami_ids_data_source.go +++ b/internal/service/ec2/ec2_ami_ids_data_source.go @@ -86,7 +86,7 @@ func dataSourceAMIIDsRead(ctx context.Context, d *schema.ResourceData, meta inte } if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } images, err := findImages(ctx, conn, input) diff --git a/internal/service/ec2/ec2_ami_ids_data_source_test.go b/internal/service/ec2/ec2_ami_ids_data_source_test.go index b1307c336ed..f69065a11ee 100644 --- a/internal/service/ec2/ec2_ami_ids_data_source_test.go +++ b/internal/service/ec2/ec2_ami_ids_data_source_test.go @@ -6,6 +6,7 @@ package ec2_test import ( "fmt" "testing" + "time" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -35,25 +36,28 @@ func TestAccEC2AMIIDsDataSource_sorted(t *testing.T) { ctx := acctest.Context(t) datasourceName := "data.aws_ami_ids.test" + date := time.Now().UTC().AddDate(0, -2, 0) + creationDate := fmt.Sprintf("%d-%02d-*", date.Year(), date.Month()) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, Steps: []resource.TestStep{ { - Config: testAccAMIIDsDataSourceConfig_sorted(false), + Config: testAccAMIIDsDataSourceConfig_sorted(false, creationDate), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "ids.#", acctest.Ct2), - resource.TestCheckResourceAttrPair(datasourceName, "ids.0", "data.aws_ami.test2", names.AttrID), - resource.TestCheckResourceAttrPair(datasourceName, "ids.1", "data.aws_ami.test1", names.AttrID), + resource.TestCheckResourceAttrPair(datasourceName, "ids.0", "data.aws_ami.test1", names.AttrID), + resource.TestCheckResourceAttrPair(datasourceName, "ids.1", "data.aws_ami.test2", names.AttrID), ), }, { - Config: testAccAMIIDsDataSourceConfig_sorted(true), + Config: testAccAMIIDsDataSourceConfig_sorted(true, creationDate), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(datasourceName, "ids.#", acctest.Ct2), - resource.TestCheckResourceAttrPair(datasourceName, "ids.0", "data.aws_ami.test1", names.AttrID), - resource.TestCheckResourceAttrPair(datasourceName, "ids.1", "data.aws_ami.test2", names.AttrID), + resource.TestCheckResourceAttrPair(datasourceName, "ids.0", "data.aws_ami.test2", names.AttrID), + resource.TestCheckResourceAttrPair(datasourceName, "ids.1", "data.aws_ami.test1", names.AttrID), ), }, }, @@ -90,23 +94,30 @@ data "aws_ami_ids" "test" { } ` -func testAccAMIIDsDataSourceConfig_sorted(sortAscending bool) string { +func testAccAMIIDsDataSourceConfig_sorted(sortAscending bool, creationDate string) string { return fmt.Sprintf(` data "aws_ami" "test1" { - owners = ["amazon"] + owners = ["amazon"] + most_recent = true filter { name = "name" - values = ["al2023-ami-2023.4.20240401.1-kernel-6.1-x86_64"] + values = ["al2023-ami-2023.*-x86_64"] } } data "aws_ami" "test2" { - owners = ["amazon"] + owners = ["amazon"] + most_recent = true filter { name = "name" - values = ["al2023-ami-2023.4.20240513.0-kernel-6.1-x86_64"] + values = ["al2023-ami-2023.*-x86_64"] + } + + filter { + name = "creation-date" + values = [%[2]q] } } @@ -120,7 +131,7 @@ data "aws_ami_ids" "test" { sort_ascending = %[1]t } -`, sortAscending) +`, sortAscending, creationDate) } func testAccAMIIDsDataSourceConfig_includeDeprecated(includeDeprecated bool) string { diff --git a/internal/service/ec2/ec2_ami_launch_permission.go b/internal/service/ec2/ec2_ami_launch_permission.go index eb2a858cd65..80e4531ded9 100644 --- a/internal/service/ec2/ec2_ami_launch_permission.go +++ b/internal/service/ec2/ec2_ami_launch_permission.go @@ -83,7 +83,7 @@ func resourceAMILaunchPermissionCreate(ctx context.Context, d *schema.ResourceDa group := d.Get("group").(string) organizationARN := d.Get("organization_arn").(string) organizationalUnitARN := d.Get("organizational_unit_arn").(string) - id := AMILaunchPermissionCreateResourceID(imageID, accountID, group, organizationARN, organizationalUnitARN) + id := amiLaunchPermissionCreateResourceID(imageID, accountID, group, organizationARN, organizationalUnitARN) input := &ec2.ModifyImageAttributeInput{ Attribute: aws.String(string(awstypes.ImageAttributeNameLaunchPermission)), ImageId: aws.String(imageID), @@ -92,7 +92,6 @@ func resourceAMILaunchPermissionCreate(ctx context.Context, d *schema.ResourceDa }, } - log.Printf("[DEBUG] Creating AMI Launch Permission: %s", d.Id()) _, err := conn.ModifyImageAttribute(ctx, input) if err != nil { @@ -106,11 +105,9 @@ func resourceAMILaunchPermissionCreate(ctx context.Context, d *schema.ResourceDa func resourceAMILaunchPermissionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - imageID, accountID, group, organizationARN, organizationalUnitARN, err := AMILaunchPermissionParseResourceID(d.Id()) - + imageID, accountID, group, organizationARN, organizationalUnitARN, err := amiLaunchPermissionParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -138,11 +135,9 @@ func resourceAMILaunchPermissionRead(ctx context.Context, d *schema.ResourceData func resourceAMILaunchPermissionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - imageID, accountID, group, organizationARN, organizationalUnitARN, err := AMILaunchPermissionParseResourceID(d.Id()) - + imageID, accountID, group, organizationARN, organizationalUnitARN, err := amiLaunchPermissionParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -179,24 +174,24 @@ func resourceAMILaunchPermissionImport(ctx context.Context, d *schema.ResourceDa if permissionID, imageID := strings.Join(parts[:n-1], importIDSeparator), parts[n-1]; permissionID != "" && imageID != "" { if regexache.MustCompile(`^\d{12}$`).MatchString(permissionID) { // AWS account ID. - d.SetId(AMILaunchPermissionCreateResourceID(imageID, permissionID, "", "", "")) + d.SetId(amiLaunchPermissionCreateResourceID(imageID, permissionID, "", "", "")) ok = true } else if arn.IsARN(permissionID) { if v, _ := arn.Parse(permissionID); v.Service == "organizations" { // See https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsorganizations.html#awsorganizations-resources-for-iam-policies. if strings.HasPrefix(v.Resource, "organization/") { // Organization ARN. - d.SetId(AMILaunchPermissionCreateResourceID(imageID, "", "", permissionID, "")) + d.SetId(amiLaunchPermissionCreateResourceID(imageID, "", "", permissionID, "")) ok = true } else if strings.HasPrefix(v.Resource, "ou/") { // Organizational unit ARN. - d.SetId(AMILaunchPermissionCreateResourceID(imageID, "", "", "", permissionID)) + d.SetId(amiLaunchPermissionCreateResourceID(imageID, "", "", "", permissionID)) ok = true } } } else { // Group name. - d.SetId(AMILaunchPermissionCreateResourceID(imageID, "", permissionID, "", "")) + d.SetId(amiLaunchPermissionCreateResourceID(imageID, "", permissionID, "", "")) ok = true } } @@ -209,28 +204,6 @@ func resourceAMILaunchPermissionImport(ctx context.Context, d *schema.ResourceDa return []*schema.ResourceData{d}, nil } -func expandLaunchPermissions(accountID, group, organizationARN, organizationalUnitARN string) []awstypes.LaunchPermission { - apiObject := awstypes.LaunchPermission{} - - if accountID != "" { - apiObject.UserId = aws.String(accountID) - } - - if group != "" { - apiObject.Group = awstypes.PermissionGroup(group) - } - - if organizationARN != "" { - apiObject.OrganizationArn = aws.String(organizationARN) - } - - if organizationalUnitARN != "" { - apiObject.OrganizationalUnitArn = aws.String(organizationalUnitARN) - } - - return []awstypes.LaunchPermission{apiObject} -} - const ( amiLaunchPermissionIDSeparator = "-" amiLaunchPermissionIDGroupIndicator = "group" @@ -238,7 +211,7 @@ const ( amiLaunchPermissionIDOrganizationalUnitIndicator = "ou" ) -func AMILaunchPermissionCreateResourceID(imageID, accountID, group, organizationARN, organizationalUnitARN string) string { +func amiLaunchPermissionCreateResourceID(imageID, accountID, group, organizationARN, organizationalUnitARN string) string { parts := []string{imageID} if accountID != "" { @@ -256,7 +229,7 @@ func AMILaunchPermissionCreateResourceID(imageID, accountID, group, organization return id } -func AMILaunchPermissionParseResourceID(id string) (string, string, string, string, string, error) { +func amiLaunchPermissionParseResourceID(id string) (string, string, string, string, string, error) { parts := strings.Split(id, amiLaunchPermissionIDSeparator) switch { @@ -275,3 +248,25 @@ func AMILaunchPermissionParseResourceID(id string) (string, string, string, stri return "", "", "", "", "", fmt.Errorf("unexpected format for ID (%[1]s), expected IMAGE-ID%[2]sACCOUNT-ID or IMAGE-ID%[2]s%[3]s%[2]sGROUP-NAME or IMAGE-ID%[2]s%[4]s%[2]sORGANIZATION-ARN or IMAGE-ID%[2]s%[5]s%[2]sORGANIZATIONAL-UNIT-ARN", id, amiLaunchPermissionIDSeparator, amiLaunchPermissionIDGroupIndicator, amiLaunchPermissionIDOrganizationIndicator, amiLaunchPermissionIDOrganizationalUnitIndicator) } + +func expandLaunchPermissions(accountID, group, organizationARN, organizationalUnitARN string) []awstypes.LaunchPermission { + apiObject := awstypes.LaunchPermission{} + + if accountID != "" { + apiObject.UserId = aws.String(accountID) + } + + if group != "" { + apiObject.Group = awstypes.PermissionGroup(group) + } + + if organizationARN != "" { + apiObject.OrganizationArn = aws.String(organizationARN) + } + + if organizationalUnitARN != "" { + apiObject.OrganizationalUnitArn = aws.String(organizationalUnitARN) + } + + return []awstypes.LaunchPermission{apiObject} +} diff --git a/internal/service/ec2/ec2_ami_launch_permission_test.go b/internal/service/ec2/ec2_ami_launch_permission_test.go index 39aca898b4a..46c22471501 100644 --- a/internal/service/ec2/ec2_ami_launch_permission_test.go +++ b/internal/service/ec2/ec2_ami_launch_permission_test.go @@ -222,19 +222,9 @@ func testAccCheckAMILaunchPermissionExists(ctx context.Context, n string) resour return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No AMI Launch Permission ID is set") - } - - imageID, accountID, group, organizationARN, organizationalUnitARN, err := tfec2.AMILaunchPermissionParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - _, err = tfec2.FindImageLaunchPermission(ctx, conn, imageID, accountID, group, organizationARN, organizationalUnitARN) + _, err := tfec2.FindImageLaunchPermission(ctx, conn, rs.Primary.Attributes["image_id"], rs.Primary.Attributes[names.AttrAccountID], rs.Primary.Attributes["group"], rs.Primary.Attributes["organization_arn"], rs.Primary.Attributes["organizational_unit_arn"]) return err } @@ -249,13 +239,7 @@ func testAccCheckAMILaunchPermissionDestroy(ctx context.Context) resource.TestCh continue } - imageID, accountID, group, organizationARN, organizationalUnitARN, err := tfec2.AMILaunchPermissionParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindImageLaunchPermission(ctx, conn, imageID, accountID, group, organizationARN, organizationalUnitARN) + _, err := tfec2.FindImageLaunchPermission(ctx, conn, rs.Primary.Attributes["image_id"], rs.Primary.Attributes[names.AttrAccountID], rs.Primary.Attributes["group"], rs.Primary.Attributes["organization_arn"], rs.Primary.Attributes["organizational_unit_arn"]) if tfresource.NotFound(err) { continue @@ -310,13 +294,13 @@ resource "aws_ami_copy" "test" { source_ami_id = data.aws_ami.amzn2-ami-minimal-hvm-ebs-x86_64.id source_ami_region = data.aws_region.current.name deprecation_time = data.aws_ami.amzn2-ami-minimal-hvm-ebs-x86_64.deprecation_time + + depends_on = [aws_ec2_image_block_public_access.test] } resource "aws_ami_launch_permission" "test" { group = "all" image_id = aws_ami_copy.test.id - - depends_on = [aws_ec2_image_block_public_access.test] } `, rName, state)) } diff --git a/internal/service/ec2/ec2_availability_zone_data_source.go b/internal/service/ec2/ec2_availability_zone_data_source.go index 3ab12866966..7bb7ffb1483 100644 --- a/internal/service/ec2/ec2_availability_zone_data_source.go +++ b/internal/service/ec2/ec2_availability_zone_data_source.go @@ -102,13 +102,13 @@ func dataSourceAvailabilityZoneRead(ctx context.Context, d *schema.ResourceData, input.ZoneNames = []string{v.(string)} } - input.Filters = newAttributeFilterListV2( + input.Filters = newAttributeFilterList( map[string]string{ names.AttrState: d.Get(names.AttrState).(string), }, ) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/ec2_availability_zone_data_source_test.go b/internal/service/ec2/ec2_availability_zone_data_source_test.go index 9f998eecf12..c62c0b288b7 100644 --- a/internal/service/ec2/ec2_availability_zone_data_source_test.go +++ b/internal/service/ec2/ec2_availability_zone_data_source_test.go @@ -197,7 +197,7 @@ func testAccPreCheckLocalZoneAvailable(ctx context.Context, t *testing.T, groupN conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeAvailabilityZonesInput{ - Filters: tfec2.NewAttributeFilterListV2(map[string]string{ + Filters: tfec2.NewAttributeFilterList(map[string]string{ "zone-type": "local-zone", "opt-in-status": "opted-in", }), diff --git a/internal/service/ec2/ec2_availability_zones_data_source.go b/internal/service/ec2/ec2_availability_zones_data_source.go index 28a96f9ea8a..3ddcbde1448 100644 --- a/internal/service/ec2/ec2_availability_zones_data_source.go +++ b/internal/service/ec2/ec2_availability_zones_data_source.go @@ -91,7 +91,7 @@ func dataSourceAvailabilityZonesRead(ctx context.Context, d *schema.ResourceData } if filters, filtersOk := d.GetOk(names.AttrFilter); filtersOk { - request.Filters = append(request.Filters, newCustomFilterListV2( + request.Filters = append(request.Filters, newCustomFilterList( filters.(*schema.Set), )...) } diff --git a/internal/service/ec2/ec2_capacity_block_offering_data_source.go b/internal/service/ec2/ec2_capacity_block_offering_data_source.go index b0b2a863aa7..d40d6a79307 100644 --- a/internal/service/ec2/ec2_capacity_block_offering_data_source.go +++ b/internal/service/ec2/ec2_capacity_block_offering_data_source.go @@ -5,36 +5,34 @@ package ec2 import ( "context" + "fmt" "github.com/aws/aws-sdk-go-v2/service/ec2" - awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/framework" fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) // @FrameworkDataSource("aws_ec2_capacity_block_offering", name="Capacity Block Offering") -func newDataSourceCapacityBlockOffering(_ context.Context) (datasource.DataSourceWithConfigure, error) { - d := &dataSourceCapacityBlockOffering{} +func newCapacityBlockOfferingDataSource(_ context.Context) (datasource.DataSourceWithConfigure, error) { + d := &capacityBlockOfferingDataSource{} return d, nil } -type dataSourceCapacityBlockOffering struct { +type capacityBlockOfferingDataSource struct { framework.DataSourceWithConfigure } -func (d *dataSourceCapacityBlockOffering) Metadata(_ context.Context, _ datasource.MetadataRequest, response *datasource.MetadataResponse) { +func (*capacityBlockOfferingDataSource) Metadata(_ context.Context, _ datasource.MetadataRequest, response *datasource.MetadataResponse) { response.TypeName = "aws_ec2_capacity_block_offering" } -func (d *dataSourceCapacityBlockOffering) Schema(_ context.Context, _ datasource.SchemaRequest, response *datasource.SchemaResponse) { +func (d *capacityBlockOfferingDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, response *datasource.SchemaResponse) { response.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ names.AttrAvailabilityZone: schema.StringAttribute{ @@ -73,39 +71,30 @@ func (d *dataSourceCapacityBlockOffering) Schema(_ context.Context, _ datasource } } -const ( - DSNameCapacityBlockOffering = "Capacity Block Offering" -) - -func (d *dataSourceCapacityBlockOffering) Read(ctx context.Context, request datasource.ReadRequest, response *datasource.ReadResponse) { - conn := d.Meta().EC2Client(ctx) - var data dataSourceCapacityBlockOfferingData - +func (d *capacityBlockOfferingDataSource) Read(ctx context.Context, request datasource.ReadRequest, response *datasource.ReadResponse) { + var data capacityBlockOfferingDataSourceModel response.Diagnostics.Append(request.Config.Get(ctx, &data)...) - if response.Diagnostics.HasError() { return } + conn := d.Meta().EC2Client(ctx) + input := &ec2.DescribeCapacityBlockOfferingsInput{} response.Diagnostics.Append(fwflex.Expand(ctx, data, input)...) - if response.Diagnostics.HasError() { return } - output, err := findCapacityBLockOffering(ctx, conn, input) + output, err := findCapacityBlockOffering(ctx, conn, input) if err != nil { - response.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionReading, DSNameCapacityBlockOffering, data.InstanceType.String(), err), - err.Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("reading EC2 Capacity Block Offering (%s)", data.InstanceType.ValueString()), err.Error()) + return } response.Diagnostics.Append(fwflex.Flatten(ctx, output, &data)...) - if response.Diagnostics.HasError() { return } @@ -113,7 +102,7 @@ func (d *dataSourceCapacityBlockOffering) Read(ctx context.Context, request data response.Diagnostics.Append(response.State.Set(ctx, &data)...) } -type dataSourceCapacityBlockOfferingData struct { +type capacityBlockOfferingDataSourceModel struct { AvailabilityZone types.String `tfsdk:"availability_zone"` CapacityDurationHours types.Int64 `tfsdk:"capacity_duration_hours"` CurrencyCode types.String `tfsdk:"currency_code"` @@ -125,21 +114,3 @@ type dataSourceCapacityBlockOfferingData struct { Tenancy types.String `tfsdk:"tenancy"` UpfrontFee types.String `tfsdk:"upfront_fee"` } - -func findCapacityBLockOffering(ctx context.Context, conn *ec2.Client, in *ec2.DescribeCapacityBlockOfferingsInput) (*awstypes.CapacityBlockOffering, error) { - output, err := conn.DescribeCapacityBlockOfferings(ctx, in) - - if err != nil { - return nil, err - } - - if output == nil || len(output.CapacityBlockOfferings) == 0 { - return nil, tfresource.NewEmptyResultError(in) - } - - if len(output.CapacityBlockOfferings) > 1 { - return nil, tfresource.NewTooManyResultsError(len(output.CapacityBlockOfferings), in) - } - - return tfresource.AssertSingleValueResult(output.CapacityBlockOfferings) -} diff --git a/internal/service/ec2/ec2_capacity_block_reservation.go b/internal/service/ec2/ec2_capacity_block_reservation.go index d7955409e28..6a9c0292d97 100644 --- a/internal/service/ec2/ec2_capacity_block_reservation.go +++ b/internal/service/ec2/ec2_capacity_block_reservation.go @@ -5,15 +5,14 @@ package ec2 import ( "context" - "errors" + "fmt" "time" - "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework-timetypes/timetypes" + "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" @@ -21,9 +20,6 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/create" - "github.com/hashicorp/terraform-provider-aws/internal/enum" "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" @@ -36,26 +32,26 @@ import ( // @FrameworkResource("aws_ec2_capacity_block_reservation",name="Capacity Block Reservation") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func newResourceCapacityBlockReservation(context.Context) (resource.ResourceWithConfigure, error) { - r := &resourceCapacityBlockReservation{} +func newCapacityBlockReservationResource(context.Context) (resource.ResourceWithConfigure, error) { + r := &capacityBlockReservationResource{} r.SetDefaultCreateTimeout(40 * time.Minute) return r, nil } -type resourceCapacityBlockReservation struct { +type capacityBlockReservationResource struct { framework.ResourceWithConfigure framework.WithTimeouts framework.WithImportByID - framework.WithNoOpUpdate[resourceCapacityBlockReservationData] + framework.WithNoOpUpdate[capacityBlockReservationReservationModel] framework.WithNoOpDelete } -func (r *resourceCapacityBlockReservation) Metadata(_ context.Context, _ resource.MetadataRequest, response *resource.MetadataResponse) { +func (*capacityBlockReservationResource) Metadata(_ context.Context, _ resource.MetadataRequest, response *resource.MetadataResponse) { response.TypeName = "aws_ec2_capacity_block_reservation" } -func (r *resourceCapacityBlockReservation) Schema(ctx context.Context, _ resource.SchemaRequest, response *resource.SchemaResponse) { +func (r *capacityBlockReservationResource) Schema(ctx context.Context, _ resource.SchemaRequest, response *resource.SchemaResponse) { s := schema.Schema{ Attributes: map[string]schema.Attribute{ names.AttrARN: schema.StringAttribute{ @@ -168,97 +164,77 @@ func (r *resourceCapacityBlockReservation) Schema(ctx context.Context, _ resourc response.Schema = s } -const ( - ResNameCapacityBlockReservation = "Capacity Block Reservation" -) - -func (r *resourceCapacityBlockReservation) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) { - conn := r.Meta().EC2Client(ctx) - var plan resourceCapacityBlockReservationData - - response.Diagnostics.Append(request.Plan.Get(ctx, &plan)...) - +func (r *capacityBlockReservationResource) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) { + var data capacityBlockReservationReservationModel + response.Diagnostics.Append(request.Plan.Get(ctx, &data)...) if response.Diagnostics.HasError() { return } - input := &ec2.PurchaseCapacityBlockInput{} - response.Diagnostics.Append(fwflex.Expand(ctx, plan, input)...) + conn := r.Meta().EC2Client(ctx) + input := &ec2.PurchaseCapacityBlockInput{} + response.Diagnostics.Append(fwflex.Expand(ctx, data, input)...) if response.Diagnostics.HasError() { return } - input.TagSpecifications = getTagSpecificationsInV2(ctx, awstypes.ResourceTypeCapacityReservation) + input.TagSpecifications = getTagSpecificationsIn(ctx, awstypes.ResourceTypeCapacityReservation) output, err := conn.PurchaseCapacityBlock(ctx, input) + if err != nil { - response.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameCapacityBlockReservation, plan.CapacityBlockOfferingID.ValueString(), err), - err.Error(), - ) - return - } + response.Diagnostics.AddError("purchasing EC2 Capacity Block Reservation", err.Error()) - if output == nil || output.CapacityReservation == nil { - response.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameCapacityBlockReservation, plan.CapacityBlockOfferingID.ValueString(), nil), - errors.New("empty output").Error(), - ) return } - cp := output.CapacityReservation - state := plan - state.ID = fwflex.StringToFramework(ctx, cp.CapacityReservationId) + // Set values for unknowns. + data.ID = fwflex.StringToFramework(ctx, output.CapacityReservation.CapacityReservationId) - createTimeout := r.CreateTimeout(ctx, plan.Timeouts) - out, err := waitCapacityBlockReservationActive(ctx, conn, createTimeout, state.ID.ValueString()) + cr, err := waitCapacityBlockReservationActive(ctx, conn, data.ID.ValueString(), r.CreateTimeout(ctx, data.Timeouts)) if err != nil { - response.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionWaitingForCreation, ResNameCapacityBlockReservation, state.ID.ValueString(), err), - err.Error(), - ) + response.State.SetAttribute(ctx, path.Root(names.AttrID), data.ID) // Set 'id' so as to taint the resource. + response.Diagnostics.AddError(fmt.Sprintf("waiting for EC2 Capacity Block Reservation (%s) active", data.ID.ValueString()), err.Error()) + return } - response.Diagnostics.Append(fwflex.Flatten(ctx, out, &state)...) - + // Set values for unknowns. + response.Diagnostics.Append(fwflex.Flatten(ctx, cr, &data)...) if response.Diagnostics.HasError() { return } - response.Diagnostics.Append(response.State.Set(ctx, &state)...) + response.Diagnostics.Append(response.State.Set(ctx, &data)...) } -func (r *resourceCapacityBlockReservation) Read(ctx context.Context, request resource.ReadRequest, response *resource.ReadResponse) { - conn := r.Meta().EC2Client(ctx) - var data resourceCapacityBlockReservationData - +func (r *capacityBlockReservationResource) Read(ctx context.Context, request resource.ReadRequest, response *resource.ReadResponse) { + var data capacityBlockReservationReservationModel response.Diagnostics.Append(request.State.Get(ctx, &data)...) - if response.Diagnostics.HasError() { return } - output, err := findCapacityBlockReservationByID(ctx, conn, data.ID.ValueString()) + conn := r.Meta().EC2Client(ctx) + + cr, err := findCapacityReservationByID(ctx, conn, data.ID.ValueString()) if tfresource.NotFound(err) { response.Diagnostics.Append(fwdiag.NewResourceNotFoundWarningDiagnostic(err)) response.State.RemoveResource(ctx) + return } + if err != nil { - response.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionReading, ResNameCapacityBlockReservation, data.ID.ValueString(), err), - err.Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("reading EC2 Capacity Block Reservation (%s)", data.ID.ValueString()), err.Error()) + return } - response.Diagnostics.Append(fwflex.Flatten(ctx, output, &data)...) - + response.Diagnostics.Append(fwflex.Flatten(ctx, cr, &data)...) if response.Diagnostics.HasError() { return } @@ -266,11 +242,11 @@ func (r *resourceCapacityBlockReservation) Read(ctx context.Context, request res response.Diagnostics.Append(response.State.Set(ctx, &data)...) } -func (r *resourceCapacityBlockReservation) ModifyPlan(ctx context.Context, request resource.ModifyPlanRequest, response *resource.ModifyPlanResponse) { +func (r *capacityBlockReservationResource) ModifyPlan(ctx context.Context, request resource.ModifyPlanRequest, response *resource.ModifyPlanResponse) { r.SetTagsAll(ctx, request, response) } -type resourceCapacityBlockReservationData struct { +type capacityBlockReservationReservationModel struct { ARN types.String `tfsdk:"arn"` AvailabilityZone types.String `tfsdk:"availability_zone"` CapacityBlockOfferingID types.String `tfsdk:"capacity_block_offering_id"` @@ -290,84 +266,3 @@ type resourceCapacityBlockReservationData struct { Tenancy types.String `tfsdk:"tenancy"` Timeouts timeouts.Value `tfsdk:"timeouts"` } - -func findCapacityBlockReservationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CapacityReservation, error) { - input := &ec2.DescribeCapacityReservationsInput{ - CapacityReservationIds: []string{id}, - } - - output, err := conn.DescribeCapacityReservations(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidReservationNotFound, errCodeInvalidCapacityReservationIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || len(output.CapacityReservations) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - reservation, err := tfresource.AssertSingleValueResult(output.CapacityReservations) - - if err != nil { - return nil, err - } - - // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#capacity-reservations-view. - if state := reservation.State; state == awstypes.CapacityReservationStateCancelled || state == awstypes.CapacityReservationStateExpired { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(reservation.CapacityReservationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return reservation, nil -} - -func waitCapacityBlockReservationActive(ctx context.Context, conn *ec2.Client, timeout time.Duration, id string) (*awstypes.CapacityReservation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.CapacityReservationStatePaymentPending), - Target: enum.Slice(awstypes.CapacityReservationStateActive, awstypes.CapacityReservationStateScheduled), - Refresh: statusCapacityBlockReservation(ctx, conn, id), - Timeout: timeout, - MinTimeout: 10 * time.Second, - Delay: 30 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CapacityReservation); ok { - return output, err - } - - return nil, err -} - -func statusCapacityBlockReservation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findCapacityBlockReservationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} diff --git a/internal/service/ec2/ec2_capacity_block_reservation_test.go b/internal/service/ec2/ec2_capacity_block_reservation_test.go index 49f38a20c2f..91e709ce523 100644 --- a/internal/service/ec2/ec2_capacity_block_reservation_test.go +++ b/internal/service/ec2/ec2_capacity_block_reservation_test.go @@ -37,7 +37,7 @@ func TestAccEC2CapacityBlockReservation_basic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) }, ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: nil, + CheckDestroy: acctest.CheckDestroyNoop, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), Steps: []resource.TestStep{ { @@ -66,10 +66,6 @@ func testAccCheckCapacityBlockReservationExists(ctx context.Context, n string, v return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 Capacity Reservation ID is set") - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindCapacityReservationByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/ec2_capacity_reservation.go b/internal/service/ec2/ec2_capacity_reservation.go index b053796cf74..1be9c24a6ce 100644 --- a/internal/service/ec2/ec2_capacity_reservation.go +++ b/internal/service/ec2/ec2_capacity_reservation.go @@ -140,7 +140,7 @@ func resourceCapacityReservationCreate(ctx context.Context, d *schema.ResourceDa InstanceCount: aws.Int32(int32(d.Get(names.AttrInstanceCount).(int))), InstancePlatform: awstypes.CapacityReservationInstancePlatform(d.Get("instance_platform").(string)), InstanceType: aws.String(d.Get(names.AttrInstanceType).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeCapacityReservation), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeCapacityReservation), } if v, ok := d.GetOk("ebs_optimized"); ok { @@ -223,7 +223,7 @@ func resourceCapacityReservationRead(ctx context.Context, d *schema.ResourceData d.Set("placement_group_arn", reservation.PlacementGroupArn) d.Set("tenancy", reservation.Tenancy) - setTagsOutV2(ctx, reservation.Tags) + setTagsOut(ctx, reservation.Tags) return diags } diff --git a/internal/service/ec2/ec2_eip.go b/internal/service/ec2/ec2_eip.go index 35c3842396b..d03109791e6 100644 --- a/internal/service/ec2/ec2_eip.go +++ b/internal/service/ec2/ec2_eip.go @@ -152,7 +152,7 @@ func resourceEIPCreate(ctx context.Context, d *schema.ResourceData, meta interfa conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.AllocateAddressInput{ - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeElasticIp), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeElasticIp), } if v, ok := d.GetOk(names.AttrAddress); ok { @@ -271,7 +271,7 @@ func resourceEIPRead(ctx context.Context, d *schema.ResourceData, meta interface return sdkdiag.AppendErrorf(diags, "reading EC2 EIP (%s) domain name attribute: %s", d.Id(), err) } - setTagsOutV2(ctx, address.Tags) + setTagsOut(ctx, address.Tags) return diags } diff --git a/internal/service/ec2/ec2_eip_data_source.go b/internal/service/ec2/ec2_eip_data_source.go index 950a4da669d..95f4553d9f0 100644 --- a/internal/service/ec2/ec2_eip_data_source.go +++ b/internal/service/ec2/ec2_eip_data_source.go @@ -117,11 +117,11 @@ func dataSourceEIPRead(ctx context.Context, d *schema.ResourceData, meta interfa input.PublicIps = []string{v.(string)} } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -174,7 +174,7 @@ func dataSourceEIPRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("public_dns", meta.(*conns.AWSClient).EC2PublicDNSNameForIP(ctx, v)) } - setTagsOutV2(ctx, eip.Tags) + setTagsOut(ctx, eip.Tags) return diags } diff --git a/internal/service/ec2/ec2_eips_data_source.go b/internal/service/ec2/ec2_eips_data_source.go index 93faf717018..e1c2e1ce5cb 100644 --- a/internal/service/ec2/ec2_eips_data_source.go +++ b/internal/service/ec2/ec2_eips_data_source.go @@ -51,14 +51,14 @@ func dataSourceEIPsRead(ctx context.Context, d *schema.ResourceData, meta interf input := &ec2.DescribeAddressesInput{} if tags, tagsOk := d.GetOk(names.AttrTags); tagsOk { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, tags.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, tags.(map[string]interface{}))), )...) } if filters, filtersOk := d.GetOk(names.AttrFilter); filtersOk { input.Filters = append(input.Filters, - newCustomFilterListV2(filters.(*schema.Set))...) + newCustomFilterList(filters.(*schema.Set))...) } if len(input.Filters) == 0 { diff --git a/internal/service/ec2/ec2_fleet.go b/internal/service/ec2/ec2_fleet.go index ea039bc5ceb..28091f1d53e 100644 --- a/internal/service/ec2/ec2_fleet.go +++ b/internal/service/ec2/ec2_fleet.go @@ -491,8 +491,8 @@ func resourceFleet() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: FleetOnDemandAllocationStrategyLowestPrice, - ValidateFunc: validation.StringInSlice(FleetOnDemandAllocationStrategy_Values(), false), + Default: fleetOnDemandAllocationStrategyLowestPrice, + ValidateFunc: validation.StringInSlice(fleetOnDemandAllocationStrategy_Values(), false), }, "capacity_reservation_options": { Type: schema.TypeList, @@ -544,8 +544,8 @@ func resourceFleet() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: SpotAllocationStrategyLowestPrice, - ValidateFunc: validation.StringInSlice(SpotAllocationStrategy_Values(), false), + Default: spotAllocationStrategyLowestPrice, + ValidateFunc: validation.StringInSlice(spotAllocationStrategy_Values(), false), }, "instance_interruption_behavior": { Type: schema.TypeString, @@ -721,7 +721,7 @@ func resourceFleetCreate(ctx context.Context, d *schema.ResourceData, meta inter ClientToken: aws.String(id.UniqueId()), LaunchTemplateConfigs: expandFleetLaunchTemplateConfigRequests(d.Get("launch_template_config").([]interface{})), TargetCapacitySpecification: expandTargetCapacitySpecificationRequest(d.Get("target_capacity_specification").([]interface{})[0].(map[string]interface{})), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeFleet), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeFleet), Type: fleetType, } @@ -858,7 +858,7 @@ func resourceFleetRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("valid_until", aws.ToTime(fleet.ValidUntil).Format(time.RFC3339)) } - setTagsOutV2(ctx, fleet.Tags) + setTagsOut(ctx, fleet.Tags) return diags } @@ -1137,7 +1137,7 @@ func expandSpotOptionsRequest(tfMap map[string]interface{}) *awstypes.SpotOption apiObject.AllocationStrategy = awstypes.SpotAllocationStrategy(v) // InvalidFleetConfig: InstancePoolsToUseCount option is only available with the lowestPrice allocation strategy. - if v == SpotAllocationStrategyLowestPrice { + if v == spotAllocationStrategyLowestPrice { if v, ok := tfMap["instance_pools_to_use_count"].(int); ok { apiObject.InstancePoolsToUseCount = aws.Int32(int32(v)) } diff --git a/internal/service/ec2/ec2_host.go b/internal/service/ec2/ec2_host.go index cb344528418..adbbf92dbca 100644 --- a/internal/service/ec2/ec2_host.go +++ b/internal/service/ec2/ec2_host.go @@ -112,7 +112,7 @@ func resourceHostCreate(ctx context.Context, d *schema.ResourceData, meta interf ClientToken: aws.String(id.UniqueId()), HostRecovery: awstypes.HostRecovery(d.Get("host_recovery").(string)), Quantity: aws.Int32(1), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeDedicatedHost), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeDedicatedHost), } if v, ok := d.GetOk("asset_id"); ok { @@ -179,7 +179,7 @@ func resourceHostRead(ctx context.Context, d *schema.ResourceData, meta interfac d.Set("outpost_arn", host.OutpostArn) d.Set(names.AttrOwnerID, host.OwnerId) - setTagsOutV2(ctx, host.Tags) + setTagsOut(ctx, host.Tags) return diags } @@ -212,7 +212,7 @@ func resourceHostUpdate(ctx context.Context, d *schema.ResourceData, meta interf output, err := conn.ModifyHosts(ctx, input) if err == nil && output != nil { - err = unsuccessfulItemsErrorV2(output.Unsuccessful) + err = unsuccessfulItemsError(output.Unsuccessful) } if err != nil { @@ -237,7 +237,7 @@ func resourceHostDelete(ctx context.Context, d *schema.ResourceData, meta interf }) if err == nil && output != nil { - err = unsuccessfulItemsErrorV2(output.Unsuccessful) + err = unsuccessfulItemsError(output.Unsuccessful) } if tfawserr.ErrCodeEquals(err, errCodeClientInvalidHostIDNotFound) { diff --git a/internal/service/ec2/ec2_host_data_source.go b/internal/service/ec2/ec2_host_data_source.go index 5b71420d470..9965c33814b 100644 --- a/internal/service/ec2/ec2_host_data_source.go +++ b/internal/service/ec2/ec2_host_data_source.go @@ -96,7 +96,7 @@ func dataSourceHostRead(ctx context.Context, d *schema.ResourceData, meta interf conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeHostsInput{ - Filter: newCustomFilterListV2(d.Get(names.AttrFilter).(*schema.Set)), + Filter: newCustomFilterList(d.Get(names.AttrFilter).(*schema.Set)), } if v, ok := d.GetOk("host_id"); ok { @@ -136,7 +136,7 @@ func dataSourceHostRead(ctx context.Context, d *schema.ResourceData, meta interf d.Set("sockets", host.HostProperties.Sockets) d.Set("total_vcpus", host.HostProperties.TotalVCpus) - setTagsOutV2(ctx, host.Tags) + setTagsOut(ctx, host.Tags) return diags } diff --git a/internal/service/ec2/ec2_instance.go b/internal/service/ec2/ec2_instance.go index c1595b9fd68..2b343e9de82 100644 --- a/internal/service/ec2/ec2_instance.go +++ b/internal/service/ec2/ec2_instance.go @@ -58,7 +58,7 @@ func resourceInstance() *schema.Resource { }, SchemaVersion: 1, - MigrateState: InstanceMigrateState, + MigrateState: instanceMigrateState, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(10 * time.Minute), @@ -198,7 +198,7 @@ func resourceInstance() *schema.Resource { "cpu_credits": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringInSlice(CPUCredits_Values(), false), + ValidateFunc: validation.StringInSlice(cpuCredits_Values(), false), DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { // Only work with existing instances if d.Id() == "" { @@ -519,7 +519,7 @@ func resourceInstance() *schema.Resource { Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringLenBetween(1, 255), - Default: LaunchTemplateVersionDefault, + Default: launchTemplateVersionDefault, }, }, }, @@ -876,11 +876,11 @@ func resourceInstance() *schema.Resource { } switch stateVersion { - case LaunchTemplateVersionDefault: + case launchTemplateVersionDefault: if instanceVersion != defaultVersion { diff.ForceNew("launch_template.0.version") } - case LaunchTemplateVersionLatest: + case launchTemplateVersionLatest: if instanceVersion != latestVersion { diff.ForceNew("launch_template.0.version") } @@ -969,7 +969,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in } // instance itself - tagSpecifications := getTagSpecificationsInV2(ctx, awstypes.ResourceTypeInstance) + tagSpecifications := getTagSpecificationsIn(ctx, awstypes.ResourceTypeInstance) // block devices defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig @@ -1106,7 +1106,7 @@ func resourceInstanceCreate(ctx context.Context, d *schema.ResourceData, meta in } for vol, blockDeviceTags := range blockDeviceTagsToCreate { - if err := createTagsV2(ctx, conn, vol, TagsV2(tftags.New(ctx, blockDeviceTags))); err != nil { + if err := createTags(ctx, conn, vol, Tags(tftags.New(ctx, blockDeviceTags))); err != nil { log.Printf("[ERR] Error creating tags for EBS volume %s: %s", vol, err) } } @@ -1322,7 +1322,7 @@ func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set("monitoring", monitoringState == awstypes.MonitoringStateEnabled || monitoringState == awstypes.MonitoringStatePending) } - setTagsOutV2(ctx, instance.Tags) + setTagsOut(ctx, instance.Tags) if _, ok := d.GetOk("volume_tags"); ok && !blockDeviceTagsDefined(d) { volumeTags, err := readVolumeTags(ctx, conn, d.Id()) @@ -1332,7 +1332,7 @@ func resourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta inte defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - tags := keyValueTagsV2(ctx, volumeTags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + tags := keyValueTags(ctx, volumeTags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) if err := d.Set("volume_tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting volume_tags: %s", err) @@ -1516,7 +1516,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in o, n := d.GetChange("volume_tags") for _, volID := range volIDs { - if err := updateTagsV2(ctx, conn, volID, o, n); err != nil { + if err := updateTags(ctx, conn, volID, o, n); err != nil { return sdkdiag.AppendErrorf(diags, "updating volume_tags (%s): %s", volID, err) } } @@ -2041,7 +2041,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in if d.HasChange("root_block_device.0.tags") { o, n := d.GetChange("root_block_device.0.tags") - if err := updateTagsV2(ctx, conn, volID, o, n); err != nil { + if err := updateTags(ctx, conn, volID, o, n); err != nil { return sdkdiag.AppendErrorf(diags, "updating tags for volume (%s): %s", volID, err) } } @@ -2049,7 +2049,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in if d.HasChange("root_block_device.0.tags_all") && !d.HasChange("root_block_device.0.tags") { o, n := d.GetChange("root_block_device.0.tags_all") - if err := updateTagsV2(ctx, conn, volID, o, n); err != nil { + if err := updateTags(ctx, conn, volID, o, n); err != nil { return sdkdiag.AppendErrorf(diags, "updating tags for volume (%s): %s", volID, err) } } @@ -2060,7 +2060,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in if d.HasChange("capacity_reservation_specification") && !d.IsNewResource() { if v, ok := d.GetOk("capacity_reservation_specification"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { if v := expandCapacityReservationSpecification(v.([]interface{})[0].(map[string]interface{})); v != nil && (v.CapacityReservationPreference != "" || v.CapacityReservationTarget != nil) { - if err := stopInstance(ctx, conn, d.Id(), false, InstanceStopTimeout); err != nil { + if err := stopInstance(ctx, conn, d.Id(), false, instanceStopTimeout); err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -2095,7 +2095,7 @@ func resourceInstanceUpdate(ctx context.Context, d *schema.ResourceData, meta in return sdkdiag.AppendErrorf(diags, "waiting for EC2 Instance (%s) capacity reservation attributes update: %s", d.Id(), err) } - if err := startInstance(ctx, conn, d.Id(), true, InstanceStartTimeout); err != nil { + if err := startInstance(ctx, conn, d.Id(), true, instanceStartTimeout); err != nil { return sdkdiag.AppendFromErr(diags, err) } } @@ -2219,7 +2219,7 @@ func disableInstanceAPITermination(ctx context.Context, conn *ec2.Client, id str func modifyInstanceAttributeWithStopStart(ctx context.Context, conn *ec2.Client, input *ec2.ModifyInstanceAttributeInput, attrName string) error { id := aws.ToString(input.InstanceId) - if err := stopInstance(ctx, conn, id, false, InstanceStopTimeout); err != nil { + if err := stopInstance(ctx, conn, id, false, instanceStopTimeout); err != nil { return err } @@ -2227,7 +2227,7 @@ func modifyInstanceAttributeWithStopStart(ctx context.Context, conn *ec2.Client, return fmt.Errorf("modifying EC2 Instance (%s) %s attribute: %w", id, attrName, err) } - if err := startInstance(ctx, conn, id, true, InstanceStartTimeout); err != nil { + if err := startInstance(ctx, conn, id, true, instanceStartTimeout); err != nil { return err } @@ -2353,9 +2353,9 @@ func readBlockDevicesFromInstance(ctx context.Context, d *schema.ResourceData, m } if v, ok := d.GetOk("volume_tags"); !ok || v == nil || len(v.(map[string]interface{})) == 0 { if ds { - bd[names.AttrTags] = keyValueTagsV2(ctx, vol.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map() + bd[names.AttrTags] = keyValueTags(ctx, vol.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map() } else { - tags := keyValueTagsV2(ctx, vol.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) + tags := keyValueTags(ctx, vol.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) bd[names.AttrTags] = tags.RemoveDefaultConfig(defaultTagsConfig).Map() bd[names.AttrTagsAll] = tags.Map() } @@ -2424,7 +2424,7 @@ func disassociateInstanceProfile(ctx context.Context, associationId *string, con return nil } -func FetchRootDeviceName(ctx context.Context, conn *ec2.Client, amiID string) (*string, error) { +func findRootDeviceName(ctx context.Context, conn *ec2.Client, amiID string) (*string, error) { if amiID == "" { return nil, errors.New("Cannot fetch root device name for blank AMI ID.") } @@ -2691,7 +2691,7 @@ func readBlockDeviceMappingsFromConfig(ctx context.Context, d *schema.ResourceDa return nil, errors.New("`ami` must be set or provided via `launch_template`") } - if dn, err := FetchRootDeviceName(ctx, conn, amiID); err == nil { + if dn, err := findRootDeviceName(ctx, conn, amiID); err == nil { if dn == nil { return nil, fmt.Errorf( "Expected 1 AMI for ID: %s, got none", @@ -2919,7 +2919,7 @@ func buildInstanceOpts(ctx context.Context, d *schema.ResourceData, meta interfa // Set default cpu_credits as Unlimited for T3/T3a instance type if strings.HasPrefix(instanceType, "t3") { opts.CreditSpecification = &awstypes.CreditSpecificationRequest{ - CpuCredits: aws.String(CPUCreditsUnlimited), + CpuCredits: aws.String(cpuCreditsUnlimited), } } @@ -3334,7 +3334,7 @@ func getInstanceVolIDs(ctx context.Context, conn *ec2.Client, instanceId string) volIDs := []string{} resp, err := conn.DescribeVolumes(ctx, &ec2.DescribeVolumesInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "attachment.instance-id": instanceId, }), }) @@ -3853,15 +3853,15 @@ func flattenInstanceLaunchTemplate(ctx context.Context, conn *ec2.Client, instan } switch previousLaunchTemplateVersion { - case LaunchTemplateVersionDefault: + case launchTemplateVersionDefault: if currentLaunchTemplateVersion == defaultVersion { - tfMap[names.AttrVersion] = LaunchTemplateVersionDefault + tfMap[names.AttrVersion] = launchTemplateVersionDefault } else { tfMap[names.AttrVersion] = currentLaunchTemplateVersion } - case LaunchTemplateVersionLatest: + case launchTemplateVersionLatest: if currentLaunchTemplateVersion == latestVersion { - tfMap[names.AttrVersion] = LaunchTemplateVersionLatest + tfMap[names.AttrVersion] = launchTemplateVersionLatest } else { tfMap[names.AttrVersion] = currentLaunchTemplateVersion } @@ -3905,11 +3905,11 @@ func findLaunchTemplateData(ctx context.Context, conn *ec2.Client, launchTemplat if v := aws.ToString(launchTemplateSpecification.Version); v != "" { switch v { - case LaunchTemplateVersionDefault: - input.Filters = newAttributeFilterListV2(map[string]string{ + case launchTemplateVersionDefault: + input.Filters = newAttributeFilterList(map[string]string{ "is-default-version": "true", }) - case LaunchTemplateVersionLatest: + case launchTemplateVersionLatest: latestVersion = true default: input.Versions = []string{v} @@ -3942,7 +3942,7 @@ func findLaunchTemplateNameAndVersions(ctx context.Context, conn *ec2.Client, id func findInstanceTagValue(ctx context.Context, conn *ec2.Client, instanceID, tagKey string) (string, error) { input := &ec2.DescribeTagsInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "resource-id": instanceID, names.AttrKey: tagKey, }), @@ -3969,8 +3969,8 @@ func isSnowballEdgeInstance(id string) bool { return strings.Contains(id, "s.") } -// InstanceType describes an EC2 instance type. -type InstanceType struct { +// instanceType describes an EC2 instance type. +type instanceType struct { // e.g. "m6i" Type string // e.g. "m" @@ -3983,7 +3983,7 @@ type InstanceType struct { Size string } -func ParseInstanceType(s string) (*InstanceType, error) { +func parseInstanceType(s string) (*instanceType, error) { matches := regexache.MustCompile(`(([[:alpha:]]+)([[:digit:]])+([[:alpha:]]*))\.([[:alnum:]]+)`).FindStringSubmatch(s) if matches == nil { @@ -3996,7 +3996,7 @@ func ParseInstanceType(s string) (*InstanceType, error) { return nil, err } - return &InstanceType{ + return &instanceType{ Type: matches[1], Family: matches[2], Generation: generation, diff --git a/internal/service/ec2/ec2_instance_connect_endpoint.go b/internal/service/ec2/ec2_instance_connect_endpoint.go index 90273f5fb28..0d83e03d8bf 100644 --- a/internal/service/ec2/ec2_instance_connect_endpoint.go +++ b/internal/service/ec2/ec2_instance_connect_endpoint.go @@ -152,7 +152,7 @@ func (r *instanceConnectEndpointResource) Create(ctx context.Context, request re // Additional fields. input.ClientToken = aws.String(id.UniqueId()) - input.TagSpecifications = getTagSpecificationsInV2(ctx, awstypes.ResourceTypeInstanceConnectEndpoint) + input.TagSpecifications = getTagSpecificationsIn(ctx, awstypes.ResourceTypeInstanceConnectEndpoint) output, err := conn.CreateInstanceConnectEndpoint(ctx, input) @@ -212,7 +212,7 @@ func (r *instanceConnectEndpointResource) Read(ctx context.Context, request reso return } - setTagsOutV2(ctx, instanceConnectEndpoint.Tags) + setTagsOut(ctx, instanceConnectEndpoint.Tags) response.Diagnostics.Append(response.State.Set(ctx, &data)...) } diff --git a/internal/service/ec2/ec2_instance_data_source.go b/internal/service/ec2/ec2_instance_data_source.go index 3cc2a1f7664..a54464eba6c 100644 --- a/internal/service/ec2/ec2_instance_data_source.go +++ b/internal/service/ec2/ec2_instance_data_source.go @@ -412,12 +412,12 @@ func dataSourceInstanceRead(ctx context.Context, d *schema.ResourceData, meta in input := &ec2.DescribeInstancesInput{} if tags, tagsOk := d.GetOk("instance_tags"); tagsOk { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, tags.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, tags.(map[string]interface{}))), )...) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) if len(input.Filters) == 0 { @@ -546,7 +546,7 @@ func instanceDescriptionAttributes(ctx context.Context, d *schema.ResourceData, d.Set("monitoring", monitoringState == names.AttrEnabled || monitoringState == "pending") } - setTagsOutV2(ctx, instance.Tags) + setTagsOut(ctx, instance.Tags) // Security Groups if err := readSecurityGroups(ctx, d, instance, conn); err != nil { diff --git a/internal/service/ec2/ec2_instance_migrate.go b/internal/service/ec2/ec2_instance_migrate.go index ff08a073e10..cc2eaaed120 100644 --- a/internal/service/ec2/ec2_instance_migrate.go +++ b/internal/service/ec2/ec2_instance_migrate.go @@ -14,7 +14,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func InstanceMigrateState( +func instanceMigrateState( v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: @@ -36,7 +36,7 @@ func migrateInstanceStateV0toV1(is *terraform.InstanceState) (*terraform.Instanc // Delete old count delete(is.Attributes, "block_device.#") - oldBds, err := ReadV0BlockDevices(is) + oldBds, err := readV0BlockDevices(is) if err != nil { return is, err } @@ -49,13 +49,13 @@ func migrateInstanceStateV0toV1(is *terraform.InstanceState) (*terraform.Instanc is.Attributes["root_block_device.#"] = "0" } for _, oldBd := range oldBds { - WriteV1BlockDevice(is, oldBd) + writeV1BlockDevice(is, oldBd) } log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) return is, nil } -func ReadV0BlockDevices(is *terraform.InstanceState) (map[string]map[string]string, error) { +func readV0BlockDevices(is *terraform.InstanceState) (map[string]map[string]string, error) { oldBds := make(map[string]map[string]string) for k, v := range is.Attributes { if !strings.HasPrefix(k, "block_device.") { @@ -77,8 +77,7 @@ func ReadV0BlockDevices(is *terraform.InstanceState) (map[string]map[string]stri return oldBds, nil } -func WriteV1BlockDevice( - is *terraform.InstanceState, oldBd map[string]string) { +func writeV1BlockDevice(is *terraform.InstanceState, oldBd map[string]string) { code := create.StringHashcode(oldBd[names.AttrDeviceName]) bdType := "ebs_block_device" if vn, ok := oldBd[names.AttrVirtualName]; ok && strings.HasPrefix(vn, "ephemeral") { diff --git a/internal/service/ec2/ec2_instance_state.go b/internal/service/ec2/ec2_instance_state.go index 92f238a7ff7..028c6cbbff5 100644 --- a/internal/service/ec2/ec2_instance_state.go +++ b/internal/service/ec2/ec2_instance_state.go @@ -8,14 +8,12 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/create" "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -28,7 +26,7 @@ func resourceInstanceState() *schema.Resource { CreateWithoutTimeout: resourceInstanceStateCreate, ReadWithoutTimeout: resourceInstanceStateRead, UpdateWithoutTimeout: resourceInstanceStateUpdate, - DeleteWithoutTimeout: resourceInstanceStateDelete, + DeleteWithoutTimeout: schema.NoopContext, Importer: &schema.ResourceImporter{ StateContext: schema.ImportStatePassthroughContext, @@ -62,67 +60,59 @@ func resourceInstanceState() *schema.Resource { func resourceInstanceStateCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - instanceId := d.Get(names.AttrInstanceID).(string) - instance, instanceErr := waitInstanceReady(ctx, conn, instanceId, d.Timeout(schema.TimeoutCreate)) + instanceID := d.Get(names.AttrInstanceID).(string) + instance, err := waitInstanceReady(ctx, conn, instanceID, d.Timeout(schema.TimeoutCreate)) - if instanceErr != nil { - return create.AppendDiagError(diags, names.EC2, create.ErrActionReading, ResInstance, instanceId, instanceErr) + if err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for EC2 Instance (%s) ready: %s", instanceID, err) } - err := updateInstanceState(ctx, conn, instanceId, string(instance.State.Name), d.Get(names.AttrState).(string), d.Get("force").(bool)) - - if err != nil { + if err := updateInstanceState(ctx, conn, instanceID, string(instance.State.Name), d.Get(names.AttrState).(string), d.Get("force").(bool)); err != nil { return sdkdiag.AppendFromErr(diags, err) } - d.SetId(d.Get(names.AttrInstanceID).(string)) + d.SetId(instanceID) return append(diags, resourceInstanceStateRead(ctx, d, meta)...) } func resourceInstanceStateRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) state, err := findInstanceStateByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { - create.LogNotFoundRemoveState(names.EC2, create.ErrActionReading, ResInstanceState, d.Id()) + log.Printf("[WARN] EC2 Instance State %s not found, removing from state", d.Id()) d.SetId("") return diags } if err != nil { - return create.AppendDiagError(diags, names.EC2, create.ErrActionReading, ResInstanceState, d.Id(), err) + return sdkdiag.AppendErrorf(diags, "reading EC2 Instance State (%s): %s", d.Id(), err) } + d.Set("force", d.Get("force").(bool)) d.Set(names.AttrInstanceID, d.Id()) d.Set(names.AttrState, state.Name) - d.Set("force", d.Get("force").(bool)) return diags } func resourceInstanceStateUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - instance, instanceErr := waitInstanceReady(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)) - - if instanceErr != nil { - return create.AppendDiagError(diags, names.EC2, create.ErrActionReading, ResInstance, aws.ToString(instance.InstanceId), instanceErr) + if _, err := waitInstanceReady(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for EC2 Instance (%s) ready: %s", d.Id(), err) } if d.HasChange(names.AttrState) { o, n := d.GetChange(names.AttrState) - err := updateInstanceState(ctx, conn, d.Id(), o.(string), n.(string), d.Get("force").(bool)) - if err != nil { + if err := updateInstanceState(ctx, conn, d.Id(), o.(string), n.(string), d.Get("force").(bool)); err != nil { return sdkdiag.AppendFromErr(diags, err) } } @@ -130,25 +120,19 @@ func resourceInstanceStateUpdate(ctx context.Context, d *schema.ResourceData, me return append(diags, resourceInstanceStateRead(ctx, d, meta)...) } -func resourceInstanceStateDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - log.Printf("[DEBUG] %s %s deleting an aws_ec2_instance_state resource only stops managing instance state, The Instance is left in its current state.: %s", names.EC2, ResInstanceState, d.Id()) - - return nil // nosemgrep:ci.semgrep.pluginsdk.return-diags-not-nil -} - func updateInstanceState(ctx context.Context, conn *ec2.Client, id string, currentState string, configuredState string, force bool) error { if currentState == configuredState { return nil } if configuredState == "stopped" { - if err := stopInstance(ctx, conn, id, force, InstanceStopTimeout); err != nil { + if err := stopInstance(ctx, conn, id, force, instanceStopTimeout); err != nil { return err } } if configuredState == "running" { - if err := startInstance(ctx, conn, id, false, InstanceStartTimeout); err != nil { + if err := startInstance(ctx, conn, id, false, instanceStartTimeout); err != nil { return err } } diff --git a/internal/service/ec2/ec2_instance_test.go b/internal/service/ec2/ec2_instance_test.go index 25135787d60..b56b2ae1712 100644 --- a/internal/service/ec2/ec2_instance_test.go +++ b/internal/service/ec2/ec2_instance_test.go @@ -5712,14 +5712,14 @@ func defaultSubnetCount(ctx context.Context, t *testing.T) int { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSubnetsInput{ - Filters: tfec2.NewAttributeFilterListV2( + Filters: tfec2.NewAttributeFilterList( map[string]string{ "defaultForAz": acctest.CtTrue, }, ), } - subnets, err := tfec2.FindSubnetsV2(ctx, conn, input) + subnets, err := tfec2.FindSubnets(ctx, conn, input) if acctest.PreCheckSkipError(err) { return 0 diff --git a/internal/service/ec2/ec2_instance_type_offering_data_source.go b/internal/service/ec2/ec2_instance_type_offering_data_source.go index 18d892d0cdb..837573a8a81 100644 --- a/internal/service/ec2/ec2_instance_type_offering_data_source.go +++ b/internal/service/ec2/ec2_instance_type_offering_data_source.go @@ -53,7 +53,7 @@ func dataSourceInstanceTypeOfferingRead(ctx context.Context, d *schema.ResourceD input := &ec2.DescribeInstanceTypeOfferingsInput{} if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } if v, ok := d.GetOk("location_type"); ok { diff --git a/internal/service/ec2/ec2_instance_type_offerings_data_source.go b/internal/service/ec2/ec2_instance_type_offerings_data_source.go index 2812c0b1d03..4ba5a469112 100644 --- a/internal/service/ec2/ec2_instance_type_offerings_data_source.go +++ b/internal/service/ec2/ec2_instance_type_offerings_data_source.go @@ -60,7 +60,7 @@ func dataSourceInstanceTypeOfferingsRead(ctx context.Context, d *schema.Resource input := &ec2.DescribeInstanceTypeOfferingsInput{} if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } if v, ok := d.GetOk("location_type"); ok { diff --git a/internal/service/ec2/ec2_instance_types_data_source.go b/internal/service/ec2/ec2_instance_types_data_source.go index 1d70b16facf..44586c540bd 100644 --- a/internal/service/ec2/ec2_instance_types_data_source.go +++ b/internal/service/ec2/ec2_instance_types_data_source.go @@ -42,7 +42,7 @@ func dataSourceInstanceTypesRead(ctx context.Context, d *schema.ResourceData, me input := &ec2.DescribeInstanceTypesInput{} if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } output, err := findInstanceTypes(ctx, conn, input) diff --git a/internal/service/ec2/ec2_instances_data_source.go b/internal/service/ec2/ec2_instances_data_source.go index 380f2c1f56d..e125c0da085 100644 --- a/internal/service/ec2/ec2_instances_data_source.go +++ b/internal/service/ec2/ec2_instances_data_source.go @@ -82,11 +82,11 @@ func dataSourceInstancesRead(ctx context.Context, d *schema.ResourceData, meta i }) } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get("instance_tags").(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get("instance_tags").(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/ec2_key_pair.go b/internal/service/ec2/ec2_key_pair.go index cb4d41d7ec9..160640fdd29 100644 --- a/internal/service/ec2/ec2_key_pair.go +++ b/internal/service/ec2/ec2_key_pair.go @@ -45,7 +45,7 @@ func resourceKeyPair() *schema.Resource { CustomizeDiff: verify.SetTagsDiff, SchemaVersion: 1, - MigrateState: KeyPairMigrateState, + MigrateState: keyPairMigrateState, Schema: map[string]*schema.Schema{ names.AttrARN: { @@ -107,7 +107,7 @@ func resourceKeyPairCreate(ctx context.Context, d *schema.ResourceData, meta int input := &ec2.ImportKeyPairInput{ KeyName: aws.String(keyName), PublicKeyMaterial: []byte(d.Get(names.AttrPublicKey).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeKeyPair), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeKeyPair), } output, err := conn.ImportKeyPair(ctx, input) @@ -139,7 +139,7 @@ func resourceKeyPairRead(ctx context.Context, d *schema.ResourceData, meta inter arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: "ec2", + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: meta.(*conns.AWSClient).AccountID, Resource: "key-pair/" + d.Id(), @@ -151,7 +151,7 @@ func resourceKeyPairRead(ctx context.Context, d *schema.ResourceData, meta inter d.Set("key_pair_id", keyPair.KeyPairId) d.Set("key_type", keyPair.KeyType) - setTagsOutV2(ctx, keyPair.Tags) + setTagsOut(ctx, keyPair.Tags) return diags } @@ -182,7 +182,7 @@ func resourceKeyPairDelete(ctx context.Context, d *schema.ResourceData, meta int // OpenSSHPublicKeysEqual returns whether or not two OpenSSH public key format strings represent the same key. // Any key comment is ignored when comparing values. -func OpenSSHPublicKeysEqual(v1, v2 string) bool { +func openSSHPublicKeysEqual(v1, v2 string) bool { key1, _, _, _, err := ssh.ParseAuthorizedKey([]byte(v1)) if err != nil { diff --git a/internal/service/ec2/ec2_key_pair_data_source.go b/internal/service/ec2/ec2_key_pair_data_source.go index 2c6a3269bfd..df6735b1316 100644 --- a/internal/service/ec2/ec2_key_pair_data_source.go +++ b/internal/service/ec2/ec2_key_pair_data_source.go @@ -77,7 +77,7 @@ func dataSourceKeyPairRead(ctx context.Context, d *schema.ResourceData, meta int input := &ec2.DescribeKeyPairsInput{} if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } if v, ok := d.GetOk("key_name"); ok { @@ -116,7 +116,7 @@ func dataSourceKeyPairRead(ctx context.Context, d *schema.ResourceData, meta int d.Set("key_type", keyPair.KeyType) d.Set(names.AttrPublicKey, keyPair.PublicKey) - setTagsOutV2(ctx, keyPair.Tags) + setTagsOut(ctx, keyPair.Tags) return diags } diff --git a/internal/service/ec2/ec2_key_pair_migrate.go b/internal/service/ec2/ec2_key_pair_migrate.go index 8537737837a..9a5e06277cf 100644 --- a/internal/service/ec2/ec2_key_pair_migrate.go +++ b/internal/service/ec2/ec2_key_pair_migrate.go @@ -12,8 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func KeyPairMigrateState( - v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { +func keyPairMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: log.Println("[INFO] Found AWS Key Pair State v0; migrating to v1") diff --git a/internal/service/ec2/ec2_launch_template.go b/internal/service/ec2/ec2_launch_template.go index ca71c429f6a..1979aebe14c 100644 --- a/internal/service/ec2/ec2_launch_template.go +++ b/internal/service/ec2/ec2_launch_template.go @@ -187,7 +187,7 @@ func resourceLaunchTemplate() *schema.Resource { "cpu_credits": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringInSlice(CPUCredits_Values(), false), + ValidateFunc: validation.StringInSlice(cpuCredits_Values(), false), }, }, }, @@ -999,7 +999,7 @@ func resourceLaunchTemplateCreate(ctx context.Context, d *schema.ResourceData, m input := &ec2.CreateLaunchTemplateInput{ ClientToken: aws.String(id.UniqueId()), LaunchTemplateName: aws.String(name), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeLaunchTemplate), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeLaunchTemplate), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -1064,7 +1064,7 @@ func resourceLaunchTemplateRead(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendFromErr(diags, err) } - setTagsOutV2(ctx, lt.Tags) + setTagsOut(ctx, lt.Tags) return diags } @@ -2129,7 +2129,7 @@ func expandLaunchTemplateTagSpecificationRequest(ctx context.Context, tfMap map[ if v, ok := tfMap[names.AttrTags].(map[string]interface{}); ok && len(v) > 0 { if v := tftags.New(ctx, v).IgnoreAWS(); len(v) > 0 { - apiObject.Tags = TagsV2(v) + apiObject.Tags = Tags(v) } } @@ -3075,7 +3075,7 @@ func flattenLaunchTemplateTagSpecification(ctx context.Context, apiObject awstyp } if v := apiObject.Tags; len(v) > 0 { - tfMap[names.AttrTags] = keyValueTagsV2(ctx, v).IgnoreAWS().Map() + tfMap[names.AttrTags] = keyValueTags(ctx, v).IgnoreAWS().Map() } return tfMap diff --git a/internal/service/ec2/ec2_launch_template_data_source.go b/internal/service/ec2/ec2_launch_template_data_source.go index ab12b488072..796513dc163 100644 --- a/internal/service/ec2/ec2_launch_template_data_source.go +++ b/internal/service/ec2/ec2_launch_template_data_source.go @@ -803,12 +803,12 @@ func dataSourceLaunchTemplateRead(ctx context.Context, d *schema.ResourceData, m input.LaunchTemplateNames = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) if len(input.Filters) == 0 { @@ -847,7 +847,7 @@ func dataSourceLaunchTemplateRead(ctx context.Context, d *schema.ResourceData, m return sdkdiag.AppendFromErr(diags, err) } - setTagsOutV2(ctx, lt.Tags) + setTagsOut(ctx, lt.Tags) return diags } diff --git a/internal/service/ec2/ec2_placement_group.go b/internal/service/ec2/ec2_placement_group.go index 8836b68df59..004d74e7ee7 100644 --- a/internal/service/ec2/ec2_placement_group.go +++ b/internal/service/ec2/ec2_placement_group.go @@ -94,7 +94,7 @@ func resourcePlacementGroupCreate(ctx context.Context, d *schema.ResourceData, m input := &ec2.CreatePlacementGroupInput{ GroupName: aws.String(name), Strategy: awstypes.PlacementStrategy(d.Get("strategy").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypePlacementGroup), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypePlacementGroup), } if v, ok := d.GetOk("partition_count"); ok { @@ -152,7 +152,7 @@ func resourcePlacementGroupRead(ctx context.Context, d *schema.ResourceData, met d.Set("spread_level", pg.SpreadLevel) d.Set("strategy", pg.Strategy) - setTagsOutV2(ctx, pg.Tags) + setTagsOut(ctx, pg.Tags) return diags } diff --git a/internal/service/ec2/ec2_public_ipv4_pool_data_source.go b/internal/service/ec2/ec2_public_ipv4_pool_data_source.go index 596d266ae07..e2c46953153 100644 --- a/internal/service/ec2/ec2_public_ipv4_pool_data_source.go +++ b/internal/service/ec2/ec2_public_ipv4_pool_data_source.go @@ -89,7 +89,7 @@ func dataSourcePublicIPv4PoolRead(ctx context.Context, d *schema.ResourceData, m if err := d.Set("pool_address_ranges", flattenPublicIPv4PoolRanges(pool.PoolAddressRanges)); err != nil { return sdkdiag.AppendErrorf(diags, "setting pool_address_ranges: %s", err) } - if err := d.Set(names.AttrTags, KeyValueTags(ctx, pool.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, pool.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } d.Set("total_address_count", pool.TotalAddressCount) diff --git a/internal/service/ec2/ec2_public_ipv4_pools_data_source.go b/internal/service/ec2/ec2_public_ipv4_pools_data_source.go index 2c105521fe7..3b844b8f506 100644 --- a/internal/service/ec2/ec2_public_ipv4_pools_data_source.go +++ b/internal/service/ec2/ec2_public_ipv4_pools_data_source.go @@ -39,11 +39,11 @@ func dataSourcePublicIPv4PoolsRead(ctx context.Context, d *schema.ResourceData, input := &ec2.DescribePublicIpv4PoolsInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/ec2_serial_console_access_data_source_test.go b/internal/service/ec2/ec2_serial_console_access_data_source_test.go index 0364e2307d8..05b1b16bd51 100644 --- a/internal/service/ec2/ec2_serial_console_access_data_source_test.go +++ b/internal/service/ec2/ec2_serial_console_access_data_source_test.go @@ -9,8 +9,8 @@ import ( "strconv" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -37,7 +37,7 @@ func TestAccEC2SerialConsoleAccessDataSource_basic(t *testing.T) { func testAccCheckSerialConsoleAccessDataSource(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) rs, ok := s.RootModule().Resources[n] if !ok { @@ -48,15 +48,15 @@ func testAccCheckSerialConsoleAccessDataSource(ctx context.Context, n string) re return fmt.Errorf("No ID is set") } - actual, err := conn.GetSerialConsoleAccessStatusWithContext(ctx, &ec2.GetSerialConsoleAccessStatusInput{}) + actual, err := conn.GetSerialConsoleAccessStatus(ctx, &ec2.GetSerialConsoleAccessStatusInput{}) if err != nil { return fmt.Errorf("Error reading serial console access toggle: %q", err) } attr, _ := strconv.ParseBool(rs.Primary.Attributes[names.AttrEnabled]) - if attr != aws.BoolValue(actual.SerialConsoleAccessEnabled) { - return fmt.Errorf("Serial console access is not in expected state (%t)", aws.BoolValue(actual.SerialConsoleAccessEnabled)) + if attr != aws.ToBool(actual.SerialConsoleAccessEnabled) { + return fmt.Errorf("Serial console access is not in expected state (%t)", aws.ToBool(actual.SerialConsoleAccessEnabled)) } return nil diff --git a/internal/service/ec2/ec2_spot_fleet_request.go b/internal/service/ec2/ec2_spot_fleet_request.go index 04f5fde8834..2d93a968b61 100644 --- a/internal/service/ec2/ec2_spot_fleet_request.go +++ b/internal/service/ec2/ec2_spot_fleet_request.go @@ -56,7 +56,7 @@ func resourceSpotFleetRequest() *schema.Resource { }, SchemaVersion: 1, - MigrateState: SpotFleetRequestMigrateState, + MigrateState: spotFleetRequestMigrateState, Schema: map[string]*schema.Schema{ "allocation_strategy": { @@ -885,7 +885,7 @@ func resourceSpotFleetRequestCreate(ctx context.Context, d *schema.ResourceData, IamFleetRole: aws.String(d.Get("iam_fleet_role").(string)), InstanceInterruptionBehavior: awstypes.InstanceInterruptionBehavior(d.Get("instance_interruption_behaviour").(string)), ReplaceUnhealthyInstances: aws.Bool(d.Get("replace_unhealthy_instances").(bool)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeSpotFleetRequest), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeSpotFleetRequest), TargetCapacity: aws.Int32(int32(d.Get("target_capacity").(int))), TerminateInstancesWithExpiration: aws.Bool(d.Get("terminate_instances_with_expiration").(bool)), Type: awstypes.FleetType(d.Get("fleet_type").(string)), @@ -1080,7 +1080,7 @@ func resourceSpotFleetRequestRead(ctx context.Context, d *schema.ResourceData, m d.Set("fleet_type", config.Type) d.Set("launch_specification", launchSpec) - setTagsOutV2(ctx, output.Tags) + setTagsOut(ctx, output.Tags) if err := d.Set("launch_template_config", flattenLaunchTemplateConfigs(config.LaunchTemplateConfigs)); err != nil { return sdkdiag.AppendErrorf(diags, "setting launch_template_config: %s", err) @@ -1286,7 +1286,7 @@ func buildSpotFleetLaunchSpecification(ctx context.Context, d map[string]interfa if m, ok := d[names.AttrTags].(map[string]interface{}); ok && len(m) > 0 { tagsSpec := make([]awstypes.SpotFleetTagSpecification, 0) - tags := TagsV2(tftags.New(ctx, m).IgnoreAWS()) + tags := Tags(tftags.New(ctx, m).IgnoreAWS()) spec := awstypes.SpotFleetTagSpecification{ ResourceType: awstypes.ResourceTypeInstance, @@ -1431,7 +1431,7 @@ func readSpotFleetBlockDeviceMappingsFromConfig(ctx context.Context, d map[strin ebs.Throughput = aws.Int32(int32(v)) } - if dn, err := FetchRootDeviceName(ctx, conn, d["ami"].(string)); err == nil { + if dn, err := findRootDeviceName(ctx, conn, d["ami"].(string)); err == nil { if dn == nil { return nil, fmt.Errorf( "Expected 1 AMI for ID: %s, got none", @@ -1852,7 +1852,7 @@ func expandSpotCapacityRebalance(l []interface{}) *awstypes.SpotCapacityRebalanc func launchSpecsToSet(ctx context.Context, conn *ec2.Client, launchSpecs []awstypes.SpotFleetLaunchSpecification) (*schema.Set, error) { specSet := &schema.Set{F: hashLaunchSpecification} for _, spec := range launchSpecs { - rootDeviceName, err := FetchRootDeviceName(ctx, conn, aws.ToString(spec.ImageId)) + rootDeviceName, err := findRootDeviceName(ctx, conn, aws.ToString(spec.ImageId)) if err != nil { return nil, err } @@ -1936,7 +1936,7 @@ func launchSpecToMap(ctx context.Context, l awstypes.SpotFleetLaunchSpecificatio for _, tagSpecs := range l.TagSpecifications { // only "instance" tags are currently supported: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_SpotFleetTagSpecification.html if tagSpecs.ResourceType == awstypes.ResourceTypeInstance { - m[names.AttrTags] = keyValueTagsV2(ctx, tagSpecs.Tags).IgnoreAWS().Map() + m[names.AttrTags] = keyValueTags(ctx, tagSpecs.Tags).IgnoreAWS().Map() } } } diff --git a/internal/service/ec2/ec2_spot_fleet_request_migrate.go b/internal/service/ec2/ec2_spot_fleet_request_migrate.go index e186eb3eedd..af1c6f406b5 100644 --- a/internal/service/ec2/ec2_spot_fleet_request_migrate.go +++ b/internal/service/ec2/ec2_spot_fleet_request_migrate.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func SpotFleetRequestMigrateState( +func spotFleetRequestMigrateState( v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: diff --git a/internal/service/ec2/ec2_spot_instance_request.go b/internal/service/ec2/ec2_spot_instance_request.go index 905e1a1d857..03845f7ddaa 100644 --- a/internal/service/ec2/ec2_spot_instance_request.go +++ b/internal/service/ec2/ec2_spot_instance_request.go @@ -181,7 +181,7 @@ func resourceSpotInstanceRequestCreate(ctx context.Context, d *schema.ResourceDa NetworkInterfaces: instanceOpts.NetworkInterfaces, }, SpotPrice: aws.String(d.Get("spot_price").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeSpotInstancesRequest), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeSpotInstancesRequest), Type: awstypes.SpotInstanceType(d.Get("spot_type").(string)), } @@ -278,7 +278,7 @@ func resourceSpotInstanceRequestRead(ctx context.Context, d *schema.ResourceData d.Set("launch_group", request.LaunchGroup) d.Set("block_duration_minutes", request.BlockDurationMinutes) - setTagsOutV2(ctx, request.Tags) + setTagsOut(ctx, request.Tags) d.Set("instance_interruption_behavior", request.InstanceInterruptionBehavior) d.Set("valid_from", aws.ToTime(request.ValidFrom).Format(time.RFC3339)) diff --git a/internal/service/ec2/ec2_spot_price_data_source.go b/internal/service/ec2/ec2_spot_price_data_source.go index 2b13468cfdf..96301e43db2 100644 --- a/internal/service/ec2/ec2_spot_price_data_source.go +++ b/internal/service/ec2/ec2_spot_price_data_source.go @@ -70,7 +70,7 @@ func dataSourceSpotPriceRead(ctx context.Context, d *schema.ResourceData, meta i } if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } resultSpotPrice, err := findSpotPrice(ctx, conn, input) diff --git a/internal/service/ec2/errors.go b/internal/service/ec2/errors.go index dd813f60c1d..4be42cf480e 100644 --- a/internal/service/ec2/errors.go +++ b/internal/service/ec2/errors.go @@ -7,11 +7,8 @@ import ( "errors" "fmt" - aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws" awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) @@ -83,6 +80,7 @@ const ( errCodeInvalidPoolIDNotFound = "InvalidPoolID.NotFound" errCodeInvalidPrefixListIDNotFound = "InvalidPrefixListID.NotFound" errCodeInvalidPrefixListIdNotFound = "InvalidPrefixListId.NotFound" + errCodeInvalidPrefixListModification = "InvalidPrefixListModification" errCodeInvalidPublicIpv4PoolIDNotFound = "InvalidPublicIpv4PoolID.NotFound" // nosemgrep:ci.caps5-in-const-name,ci.caps5-in-var-name errCodeInvalidReservationNotFound = "InvalidReservationID.NotFound" errCodeInvalidRouteNotFound = "InvalidRoute.NotFound" @@ -147,7 +145,7 @@ func cancelSpotFleetRequestError(apiObject *awstypes.CancelSpotFleetRequestsErro return nil } - return errs.APIError(apiObject.Code, aws_sdkv2.ToString(apiObject.Message)) + return errs.APIError(apiObject.Code, aws.ToString(apiObject.Message)) } func cancelSpotFleetRequestsError(apiObjects []awstypes.CancelSpotFleetRequestsErrorItem) error { @@ -155,7 +153,7 @@ func cancelSpotFleetRequestsError(apiObjects []awstypes.CancelSpotFleetRequestsE for _, apiObject := range apiObjects { if err := cancelSpotFleetRequestError(apiObject.Error); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", aws_sdkv2.ToString(apiObject.SpotFleetRequestId), err)) + errs = append(errs, fmt.Errorf("%s: %w", aws.ToString(apiObject.SpotFleetRequestId), err)) } } @@ -167,7 +165,7 @@ func deleteFleetError(apiObject *awstypes.DeleteFleetError) error { return nil } - return errs.APIError(apiObject.Code, aws_sdkv2.ToString(apiObject.Message)) + return errs.APIError(apiObject.Code, aws.ToString(apiObject.Message)) } func deleteFleetsError(apiObjects []awstypes.DeleteFleetErrorItem) error { @@ -175,51 +173,27 @@ func deleteFleetsError(apiObjects []awstypes.DeleteFleetErrorItem) error { for _, apiObject := range apiObjects { if err := deleteFleetError(apiObject.Error); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", aws_sdkv2.ToString(apiObject.FleetId), err)) + errs = append(errs, fmt.Errorf("%s: %w", aws.ToString(apiObject.FleetId), err)) } } return errors.Join(errs...) } -func UnsuccessfulItemError(apiObject *ec2.UnsuccessfulItemError) error { +func unsuccessfulItemError(apiObject *awstypes.UnsuccessfulItemError) error { if apiObject == nil { return nil } - return awserr.New(aws.StringValue(apiObject.Code), aws.StringValue(apiObject.Message), nil) + return errs.APIError(aws.ToString(apiObject.Code), aws.ToString(apiObject.Message)) } -func UnsuccessfulItemsError(apiObjects []*ec2.UnsuccessfulItem) error { +func unsuccessfulItemsError(apiObjects []awstypes.UnsuccessfulItem) error { var errs []error for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - - if err := UnsuccessfulItemError(apiObject.Error); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", aws.StringValue(apiObject.ResourceId), err)) - } - } - - return errors.Join(errs...) -} - -func unsuccessfulItemErrorV2(apiObject *awstypes.UnsuccessfulItemError) error { - if apiObject == nil { - return nil - } - - return errs.APIError(aws_sdkv2.ToString(apiObject.Code), aws_sdkv2.ToString(apiObject.Message)) -} - -func unsuccessfulItemsErrorV2(apiObjects []awstypes.UnsuccessfulItem) error { - var errs []error - - for _, apiObject := range apiObjects { - if err := unsuccessfulItemErrorV2(apiObject.Error); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", aws_sdkv2.ToString(apiObject.ResourceId), err)) + if err := unsuccessfulItemError(apiObject.Error); err != nil { + errs = append(errs, fmt.Errorf("%s: %w", aws.ToString(apiObject.ResourceId), err)) } } @@ -231,7 +205,7 @@ func enableFastSnapshotRestoreStateItemError(apiObject *awstypes.EnableFastSnaps return nil } - return errs.APIError(aws_sdkv2.ToString(apiObject.Code), aws_sdkv2.ToString(apiObject.Message)) + return errs.APIError(aws.ToString(apiObject.Code), aws.ToString(apiObject.Message)) } func enableFastSnapshotRestoreStateItemsError(apiObjects []awstypes.EnableFastSnapshotRestoreStateErrorItem) error { @@ -239,7 +213,7 @@ func enableFastSnapshotRestoreStateItemsError(apiObjects []awstypes.EnableFastSn for _, apiObject := range apiObjects { if err := enableFastSnapshotRestoreStateItemError(apiObject.Error); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", aws_sdkv2.ToString(apiObject.AvailabilityZone), err)) + errs = append(errs, fmt.Errorf("%s: %w", aws.ToString(apiObject.AvailabilityZone), err)) } } @@ -251,7 +225,7 @@ func enableFastSnapshotRestoreItemsError(apiObjects []awstypes.EnableFastSnapsho for _, apiObject := range apiObjects { if err := enableFastSnapshotRestoreStateItemsError(apiObject.FastSnapshotRestoreStateErrors); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", aws_sdkv2.ToString(apiObject.SnapshotId), err)) + errs = append(errs, fmt.Errorf("%s: %w", aws.ToString(apiObject.SnapshotId), err)) } } @@ -259,7 +233,7 @@ func enableFastSnapshotRestoreItemsError(apiObjects []awstypes.EnableFastSnapsho } func networkACLEntryAlreadyExistsError(naclID string, egress bool, ruleNumber int) error { - return awserr.New(errCodeNetworkACLEntryAlreadyExists, fmt.Sprintf("EC2 Network ACL (%s) Rule (egress: %t)(%d) already exists", naclID, egress, ruleNumber), nil) + return errs.APIError(errCodeNetworkACLEntryAlreadyExists, fmt.Sprintf("EC2 Network ACL (%s) Rule (egress: %t)(%d) already exists", naclID, egress, ruleNumber)) } func routeAlreadyExistsError(routeTableID, destination string) error { diff --git a/internal/service/ec2/errors_test.go b/internal/service/ec2/errors_test.go index 243711e8872..0bfa131a6bf 100644 --- a/internal/service/ec2/errors_test.go +++ b/internal/service/ec2/errors_test.go @@ -6,16 +6,16 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" ) func TestUnsuccessfulItemError(t *testing.T) { t.Parallel() - unsuccessfulItemError := &ec2.UnsuccessfulItemError{ + unsuccessfulItemError := &awstypes.UnsuccessfulItemError{ Code: aws.String("test code"), Message: aws.String("test message"), } @@ -36,7 +36,7 @@ func TestUnsuccessfulItemsError(t *testing.T) { testCases := []struct { Name string - Items []*ec2.UnsuccessfulItem + Items []awstypes.UnsuccessfulItem Expected bool }{ { @@ -44,7 +44,7 @@ func TestUnsuccessfulItemsError(t *testing.T) { }, { Name: "one item no error", - Items: []*ec2.UnsuccessfulItem{ + Items: []awstypes.UnsuccessfulItem{ { ResourceId: aws.String("test resource"), }, @@ -52,9 +52,9 @@ func TestUnsuccessfulItemsError(t *testing.T) { }, { Name: "one item", - Items: []*ec2.UnsuccessfulItem{ + Items: []awstypes.UnsuccessfulItem{ { - Error: &ec2.UnsuccessfulItemError{ + Error: &awstypes.UnsuccessfulItemError{ Code: aws.String("test code"), Message: aws.String("test message"), }, @@ -65,12 +65,12 @@ func TestUnsuccessfulItemsError(t *testing.T) { }, { Name: "two items, first no error", - Items: []*ec2.UnsuccessfulItem{ + Items: []awstypes.UnsuccessfulItem{ { ResourceId: aws.String("test resource 1"), }, { - Error: &ec2.UnsuccessfulItemError{ + Error: &awstypes.UnsuccessfulItemError{ Code: aws.String("test code"), Message: aws.String("test message"), }, @@ -81,16 +81,16 @@ func TestUnsuccessfulItemsError(t *testing.T) { }, { Name: "two items, first not as expected", - Items: []*ec2.UnsuccessfulItem{ + Items: []awstypes.UnsuccessfulItem{ { - Error: &ec2.UnsuccessfulItemError{ + Error: &awstypes.UnsuccessfulItemError{ Code: aws.String("not what is required"), Message: aws.String("not what is wanted"), }, ResourceId: aws.String("test resource 1"), }, { - Error: &ec2.UnsuccessfulItemError{ + Error: &awstypes.UnsuccessfulItemError{ Code: aws.String("test code"), Message: aws.String("test message"), }, @@ -100,16 +100,16 @@ func TestUnsuccessfulItemsError(t *testing.T) { }, { Name: "two items, first as expected", - Items: []*ec2.UnsuccessfulItem{ + Items: []awstypes.UnsuccessfulItem{ { - Error: &ec2.UnsuccessfulItemError{ + Error: &awstypes.UnsuccessfulItemError{ Code: aws.String("test code"), Message: aws.String("test message"), }, ResourceId: aws.String("test resource 1"), }, { - Error: &ec2.UnsuccessfulItemError{ + Error: &awstypes.UnsuccessfulItemError{ Code: aws.String("not what is required"), Message: aws.String("not what is wanted"), }, diff --git a/internal/service/ec2/exports.go b/internal/service/ec2/exports.go index 681dc9a9918..67f3542909d 100644 --- a/internal/service/ec2/exports.go +++ b/internal/service/ec2/exports.go @@ -10,20 +10,23 @@ var ( DetachNetworkInterface = detachNetworkInterface FindImageByID = findImageByID FindInstanceByID = findInstanceByID + FindNetworkInterfaces = findNetworkInterfaces FindNetworkInterfacesByAttachmentInstanceOwnerIDAndDescription = findNetworkInterfacesByAttachmentInstanceOwnerIDAndDescription - FindNetworkInterfacesV2 = findNetworkInterfaces FindSecurityGroupByDescriptionAndVPCID = findSecurityGroupByDescriptionAndVPCID FindSecurityGroupByNameAndVPCID = findSecurityGroupByNameAndVPCID FindSecurityGroupByNameAndVPCIDAndOwnerID = findSecurityGroupByNameAndVPCIDAndOwnerID - FindVPCByIDV2 = findVPCByID + FindSecurityGroups = findSecurityGroups + FindSubnetByID = findSubnetByID + FindVPCByID = findVPCByID FindVPCEndpointByID = findVPCEndpointByID - NewCustomFilterListFrameworkV2 = newCustomFilterListFrameworkV2 + NetworkInterfaceDetachedTimeout = networkInterfaceDetachedTimeout + NewCustomFilterListFramework = newCustomFilterListFramework NewFilter = newFilter - NewFilterV2 = newFilterV2 ResourceAMI = resourceAMI ResourceSecurityGroup = resourceSecurityGroup ResourceTransitGateway = resourceTransitGateway ResourceTransitGatewayConnectPeer = resourceTransitGatewayConnectPeer + ResourceVPC = resourceVPC VPCEndpointCreationTimeout = vpcEndpointCreationTimeout WaitVPCEndpointAvailable = waitVPCEndpointAvailable ) diff --git a/internal/service/ec2/exports_test.go b/internal/service/ec2/exports_test.go index 7ddb9f53a2f..776ebab657c 100644 --- a/internal/service/ec2/exports_test.go +++ b/internal/service/ec2/exports_test.go @@ -5,96 +5,125 @@ package ec2 // Exports for use in tests only. var ( - ResourceAMICopy = resourceAMICopy - ResourceAMIFromInstance = resourceAMIFromInstance - ResourceAMILaunchPermission = resourceAMILaunchPermission - ResourceAvailabilityZoneGroup = resourceAvailabilityZoneGroup - ResourceCapacityReservation = resourceCapacityReservation - ResourceCarrierGateway = resourceCarrierGateway - ResourceClientVPNAuthorizationRule = resourceClientVPNAuthorizationRule - ResourceClientVPNEndpoint = resourceClientVPNEndpoint - ResourceClientVPNNetworkAssociation = resourceClientVPNNetworkAssociation - ResourceClientVPNRoute = resourceClientVPNRoute - ResourceCustomerGateway = resourceCustomerGateway - ResourceDefaultNetworkACL = resourceDefaultNetworkACL - ResourceDefaultRouteTable = resourceDefaultRouteTable - ResourceEBSDefaultKMSKey = resourceEBSDefaultKMSKey - ResourceEBSEncryptionByDefault = resourceEBSEncryptionByDefault - ResourceEBSFastSnapshotRestore = newEBSFastSnapshotRestoreResource - ResourceEBSSnapshot = resourceEBSSnapshot - ResourceEBSSnapshotCopy = resourceEBSSnapshotCopy - ResourceEBSSnapshotImport = resourceEBSSnapshotImport - ResourceEBSVolume = resourceEBSVolume - ResourceEIP = resourceEIP - ResourceEIPAssociation = resourceEIPAssociation - ResourceEIPDomainName = newEIPDomainNameResource - ResourceFleet = resourceFleet - ResourceHost = resourceHost - ResourceIPAM = resourceIPAM - ResourceIPAMOrganizationAdminAccount = resourceIPAMOrganizationAdminAccount - ResourceIPAMPool = resourceIPAMPool - ResourceIPAMPoolCIDR = resourceIPAMPoolCIDR - ResourceIPAMPoolCIDRAllocation = resourceIPAMPoolCIDRAllocation - ResourceIPAMPreviewNextCIDR = resourceIPAMPreviewNextCIDR - ResourceIPAMResourceDiscovery = resourceIPAMResourceDiscovery - ResourceIPAMResourceDiscoveryAssociation = resourceIPAMResourceDiscoveryAssociation - ResourceIPAMScope = resourceIPAMScope - ResourceImageBlockPublicAccess = resourceImageBlockPublicAccess - ResourceInstance = resourceInstance - ResourceInstanceConnectEndpoint = newInstanceConnectEndpointResource - ResourceInstanceMetadataDefaults = newInstanceMetadataDefaultsResource - ResourceInstanceState = resourceInstanceState - ResourceKeyPair = resourceKeyPair - ResourceLaunchTemplate = resourceLaunchTemplate - ResourceLocalGatewayRoute = resourceLocalGatewayRoute - ResourceLocalGatewayRouteTableVPCAssociation = resourceLocalGatewayRouteTableVPCAssociation - ResourceMainRouteTableAssociation = resourceMainRouteTableAssociation - ResourceNetworkACL = resourceNetworkACL - ResourceNetworkACLRule = resourceNetworkACLRule - ResourceNetworkInsightsAnalysis = resourceNetworkInsightsAnalysis - ResourceNetworkInsightsPath = resourceNetworkInsightsPath - ResourceNetworkInterface = resourceNetworkInterface - ResourcePlacementGroup = resourcePlacementGroup - ResourceRoute = resourceRoute - ResourceRouteTable = resourceRouteTable - ResourceSecurityGroupEgressRule = newSecurityGroupEgressRuleResource - ResourceSecurityGroupIngressRule = newSecurityGroupIngressRuleResource - ResourceSnapshotCreateVolumePermission = resourceSnapshotCreateVolumePermission - ResourceSpotDataFeedSubscription = resourceSpotDataFeedSubscription - ResourceSpotFleetRequest = resourceSpotFleetRequest - ResourceSpotInstanceRequest = resourceSpotInstanceRequest - ResourceTag = resourceTag - ResourceTrafficMirrorFilter = resourceTrafficMirrorFilter - ResourceTrafficMirrorFilterRule = resourceTrafficMirrorFilterRule - ResourceTrafficMirrorSession = resourceTrafficMirrorSession - ResourceTrafficMirrorTarget = resourceTrafficMirrorTarget - ResourceTransitGatewayConnect = resourceTransitGatewayConnect - ResourceTransitGatewayMulticastDomain = resourceTransitGatewayMulticastDomain - ResourceTransitGatewayMulticastDomainAssociation = resourceTransitGatewayMulticastDomainAssociation - ResourceTransitGatewayMulticastGroupMember = resourceTransitGatewayMulticastGroupMember - ResourceTransitGatewayMulticastGroupSource = resourceTransitGatewayMulticastGroupSource - ResourceTransitGatewayPeeringAttachment = resourceTransitGatewayPeeringAttachment - ResourceTransitGatewayPeeringAttachmentAccepter = resourceTransitGatewayPeeringAttachmentAccepter - ResourceTransitGatewayPolicyTable = resourceTransitGatewayPolicyTable - ResourceTransitGatewayPolicyTableAssociation = resourceTransitGatewayPolicyTableAssociation - ResourceTransitGatewayPrefixListReference = resourceTransitGatewayPrefixListReference - ResourceTransitGatewayRoute = resourceTransitGatewayRoute - ResourceTransitGatewayRouteTable = resourceTransitGatewayRouteTable - ResourceTransitGatewayRouteTableAssociation = resourceTransitGatewayRouteTableAssociation - ResourceTransitGatewayRouteTablePropagation = resourceTransitGatewayRouteTablePropagation - ResourceTransitGatewayVPCAttachment = resourceTransitGatewayVPCAttachment - ResourceTransitGatewayVPCAttachmentAccepter = resourceTransitGatewayVPCAttachmentAccepter - ResourceVPCEndpoint = resourceVPCEndpoint - ResourceVPNConnection = resourceVPNConnection - ResourceVPNConnectionRoute = resourceVPNConnectionRoute - ResourceVPNGateway = resourceVPNGateway - ResourceVPNGatewayAttachment = resourceVPNGatewayAttachment - ResourceVPNGatewayRoutePropagation = resourceVPNGatewayRoutePropagation - ResourceVolumeAttachment = resourceVolumeAttachment + ResourceAMICopy = resourceAMICopy + ResourceAMIFromInstance = resourceAMIFromInstance + ResourceAMILaunchPermission = resourceAMILaunchPermission + ResourceAvailabilityZoneGroup = resourceAvailabilityZoneGroup + ResourceCapacityReservation = resourceCapacityReservation + ResourceCarrierGateway = resourceCarrierGateway + ResourceClientVPNAuthorizationRule = resourceClientVPNAuthorizationRule + ResourceClientVPNEndpoint = resourceClientVPNEndpoint + ResourceClientVPNNetworkAssociation = resourceClientVPNNetworkAssociation + ResourceClientVPNRoute = resourceClientVPNRoute + ResourceCustomerGateway = resourceCustomerGateway + ResourceDefaultNetworkACL = resourceDefaultNetworkACL + ResourceDefaultRouteTable = resourceDefaultRouteTable + ResourceEBSDefaultKMSKey = resourceEBSDefaultKMSKey + ResourceEBSEncryptionByDefault = resourceEBSEncryptionByDefault + ResourceEBSFastSnapshotRestore = newEBSFastSnapshotRestoreResource + ResourceEBSSnapshot = resourceEBSSnapshot + ResourceEBSSnapshotCopy = resourceEBSSnapshotCopy + ResourceEBSSnapshotImport = resourceEBSSnapshotImport + ResourceEBSVolume = resourceEBSVolume + ResourceEIP = resourceEIP + ResourceEIPAssociation = resourceEIPAssociation + ResourceEIPDomainName = newEIPDomainNameResource + ResourceFleet = resourceFleet + ResourceFlowLog = resourceFlowLog + ResourceHost = resourceHost + ResourceIPAM = resourceIPAM + ResourceIPAMOrganizationAdminAccount = resourceIPAMOrganizationAdminAccount + ResourceIPAMPool = resourceIPAMPool + ResourceIPAMPoolCIDR = resourceIPAMPoolCIDR + ResourceIPAMPoolCIDRAllocation = resourceIPAMPoolCIDRAllocation + ResourceIPAMPreviewNextCIDR = resourceIPAMPreviewNextCIDR + ResourceIPAMResourceDiscovery = resourceIPAMResourceDiscovery + ResourceIPAMResourceDiscoveryAssociation = resourceIPAMResourceDiscoveryAssociation + ResourceIPAMScope = resourceIPAMScope + ResourceImageBlockPublicAccess = resourceImageBlockPublicAccess + ResourceInstance = resourceInstance + ResourceInstanceConnectEndpoint = newInstanceConnectEndpointResource + ResourceInstanceMetadataDefaults = newInstanceMetadataDefaultsResource + ResourceInstanceState = resourceInstanceState + ResourceInternetGateway = resourceInternetGateway + ResourceInternetGatewayAttachment = resourceInternetGatewayAttachment + ResourceKeyPair = resourceKeyPair + ResourceLaunchTemplate = resourceLaunchTemplate + ResourceLocalGatewayRoute = resourceLocalGatewayRoute + ResourceLocalGatewayRouteTableVPCAssociation = resourceLocalGatewayRouteTableVPCAssociation + ResourceMainRouteTableAssociation = resourceMainRouteTableAssociation + ResourceManagedPrefixList = resourceManagedPrefixList + ResourceManagedPrefixListEntry = resourceManagedPrefixListEntry + ResourceNATGateway = resourceNATGateway + ResourceNetworkACL = resourceNetworkACL + ResourceNetworkACLAssociation = resourceNetworkACLAssociation + ResourceNetworkACLRule = resourceNetworkACLRule + ResourceNetworkInsightsAnalysis = resourceNetworkInsightsAnalysis + ResourceNetworkInsightsPath = resourceNetworkInsightsPath + ResourceNetworkInterface = resourceNetworkInterface + ResourceNetworkInterfaceSGAttachment = resourceNetworkInterfaceSGAttachment + ResourceNetworkPerformanceMetricSubscription = resourceNetworkPerformanceMetricSubscription + ResourcePlacementGroup = resourcePlacementGroup + ResourceRoute = resourceRoute + ResourceRouteTable = resourceRouteTable + ResourceRouteTableAssociation = resourceRouteTableAssociation + ResourceSecurityGroupEgressRule = newSecurityGroupEgressRuleResource + ResourceSecurityGroupIngressRule = newSecurityGroupIngressRuleResource + ResourceSnapshotCreateVolumePermission = resourceSnapshotCreateVolumePermission + ResourceSpotDataFeedSubscription = resourceSpotDataFeedSubscription + ResourceSpotFleetRequest = resourceSpotFleetRequest + ResourceSpotInstanceRequest = resourceSpotInstanceRequest + ResourceSubnet = resourceSubnet + ResourceSubnetCIDRReservation = resourceSubnetCIDRReservation + ResourceTag = resourceTag + ResourceTrafficMirrorFilter = resourceTrafficMirrorFilter + ResourceTrafficMirrorFilterRule = resourceTrafficMirrorFilterRule + ResourceTrafficMirrorSession = resourceTrafficMirrorSession + ResourceTrafficMirrorTarget = resourceTrafficMirrorTarget + ResourceTransitGatewayConnect = resourceTransitGatewayConnect + ResourceTransitGatewayMulticastDomain = resourceTransitGatewayMulticastDomain + ResourceTransitGatewayMulticastDomainAssociation = resourceTransitGatewayMulticastDomainAssociation + ResourceTransitGatewayMulticastGroupMember = resourceTransitGatewayMulticastGroupMember + ResourceTransitGatewayMulticastGroupSource = resourceTransitGatewayMulticastGroupSource + ResourceTransitGatewayPeeringAttachment = resourceTransitGatewayPeeringAttachment + ResourceTransitGatewayPeeringAttachmentAccepter = resourceTransitGatewayPeeringAttachmentAccepter + ResourceTransitGatewayPolicyTable = resourceTransitGatewayPolicyTable + ResourceTransitGatewayPolicyTableAssociation = resourceTransitGatewayPolicyTableAssociation + ResourceTransitGatewayPrefixListReference = resourceTransitGatewayPrefixListReference + ResourceTransitGatewayRoute = resourceTransitGatewayRoute + ResourceTransitGatewayRouteTable = resourceTransitGatewayRouteTable + ResourceTransitGatewayRouteTableAssociation = resourceTransitGatewayRouteTableAssociation + ResourceTransitGatewayRouteTablePropagation = resourceTransitGatewayRouteTablePropagation + ResourceTransitGatewayVPCAttachment = resourceTransitGatewayVPCAttachment + ResourceTransitGatewayVPCAttachmentAccepter = resourceTransitGatewayVPCAttachmentAccepter + ResourceVPCDHCPOptions = resourceVPCDHCPOptions + ResourceVPCDHCPOptionsAssociation = resourceVPCDHCPOptionsAssociation + ResourceVPCEndpoint = resourceVPCEndpoint + ResourceVPCEndpointPolicy = resourceVPCEndpointPolicy + ResourceVPCEndpointRouteTableAssociation = resourceVPCEndpointRouteTableAssociation + ResourceVPCEndpointSecurityGroupAssociation = resourceVPCEndpointSecurityGroupAssociation + ResourceVPCEndpointService = resourceVPCEndpointService + ResourceVPCEndpointSubnetAssociation = resourceVPCEndpointSubnetAssociation + ResourceVPCIPv4CIDRBlockAssociation = resourceVPCIPv4CIDRBlockAssociation + ResourceVPCPeeringConnection = resourceVPCPeeringConnection + ResourceVPNConnection = resourceVPNConnection + ResourceVPNConnectionRoute = resourceVPNConnectionRoute + ResourceVPNGateway = resourceVPNGateway + ResourceVPNGatewayAttachment = resourceVPNGatewayAttachment + ResourceVPNGatewayRoutePropagation = resourceVPNGatewayRoutePropagation + ResourceVerifiedAccessEndpoint = resourceVerifiedAccessEndpoint + ResourceVerifiedAccessGroup = resourceVerifiedAccessGroup + ResourceVerifiedAccessInstance = resourceVerifiedAccessInstance + ResourceVerifiedAccessInstanceLoggingConfiguration = resourceVerifiedAccessInstanceLoggingConfiguration + ResourceVerifiedAccessInstanceTrustProviderAttachment = resourceVerifiedAccessInstanceTrustProviderAttachment + ResourceVerifiedAccessTrustProvider = resourceVerifiedAccessTrustProvider + ResourceVolumeAttachment = resourceVolumeAttachment CustomFiltersSchema = customFiltersSchema + CustomerGatewayConfigurationToTunnelInfo = customerGatewayConfigurationToTunnelInfo ErrCodeDefaultSubnetAlreadyExistsInAvailabilityZone = errCodeDefaultSubnetAlreadyExistsInAvailabilityZone ErrCodeInvalidSpotDatafeedNotFound = errCodeInvalidSpotDatafeedNotFound + ExpandIPPerms = expandIPPerms FindAvailabilityZones = findAvailabilityZones FindCapacityReservationByID = findCapacityReservationByID FindCarrierGatewayByID = findCarrierGatewayByID @@ -104,13 +133,16 @@ var ( FindClientVPNRouteByThreePartKey = findClientVPNRouteByThreePartKey FindCreateSnapshotCreateVolumePermissionByTwoPartKey = findCreateSnapshotCreateVolumePermissionByTwoPartKey FindCustomerGatewayByID = findCustomerGatewayByID + FindDHCPOptionsByID = findDHCPOptionsByID FindEBSVolumeAttachment = findVolumeAttachment FindEBSVolumeByID = findEBSVolumeByID FindEIPByAllocationID = findEIPByAllocationID FindEIPByAssociationID = findEIPByAssociationID FindEIPDomainNameAttributeByAllocationID = findEIPDomainNameAttributeByAllocationID + FindEgressOnlyInternetGatewayByID = findEgressOnlyInternetGatewayByID FindFastSnapshotRestoreByTwoPartKey = findFastSnapshotRestoreByTwoPartKey FindFleetByID = findFleetByID + FindFlowLogByID = findFlowLogByID FindHostByID = findHostByID FindIPAMByID = findIPAMByID FindIPAMPoolAllocationByTwoPartKey = findIPAMPoolAllocationByTwoPartKey @@ -123,15 +155,24 @@ var ( FindInstanceConnectEndpointByID = findInstanceConnectEndpointByID FindInstanceMetadataDefaults = findInstanceMetadataDefaults FindInstanceStateByID = findInstanceStateByID + FindInternetGateway = findInternetGateway + FindInternetGatewayAttachment = findInternetGatewayAttachment + FindInternetGatewayByID = findInternetGatewayByID FindKeyPairByName = findKeyPairByName FindLaunchTemplateByID = findLaunchTemplateByID FindLocalGatewayRouteByTwoPartKey = findLocalGatewayRouteByTwoPartKey FindLocalGatewayRouteTableVPCAssociationByID = findLocalGatewayRouteTableVPCAssociationByID FindMainRouteTableAssociationByID = findMainRouteTableAssociationByID - FindNetworkACLByIDV2 = findNetworkACLByID + FindManagedPrefixListByID = findManagedPrefixListByID + FindManagedPrefixListEntryByIDAndCIDR = findManagedPrefixListEntryByIDAndCIDR + FindNATGatewayByID = findNATGatewayByID + FindNetworkACLAssociationByID = findNetworkACLAssociationByID + FindNetworkACLByID = findNetworkACLByID + FindNetworkACLEntryByThreePartKey = findNetworkACLEntryByThreePartKey FindNetworkInsightsAnalysisByID = findNetworkInsightsAnalysisByID FindNetworkInsightsPathByID = findNetworkInsightsPathByID - FindNetworkInterfaceByIDV2 = findNetworkInterfaceByID + FindNetworkInterfaceByID = findNetworkInterfaceByID + FindNetworkInterfaceSecurityGroup = findNetworkInterfaceSecurityGroup FindNetworkPerformanceMetricSubscriptionByFourPartKey = findNetworkPerformanceMetricSubscriptionByFourPartKey FindPlacementGroupByName = findPlacementGroupByName FindPublicIPv4Pools = findPublicIPv4Pools @@ -140,13 +181,17 @@ var ( FindRouteByPrefixListIDDestination = findRouteByPrefixListIDDestination FindRouteTableAssociationByID = findRouteTableAssociationByID FindRouteTableByID = findRouteTableByID + FindSecurityGroupByID = findSecurityGroupByID + FindSecurityGroupEgressRuleByID = findSecurityGroupEgressRuleByID + FindSecurityGroupIngressRuleByID = findSecurityGroupIngressRuleByID FindSnapshot = findSnapshot FindSnapshotByID = findSnapshotByID FindSpotDatafeedSubscription = findSpotDatafeedSubscription FindSpotFleetRequestByID = findSpotFleetRequestByID FindSpotFleetRequests = findSpotFleetRequests FindSpotInstanceRequestByID = findSpotInstanceRequestByID - FindSubnetsV2 = findSubnets + FindSubnetCIDRReservationBySubnetIDAndReservationID = findSubnetCIDRReservationBySubnetIDAndReservationID + FindSubnets = findSubnets FindTag = findTag FindTrafficMirrorFilterByID = findTrafficMirrorFilterByID FindTrafficMirrorFilterRuleByTwoPartKey = findTrafficMirrorFilterRuleByTwoPartKey @@ -168,6 +213,8 @@ var ( FindTransitGatewayRouteTablePropagationByTwoPartKey = findTransitGatewayRouteTablePropagationByTwoPartKey FindTransitGatewayStaticRoute = findTransitGatewayStaticRoute FindTransitGatewayVPCAttachmentByID = findTransitGatewayVPCAttachmentByID + FindVPCCIDRBlockAssociationByID = findVPCCIDRBlockAssociationByID + FindVPCDHCPOptionsAssociation = findVPCDHCPOptionsAssociation FindVPCEndpointConnectionByServiceIDAndVPCEndpointID = findVPCEndpointConnectionByServiceIDAndVPCEndpointID FindVPCEndpointConnectionNotificationByID = findVPCEndpointConnectionNotificationByID FindVPCEndpointRouteTableAssociationExists = findVPCEndpointRouteTableAssociationExists @@ -175,7 +222,8 @@ var ( FindVPCEndpointServiceConfigurationByID = findVPCEndpointServiceConfigurationByID FindVPCEndpointServicePermission = findVPCEndpointServicePermission FindVPCEndpointSubnetAssociationExists = findVPCEndpointSubnetAssociationExists - FindVPCIPv6CIDRBlockAssociationByIDV2 = findVPCIPv6CIDRBlockAssociationByID + FindVPCIPv6CIDRBlockAssociationByID = findVPCIPv6CIDRBlockAssociationByID + FindVPCPeeringConnectionByID = findVPCPeeringConnectionByID FindVPNConnectionByID = findVPNConnectionByID FindVPNConnectionRouteByTwoPartKey = findVPNConnectionRouteByTwoPartKey FindVPNGatewayByID = findVPNGatewayByID @@ -189,19 +237,44 @@ var ( FindVerifiedAccessTrustProviderByID = findVerifiedAccessTrustProviderByID FindVolumeAttachmentInstanceByID = findVolumeAttachmentInstanceByID FlattenNetworkInterfacePrivateIPAddresses = flattenNetworkInterfacePrivateIPAddresses + FlattenSecurityGroups = flattenSecurityGroups IPAMServicePrincipal = ipamServicePrincipal + InstanceMigrateState = instanceMigrateState + InternetGatewayAttachmentParseResourceID = internetGatewayAttachmentParseResourceID + KeyPairMigrateState = keyPairMigrateState + ManagedPrefixListEntryCreateResourceID = managedPrefixListEntryCreateResourceID + ManagedPrefixListEntryParseResourceID = managedPrefixListEntryParseResourceID + MatchRules = matchRules + NetworkACLRuleImportIDSeparator = networkACLRuleImportIDSeparator NewAttributeFilterList = newAttributeFilterList - NewAttributeFilterListV2 = newAttributeFilterListV2 NewCustomFilterList = newCustomFilterList NewTagFilterList = newTagFilterList + OpenSSHPublicKeysEqual = openSSHPublicKeysEqual + ParseInstanceType = parseInstanceType ProtocolForValue = protocolForValue + ProtocolStateFunc = protocolStateFunc + SecurityGroupCollapseRules = securityGroupCollapseRules + SecurityGroupExpandRules = securityGroupExpandRules + SecurityGroupIPPermGather = securityGroupIPPermGather + SecurityGroupMigrateState = securityGroupMigrateState + SecurityGroupRuleCreateID = securityGroupRuleCreateID + SecurityGroupRuleHash = securityGroupRuleHash + SecurityGroupRuleMigrateState = securityGroupRuleMigrateState + SpotFleetRequestMigrateState = spotFleetRequestMigrateState StopEBSVolumeAttachmentInstance = stopVolumeAttachmentInstance StopInstance = stopInstance + SubnetMigrateState = subnetMigrateState + UnsuccessfulItemError = unsuccessfulItemError + UnsuccessfulItemsError = unsuccessfulItemsError UpdateTags = updateTags - UpdateTagsV2 = updateTagsV2 + VPCDHCPOptionsAssociationParseResourceID = vpcDHCPOptionsAssociationParseResourceID + VPCMigrateState = vpcMigrateState + VPNGatewayRoutePropagationParseID = vpnGatewayRoutePropagationParseID WaitVolumeAttachmentCreated = waitVolumeAttachmentCreated ) type ( - IPProtocol = ipProtocol + GroupIdentifier = groupIdentifier + IPProtocol = ipProtocol + TunnelInfo = tunnelInfo ) diff --git a/internal/service/ec2/filters.go b/internal/service/ec2/filters.go index 41609f1f5e0..6a2d26c5105 100644 --- a/internal/service/ec2/filters.go +++ b/internal/service/ec2/filters.go @@ -7,10 +7,8 @@ import ( "context" "sort" - aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws" awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - ec2_sdkv1 "github.com/aws/aws-sdk-go/service/ec2" datasourceschema "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/tfsdk" "github.com/hashicorp/terraform-plugin-framework/types" @@ -22,16 +20,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -func newFilter(name string, values []string) *ec2_sdkv1.Filter { - return &ec2_sdkv1.Filter{ - Name: aws_sdkv1.String(name), - Values: aws_sdkv1.StringSlice(values), - } -} - -func newFilterV2(name string, values []string) awstypes.Filter { +func newFilter(name string, values []string) awstypes.Filter { return awstypes.Filter{ - Name: aws_sdkv2.String(name), + Name: aws.String(name), Values: values, } } @@ -56,15 +47,9 @@ func newFilterV2(name string, values []string) awstypes.Filter { // tags { // Name = "my-awesome-subnet" // } -func newTagFilterList(tags []*ec2_sdkv1.Tag) []*ec2_sdkv1.Filter { - return tfslices.ApplyToAll(tags, func(tag *ec2_sdkv1.Tag) *ec2_sdkv1.Filter { - return newFilter("tag:"+aws_sdkv1.StringValue(tag.Key), []string{aws_sdkv1.StringValue(tag.Value)}) - }) -} - -func newTagFilterListV2(tags []awstypes.Tag) []awstypes.Filter { +func newTagFilterList(tags []awstypes.Tag) []awstypes.Filter { return tfslices.ApplyToAll(tags, func(tag awstypes.Tag) awstypes.Filter { - return newFilterV2("tag:"+aws_sdkv2.ToString(tag.Key), []string{aws_sdkv2.ToString(tag.Value)}) + return newFilter("tag:"+aws.ToString(tag.Key), []string{aws.ToString(tag.Value)}) }) } @@ -84,7 +69,7 @@ func attributeFiltersFromMultimap(m map[string][]string) []awstypes.Filter { filters := []awstypes.Filter{} for k, v := range m { - filters = append(filters, newFilterV2(k, v)) + filters = append(filters, newFilter(k, v)) } return filters @@ -92,7 +77,7 @@ func attributeFiltersFromMultimap(m map[string][]string) []awstypes.Filter { // tagFilters returns an array of EC2 Filter objects to be used when listing resources by tag. func tagFilters(ctx context.Context) []awstypes.Filter { - return newTagFilterListV2(getTagsInV2(ctx)) + return newTagFilterList(getTagsIn(ctx)) } // customFiltersSchema returns a *schema.Schema that represents @@ -186,67 +171,18 @@ type customFilterModel struct { // This function is intended only to be used in conjunction with // CustomFiltersSchema. See the docs on that function for more details // on the configuration pattern this is intended to support. -func newCustomFilterList(s *schema.Set) []*ec2_sdkv1.Filter { - if s == nil { - return []*ec2_sdkv1.Filter{} - } - - return tfslices.ApplyToAll(s.List(), func(tfList interface{}) *ec2_sdkv1.Filter { - tfMap := tfList.(map[string]interface{}) - return newFilter(tfMap[names.AttrName].(string), flex.ExpandStringValueSet(tfMap[names.AttrValues].(*schema.Set))) - }) -} - -// newCustomFilterListV2 takes the set value extracted from a schema -// attribute conforming to the schema returned by CustomFiltersSchema, -// and transforms it into a []*ec2.Filter representing the same filter -// expressions which is ready to pass into the "Filters" attribute on most -// of the "Describe..." functions in the EC2 API. -// -// This function is intended only to be used in conjunction with -// CustomFiltersSchema. See the docs on that function for more details -// on the configuration pattern this is intended to support. -func newCustomFilterListV2(s *schema.Set) []awstypes.Filter { +func newCustomFilterList(s *schema.Set) []awstypes.Filter { if s == nil { return []awstypes.Filter{} } return tfslices.ApplyToAll(s.List(), func(tfList interface{}) awstypes.Filter { tfMap := tfList.(map[string]interface{}) - return newFilterV2(tfMap[names.AttrName].(string), flex.ExpandStringValueEmptySet(tfMap[names.AttrValues].(*schema.Set))) + return newFilter(tfMap[names.AttrName].(string), flex.ExpandStringValueEmptySet(tfMap[names.AttrValues].(*schema.Set))) }) } -func newCustomFilterListFramework(ctx context.Context, filterSet types.Set) []*ec2_sdkv1.Filter { - if filterSet.IsNull() || filterSet.IsUnknown() { - return nil - } - - var filters []*ec2_sdkv1.Filter - - for _, v := range filterSet.Elements() { - var data customFilterModel - - if tfsdk.ValueAs(ctx, v, &data).HasError() { - continue - } - - if data.Name.IsNull() || data.Name.IsUnknown() { - continue - } - - if v := fwflex.ExpandFrameworkStringSet(ctx, data.Values); v != nil { - filters = append(filters, &ec2_sdkv1.Filter{ - Name: fwflex.StringFromFramework(ctx, data.Name), - Values: v, - }) - } - } - - return filters -} - -func newCustomFilterListFrameworkV2(ctx context.Context, filterSet types.Set) []awstypes.Filter { +func newCustomFilterListFramework(ctx context.Context, filterSet types.Set) []awstypes.Filter { if filterSet.IsNull() || filterSet.IsUnknown() { return nil } @@ -296,26 +232,7 @@ func newCustomFilterListFrameworkV2(ctx context.Context, filterSet types.Set) [] // for the "Filters" attribute on most of the "Describe..." API functions in // the EC2 API, to aid in the implementation of Terraform data sources that // retrieve data about EC2 objects. -func newAttributeFilterList(m map[string]string) []*ec2_sdkv1.Filter { - var filters []*ec2_sdkv1.Filter - - // Sort the filters by name to make the output deterministic. - names := tfmaps.Keys(m) - sort.Strings(names) - - for _, name := range names { - value := m[name] - if value == "" { - continue - } - - filters = append(filters, newFilter(name, []string{value})) - } - - return filters -} - -func newAttributeFilterListV2(m map[string]string) []awstypes.Filter { +func newAttributeFilterList(m map[string]string) []awstypes.Filter { var filters []awstypes.Filter // Sort the filters by name to make the output deterministic. @@ -328,7 +245,7 @@ func newAttributeFilterListV2(m map[string]string) []awstypes.Filter { continue } - filters = append(filters, newFilterV2(name, []string{value})) + filters = append(filters, newFilter(name, []string{value})) } return filters diff --git a/internal/service/ec2/filters_test.go b/internal/service/ec2/filters_test.go index 072abc7f235..3cce9e771ed 100644 --- a/internal/service/ec2/filters_test.go +++ b/internal/service/ec2/filters_test.go @@ -6,8 +6,8 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/google/go-cmp/cmp" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" @@ -19,7 +19,7 @@ func TestNewAttributeFilterList(t *testing.T) { type TestCase struct { Attrs map[string]string - Expected []*ec2.Filter + Expected []awstypes.Filter } testCases := []TestCase{ { @@ -27,14 +27,14 @@ func TestNewAttributeFilterList(t *testing.T) { "foo": "bar", "baz": "boo", }, - []*ec2.Filter{ + []awstypes.Filter{ { Name: aws.String("baz"), - Values: []*string{aws.String("boo")}, + Values: []string{"boo"}, }, { Name: aws.String("foo"), - Values: []*string{aws.String("bar")}, + Values: []string{"bar"}, }, }, }, @@ -43,10 +43,10 @@ func TestNewAttributeFilterList(t *testing.T) { "foo": "bar", "baz": "", }, - []*ec2.Filter{ + []awstypes.Filter{ { Name: aws.String("foo"), - Values: []*string{aws.String("bar")}, + Values: []string{"bar"}, }, }, }, @@ -55,7 +55,7 @@ func TestNewAttributeFilterList(t *testing.T) { for _, testCase := range testCases { result := tfec2.NewAttributeFilterList(testCase.Attrs) - if diff := cmp.Diff(result, testCase.Expected); diff != "" { + if diff := cmp.Diff(result, testCase.Expected, cmp.AllowUnexported(awstypes.Filter{})); diff != "" { t.Errorf("unexpected diff (+wanted, -got): %s", diff) } } @@ -65,12 +65,12 @@ func TestNewTagFilterList(t *testing.T) { t.Parallel() type TestCase struct { - Tags []*ec2.Tag - Expected []*ec2.Filter + Tags []awstypes.Tag + Expected []awstypes.Filter } testCases := []TestCase{ { - []*ec2.Tag{ + []awstypes.Tag{ { Key: aws.String("foo"), Value: aws.String("bar"), @@ -80,14 +80,14 @@ func TestNewTagFilterList(t *testing.T) { Value: aws.String("boo"), }, }, - []*ec2.Filter{ + []awstypes.Filter{ { Name: aws.String("tag:foo"), - Values: []*string{aws.String("bar")}, + Values: []string{"bar"}, }, { Name: aws.String("tag:baz"), - Values: []*string{aws.String("boo")}, + Values: []string{"boo"}, }, }, }, @@ -96,7 +96,7 @@ func TestNewTagFilterList(t *testing.T) { for _, testCase := range testCases { result := tfec2.NewTagFilterList(testCase.Tags) - if diff := cmp.Diff(result, testCase.Expected); diff != "" { + if diff := cmp.Diff(result, testCase.Expected, cmp.AllowUnexported(awstypes.Filter{})); diff != "" { t.Errorf("unexpected diff (+wanted, -got): %s", diff) } } @@ -135,7 +135,7 @@ func TestNewCustomFilterList(t *testing.T) { names.AttrValues: valuesSet("cheese"), }) - expected := []*ec2.Filter{ + expected := []awstypes.Filter{ // These are produced in the deterministic order guaranteed // by schema.Set.List(), which happens to produce them in // the following order for our current input. If this test @@ -143,16 +143,16 @@ func TestNewCustomFilterList(t *testing.T) { // will likely be emitted in a different order, which is fine. { Name: aws.String("pizza"), - Values: []*string{aws.String("cheese")}, + Values: []string{"cheese"}, }, { Name: aws.String("foo"), - Values: []*string{aws.String("bar"), aws.String("baz")}, + Values: []string{"bar", "baz"}, }, } result := tfec2.NewCustomFilterList(filters) - if diff := cmp.Diff(result, expected); diff != "" { + if diff := cmp.Diff(result, expected, cmp.AllowUnexported(awstypes.Filter{})); diff != "" { t.Errorf("unexpected diff (+wanted, -got): %s", diff) } } diff --git a/internal/service/ec2/find.go b/internal/service/ec2/find.go index af8ed4a134d..6f94096cfb3 100644 --- a/internal/service/ec2/find.go +++ b/internal/service/ec2/find.go @@ -6,205 +6,220 @@ package ec2 import ( "context" "fmt" + "slices" "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" + tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" + "github.com/hashicorp/terraform-provider-aws/internal/types" + "github.com/hashicorp/terraform-provider-aws/names" ) -// -// Move functions to findv2.go as they are migrated to AWS SDK for Go v2. -// - -func FindNetworkACL(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeNetworkAclsInput) (*ec2.NetworkAcl, error) { - output, err := FindNetworkACLs(ctx, conn, input) +func findAvailabilityZones(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAvailabilityZonesInput) ([]awstypes.AvailabilityZone, error) { + output, err := conn.DescribeAvailabilityZones(ctx, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) -} - -func FindNetworkACLs(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeNetworkAclsInput) ([]*ec2.NetworkAcl, error) { - var output []*ec2.NetworkAcl - - err := conn.DescribeNetworkAclsPagesWithContext(ctx, input, func(page *ec2.DescribeNetworkAclsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - for _, v := range page.NetworkAcls { - if v == nil { - continue - } - - output = append(output, v) - } + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } - return !lastPage - }) + return output.AvailabilityZones, nil +} - if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkACLIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } +func findAvailabilityZone(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAvailabilityZonesInput) (*awstypes.AvailabilityZone, error) { + output, err := findAvailabilityZones(ctx, conn, input) if err != nil { return nil, err } - return output, nil + return tfresource.AssertSingleValueResult(output) } -func FindNetworkACLByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.NetworkAcl, error) { - input := &ec2.DescribeNetworkAclsInput{ - NetworkAclIds: aws.StringSlice([]string{id}), +func findAvailabilityZoneGroupByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.AvailabilityZone, error) { + input := &ec2.DescribeAvailabilityZonesInput{ + AllAvailabilityZones: aws.Bool(true), + Filters: newAttributeFilterList(map[string]string{ + "group-name": name, + }), } - output, err := FindNetworkACL(ctx, conn, input) + output, err := findAvailabilityZones(ctx, conn, input) if err != nil { return nil, err } + if len(output) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + // An AZ group may contain more than one AZ. + availabilityZone := output[0] + // Eventual consistency check. - if aws.StringValue(output.NetworkAclId) != id { + if aws.ToString(availabilityZone.GroupName) != name { return nil, &retry.NotFoundError{ LastRequest: input, } } - return output, nil + return &availabilityZone, nil } -func FindNetworkACLAssociationByID(ctx context.Context, conn *ec2.EC2, associationID string) (*ec2.NetworkAclAssociation, error) { - input := &ec2.DescribeNetworkAclsInput{ - Filters: newAttributeFilterList(map[string]string{ - "association.association-id": associationID, - }), - } - - output, err := FindNetworkACL(ctx, conn, input) +func findCapacityReservation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCapacityReservationsInput) (*awstypes.CapacityReservation, error) { + output, err := findCapacityReservations(ctx, conn, input) if err != nil { return nil, err } - for _, v := range output.Associations { - if aws.StringValue(v.NetworkAclAssociationId) == associationID { - return v, nil + return tfresource.AssertSingleValueResult(output) +} + +func findCapacityReservations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCapacityReservationsInput) ([]awstypes.CapacityReservation, error) { + var output []awstypes.CapacityReservation + + pages := ec2.NewDescribeCapacityReservationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidCapacityReservationIdNotFound, errCodeInvalidReservationNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err } + + output = append(output, page.CapacityReservations...) } - return nil, &retry.NotFoundError{} + return output, nil } -func FindNetworkACLAssociationBySubnetID(ctx context.Context, conn *ec2.EC2, subnetID string) (*ec2.NetworkAclAssociation, error) { - input := &ec2.DescribeNetworkAclsInput{ - Filters: newAttributeFilterList(map[string]string{ - "association.subnet-id": subnetID, - }), +func findCapacityReservationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CapacityReservation, error) { + input := &ec2.DescribeCapacityReservationsInput{ + CapacityReservationIds: []string{id}, } - output, err := FindNetworkACL(ctx, conn, input) + output, err := findCapacityReservation(ctx, conn, input) if err != nil { return nil, err } - for _, v := range output.Associations { - if aws.StringValue(v.SubnetId) == subnetID { - return v, nil + // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#capacity-reservations-view. + if state := output.State; state == awstypes.CapacityReservationStateCancelled || state == awstypes.CapacityReservationStateExpired { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, } } - return nil, &retry.NotFoundError{} -} - -func FindNetworkACLEntryByThreePartKey(ctx context.Context, conn *ec2.EC2, naclID string, egress bool, ruleNumber int) (*ec2.NetworkAclEntry, error) { - input := &ec2.DescribeNetworkAclsInput{ - Filters: newAttributeFilterList(map[string]string{ - "entry.egress": strconv.FormatBool(egress), - "entry.rule-number": strconv.Itoa(ruleNumber), - }), - NetworkAclIds: aws.StringSlice([]string{naclID}), + // Eventual consistency check. + if aws.ToString(output.CapacityReservationId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } } - output, err := FindNetworkACL(ctx, conn, input) + return output, nil +} + +func findCOIPPool(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCoipPoolsInput) (*awstypes.CoipPool, error) { + output, err := findCOIPPools(ctx, conn, input) if err != nil { return nil, err } - for _, v := range output.Entries { - if aws.BoolValue(v.Egress) == egress && aws.Int64Value(v.RuleNumber) == int64(ruleNumber) { - return v, nil + return tfresource.AssertSingleValueResult(output) +} + +func findCOIPPools(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCoipPoolsInput) ([]awstypes.CoipPool, error) { + var output []awstypes.CoipPool + + pages := ec2.NewDescribeCoipPoolsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidPoolIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err } + + output = append(output, page.CoipPools...) } - return nil, &retry.NotFoundError{} + return output, nil } -func FindNetworkInterface(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeNetworkInterfacesInput) (*ec2.NetworkInterface, error) { - output, err := FindNetworkInterfaces(ctx, conn, input) +func findDHCPOptions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeDhcpOptionsInput) (*awstypes.DhcpOptions, error) { + output, err := findDHCPOptionses(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindNetworkInterfaces(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeNetworkInterfacesInput) ([]*ec2.NetworkInterface, error) { - var output []*ec2.NetworkInterface +func findDHCPOptionses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeDhcpOptionsInput) ([]awstypes.DhcpOptions, error) { + var output []awstypes.DhcpOptions - err := conn.DescribeNetworkInterfacesPagesWithContext(ctx, input, func(page *ec2.DescribeNetworkInterfacesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeDhcpOptionsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.NetworkInterfaces { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidDHCPOptionIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInterfaceIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.DhcpOptions...) } return output, nil } -func FindNetworkInterfaceByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.NetworkInterface, error) { - input := &ec2.DescribeNetworkInterfacesInput{ - NetworkInterfaceIds: aws.StringSlice([]string{id}), +func findDHCPOptionsByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.DhcpOptions, error) { + input := &ec2.DescribeDhcpOptionsInput{ + DhcpOptionsIds: []string{id}, } - output, err := FindNetworkInterface(ctx, conn, input) + output, err := findDHCPOptions(ctx, conn, input) if err != nil { return nil, err } // Eventual consistency check. - if aws.StringValue(output.NetworkInterfaceId) != id { + if aws.ToString(output.DhcpOptionsId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -213,210 +228,177 @@ func FindNetworkInterfaceByID(ctx context.Context, conn *ec2.EC2, id string) (*e return output, nil } -func FindNetworkInterfaceByAttachmentID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.NetworkInterface, error) { - input := &ec2.DescribeNetworkInterfacesInput{ - Filters: newAttributeFilterList(map[string]string{ - "attachment.attachment-id": id, - }), - } - - networkInterface, err := FindNetworkInterface(ctx, conn, input) +func findFleet(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFleetsInput) (*awstypes.FleetData, error) { + output, err := findFleets(ctx, conn, input) if err != nil { return nil, err } - if networkInterface == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return networkInterface, nil + return tfresource.AssertSingleValueResult(output) } -func FindNetworkInterfaceAttachmentByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.NetworkInterfaceAttachment, error) { - input := &ec2.DescribeNetworkInterfacesInput{ - Filters: newAttributeFilterList(map[string]string{ - "attachment.attachment-id": id, - }), - } +func findFleets(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFleetsInput) ([]awstypes.FleetData, error) { + var output []awstypes.FleetData - networkInterface, err := FindNetworkInterface(ctx, conn, input) + pages := ec2.NewDescribeFleetsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - if err != nil { - return nil, err - } + if tfawserr.ErrCodeEquals(err, errCodeInvalidFleetIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } - if networkInterface.Attachment == nil { - return nil, tfresource.NewEmptyResultError(input) + if err != nil { + return nil, err + } + + output = append(output, page.Fleets...) } - return networkInterface.Attachment, nil + return output, nil } -func FindNetworkInterfaceSecurityGroup(ctx context.Context, conn *ec2.EC2, networkInterfaceID string, securityGroupID string) (*ec2.GroupIdentifier, error) { - networkInterface, err := FindNetworkInterfaceByID(ctx, conn, networkInterfaceID) +func findFleetByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.FleetData, error) { + input := &ec2.DescribeFleetsInput{ + FleetIds: []string{id}, + } + + output, err := findFleet(ctx, conn, input) if err != nil { return nil, err } - for _, groupIdentifier := range networkInterface.Groups { - if aws.StringValue(groupIdentifier.GroupId) == securityGroupID { - return groupIdentifier, nil + if state := output.FleetState; state == awstypes.FleetStateCodeDeleted || state == awstypes.FleetStateCodeDeletedRunning || state == awstypes.FleetStateCodeDeletedTerminatingInstances { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, } } - return nil, &retry.NotFoundError{ - LastError: fmt.Errorf("Network Interface (%s) Security Group (%s) not found", networkInterfaceID, securityGroupID), + // Eventual consistency check. + if aws.ToString(output.FleetId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } } + + return output, nil } -func FindSecurityGroupByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SecurityGroup, error) { - input := &ec2.DescribeSecurityGroupsInput{ - GroupIds: aws.StringSlice([]string{id}), +func findHostByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Host, error) { + input := &ec2.DescribeHostsInput{ + HostIds: []string{id}, } - output, err := FindSecurityGroup(ctx, conn, input) + output, err := findHost(ctx, conn, input) if err != nil { return nil, err } - // Eventual consistency check. - if aws.StringValue(output.GroupId) != id { + if state := output.State; state == awstypes.AllocationStateReleased || state == awstypes.AllocationStateReleasedPermanentFailure { return nil, &retry.NotFoundError{ + Message: string(state), LastRequest: input, } } - return output, nil -} - -func findSecurityGroupByDescriptionAndVPCID(ctx context.Context, conn *ec2.EC2, description, vpcID string) (*ec2.SecurityGroup, error) { - input := &ec2.DescribeSecurityGroupsInput{ - Filters: newAttributeFilterList( - map[string]string{ - "description": description, // nosemgrep:ci.literal-description-string-constant - "vpc-id": vpcID, - }, - ), - } - return FindSecurityGroup(ctx, conn, input) -} - -func findSecurityGroupByNameAndVPCIDAndOwnerID(ctx context.Context, conn *ec2.EC2, name, vpcID, ownerID string) (*ec2.SecurityGroup, error) { - input := &ec2.DescribeSecurityGroupsInput{ - Filters: newAttributeFilterList( - map[string]string{ - "group-name": name, - "vpc-id": vpcID, - "owner-id": ownerID, - }, - ), - } - return FindSecurityGroup(ctx, conn, input) -} - -// FindSecurityGroup looks up a security group using an ec2.DescribeSecurityGroupsInput. Returns a retry.NotFoundError if not found. -func FindSecurityGroup(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeSecurityGroupsInput) (*ec2.SecurityGroup, error) { - output, err := FindSecurityGroups(ctx, conn, input) - - if err != nil { - return nil, err + // Eventual consistency check. + if aws.ToString(output.HostId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } } - return tfresource.AssertSinglePtrResult(output) + return output, nil } -func FindSecurityGroups(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) { - var output []*ec2.SecurityGroup +func findHosts(ctx context.Context, conn *ec2.Client, input *ec2.DescribeHostsInput) ([]awstypes.Host, error) { + var output []awstypes.Host - err := conn.DescribeSecurityGroupsPagesWithContext(ctx, input, func(page *ec2.DescribeSecurityGroupsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeHostsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.SecurityGroups { - if v == nil { - continue + if tfawserr.ErrCodeEquals(err, errCodeInvalidHostIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } - - output = append(output, v) } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidGroupNotFound, errCodeInvalidSecurityGroupIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.Hosts...) } return output, nil } -func FindSecurityGroupRule(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeSecurityGroupRulesInput) (*ec2.SecurityGroupRule, error) { - output, err := FindSecurityGroupRules(ctx, conn, input) +func findHost(ctx context.Context, conn *ec2.Client, input *ec2.DescribeHostsInput) (*awstypes.Host, error) { + output, err := findHosts(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output, func(v *awstypes.Host) bool { return v.HostProperties != nil }) } -func FindSecurityGroupRules(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeSecurityGroupRulesInput) ([]*ec2.SecurityGroupRule, error) { - var output []*ec2.SecurityGroupRule +func findInstanceCreditSpecifications(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceCreditSpecificationsInput) ([]awstypes.InstanceCreditSpecification, error) { + var output []awstypes.InstanceCreditSpecification - err := conn.DescribeSecurityGroupRulesPagesWithContext(ctx, input, func(page *ec2.DescribeSecurityGroupRulesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeInstanceCreditSpecificationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.SecurityGroupRules { - if v == nil { - continue + if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } - - output = append(output, v) } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSecurityGroupRuleIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } + + output = append(output, page.InstanceCreditSpecifications...) } + return output, nil +} + +func findInstanceCreditSpecification(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceCreditSpecificationsInput) (*awstypes.InstanceCreditSpecification, error) { + output, err := findInstanceCreditSpecifications(ctx, conn, input) + if err != nil { return nil, err } - return output, nil + return tfresource.AssertSingleValueResult(output) } -func FindSecurityGroupRuleByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SecurityGroupRule, error) { - input := &ec2.DescribeSecurityGroupRulesInput{ - SecurityGroupRuleIds: aws.StringSlice([]string{id}), +func findInstanceCreditSpecificationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.InstanceCreditSpecification, error) { + input := &ec2.DescribeInstanceCreditSpecificationsInput{ + InstanceIds: []string{id}, } - output, err := FindSecurityGroupRule(ctx, conn, input) + output, err := findInstanceCreditSpecification(ctx, conn, input) if err != nil { return nil, err } // Eventual consistency check. - if aws.StringValue(output.SecurityGroupRuleId) != id { + if aws.ToString(output.InstanceId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -425,57 +407,61 @@ func FindSecurityGroupRuleByID(ctx context.Context, conn *ec2.EC2, id string) (* return output, nil } -func FindSecurityGroupEgressRuleByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SecurityGroupRule, error) { - output, err := FindSecurityGroupRuleByID(ctx, conn, id) +func findInstances(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstancesInput) ([]awstypes.Instance, error) { + var output []awstypes.Instance - if err != nil { - return nil, err - } + pages := ec2.NewDescribeInstancesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - if !aws.BoolValue(output.IsEgress) { - return nil, &retry.NotFoundError{} + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + for _, v := range page.Reservations { + output = append(output, v.Instances...) + } } return output, nil } -func FindSecurityGroupIngressRuleByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SecurityGroupRule, error) { - output, err := FindSecurityGroupRuleByID(ctx, conn, id) +func findInstance(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstancesInput) (*awstypes.Instance, error) { + output, err := findInstances(ctx, conn, input) if err != nil { return nil, err } - if aws.BoolValue(output.IsEgress) { - return nil, &retry.NotFoundError{} - } - - return output, nil -} - -func FindSecurityGroupRulesBySecurityGroupID(ctx context.Context, conn *ec2.EC2, id string) ([]*ec2.SecurityGroupRule, error) { - input := &ec2.DescribeSecurityGroupRulesInput{ - Filters: newAttributeFilterList(map[string]string{ - "group-id": id, - }), - } - - return FindSecurityGroupRules(ctx, conn, input) + return tfresource.AssertSingleValueResult(output, func(v *awstypes.Instance) bool { return v.State != nil }) } -func FindSubnetByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.Subnet, error) { - input := &ec2.DescribeSubnetsInput{ - SubnetIds: aws.StringSlice([]string{id}), +func findInstanceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Instance, error) { + input := &ec2.DescribeInstancesInput{ + InstanceIds: []string{id}, } - output, err := FindSubnet(ctx, conn, input) + output, err := findInstance(ctx, conn, input) if err != nil { return nil, err } + if state := output.State.Name; state == awstypes.InstanceStateNameTerminated { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + // Eventual consistency check. - if aws.StringValue(output.SubnetId) != id { + if aws.ToString(output.InstanceId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -484,165 +470,459 @@ func FindSubnetByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.Subnet, return output, nil } -func FindSubnet(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeSubnetsInput) (*ec2.Subnet, error) { - output, err := FindSubnets(ctx, conn, input) +func findInstanceStatus(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceStatusInput) (*awstypes.InstanceStatus, error) { + output, err := findInstanceStatuses(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindSubnets(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeSubnetsInput) ([]*ec2.Subnet, error) { - var output []*ec2.Subnet +func findInstanceStatuses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceStatusInput) ([]awstypes.InstanceStatus, error) { + var output []awstypes.InstanceStatus - err := conn.DescribeSubnetsPagesWithContext(ctx, input, func(page *ec2.DescribeSubnetsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeInstanceStatusPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.Subnets { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.InstanceStatuses...) } return output, nil } -func FindSubnetCIDRReservationBySubnetIDAndReservationID(ctx context.Context, conn *ec2.EC2, subnetID, reservationID string) (*ec2.SubnetCidrReservation, error) { - input := &ec2.GetSubnetCidrReservationsInput{ - SubnetId: aws.String(subnetID), - } - - output, err := conn.GetSubnetCidrReservationsWithContext(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - } - } +func findInstanceState(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceStatusInput) (*awstypes.InstanceState, error) { + output, err := findInstanceStatus(ctx, conn, input) if err != nil { return nil, err } - if output == nil || (len(output.SubnetIpv4CidrReservations) == 0 && len(output.SubnetIpv6CidrReservations) == 0) { + if output.InstanceState == nil { return nil, tfresource.NewEmptyResultError(input) } - for _, r := range output.SubnetIpv4CidrReservations { - if aws.StringValue(r.SubnetCidrReservationId) == reservationID { - return r, nil - } + return output.InstanceState, nil +} + +func findInstanceStateByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.InstanceState, error) { + input := &ec2.DescribeInstanceStatusInput{ + InstanceIds: []string{id}, + IncludeAllInstances: aws.Bool(true), } - for _, r := range output.SubnetIpv6CidrReservations { - if aws.StringValue(r.SubnetCidrReservationId) == reservationID { - return r, nil + + output, err := findInstanceState(ctx, conn, input) + + if err != nil { + return nil, err + } + + if name := output.Name; name == awstypes.InstanceStateNameTerminated { + return nil, &retry.NotFoundError{ + Message: string(name), + LastRequest: input, } } - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + return output, nil +} + +func findInstanceTypes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceTypesInput) ([]awstypes.InstanceTypeInfo, error) { + var output []awstypes.InstanceTypeInfo + + pages := ec2.NewDescribeInstanceTypesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.InstanceTypes...) } + + return output, nil } -func FindSubnetIPv6CIDRBlockAssociationByID(ctx context.Context, conn *ec2.EC2, associationID string) (*ec2.SubnetIpv6CidrBlockAssociation, error) { - input := &ec2.DescribeSubnetsInput{ - Filters: newAttributeFilterList(map[string]string{ - "ipv6-cidr-block-association.association-id": associationID, - }), +func findInstanceType(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceTypesInput) (*awstypes.InstanceTypeInfo, error) { + output, err := findInstanceTypes(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findInstanceTypeByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.InstanceTypeInfo, error) { + input := &ec2.DescribeInstanceTypesInput{ + InstanceTypes: []awstypes.InstanceType{awstypes.InstanceType(name)}, } - output, err := FindSubnet(ctx, conn, input) + output, err := findInstanceType(ctx, conn, input) if err != nil { return nil, err } - for _, association := range output.Ipv6CidrBlockAssociationSet { - if aws.StringValue(association.AssociationId) == associationID { - if state := aws.StringValue(association.Ipv6CidrBlockState.State); state == ec2.SubnetCidrBlockStateCodeDisassociated { - return nil, &retry.NotFoundError{Message: state} + return output, nil +} + +func findInstanceTypeOfferings(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceTypeOfferingsInput) ([]awstypes.InstanceTypeOffering, error) { + var output []awstypes.InstanceTypeOffering + + pages := ec2.NewDescribeInstanceTypeOfferingsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.InstanceTypeOfferings...) + } + + return output, nil +} + +func findInternetGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInternetGatewaysInput) (*awstypes.InternetGateway, error) { + output, err := findInternetGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findInternetGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInternetGatewaysInput) ([]awstypes.InternetGateway, error) { + var output []awstypes.InternetGateway + + pages := ec2.NewDescribeInternetGatewaysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidInternetGatewayIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } + } - return association, nil + if err != nil { + return nil, err } + + output = append(output, page.InternetGateways...) } - return nil, &retry.NotFoundError{} + return output, nil +} + +func findInternetGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.InternetGateway, error) { + input := &ec2.DescribeInternetGatewaysInput{ + InternetGatewayIds: []string{id}, + } + + output, err := findInternetGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.InternetGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findInternetGatewayAttachment(ctx context.Context, conn *ec2.Client, internetGatewayID, vpcID string) (*awstypes.InternetGatewayAttachment, error) { + internetGateway, err := findInternetGatewayByID(ctx, conn, internetGatewayID) + + if err != nil { + return nil, err + } + + if len(internetGateway.Attachments) == 0 { + return nil, tfresource.NewEmptyResultError(internetGatewayID) + } + + if count := len(internetGateway.Attachments); count > 1 { + return nil, tfresource.NewTooManyResultsError(count, internetGatewayID) + } + + attachment := internetGateway.Attachments[0] + + if aws.ToString(attachment.VpcId) != vpcID { + return nil, tfresource.NewEmptyResultError(vpcID) + } + + return &attachment, nil } -func FindVPC(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeVpcsInput) (*ec2.Vpc, error) { - output, err := FindVPCs(ctx, conn, input) +func findLaunchTemplate(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplatesInput) (*awstypes.LaunchTemplate, error) { + output, err := findLaunchTemplates(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindVPCs(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeVpcsInput) ([]*ec2.Vpc, error) { - var output []*ec2.Vpc +func findLaunchTemplates(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplatesInput) ([]awstypes.LaunchTemplate, error) { + var output []awstypes.LaunchTemplate - err := conn.DescribeVpcsPagesWithContext(ctx, input, func(page *ec2.DescribeVpcsOutput, lastPage bool) bool { - if page == nil { - return !lastPage + pages := ec2.NewDescribeLaunchTemplatesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidLaunchTemplateIdMalformed, errCodeInvalidLaunchTemplateIdNotFound, errCodeInvalidLaunchTemplateNameNotFoundException) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.LaunchTemplates...) + } + + return output, nil +} + +func findLaunchTemplateByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LaunchTemplate, error) { + input := &ec2.DescribeLaunchTemplatesInput{ + LaunchTemplateIds: []string{id}, + } + + output, err := findLaunchTemplate(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.LaunchTemplateId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findLaunchTemplateVersion(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplateVersionsInput) (*awstypes.LaunchTemplateVersion, error) { + output, err := findLaunchTemplateVersions(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.LaunchTemplateVersion) bool { return v.LaunchTemplateData != nil }) +} + +func findLaunchTemplateVersions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplateVersionsInput) ([]awstypes.LaunchTemplateVersion, error) { + var output []awstypes.LaunchTemplateVersion + + pages := ec2.NewDescribeLaunchTemplateVersionsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidLaunchTemplateIdNotFound, errCodeInvalidLaunchTemplateNameNotFoundException, errCodeInvalidLaunchTemplateIdVersionNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.LaunchTemplateVersions...) + } + + return output, nil +} + +func findLaunchTemplateVersionByTwoPartKey(ctx context.Context, conn *ec2.Client, launchTemplateID, version string) (*awstypes.LaunchTemplateVersion, error) { + input := &ec2.DescribeLaunchTemplateVersionsInput{ + LaunchTemplateId: aws.String(launchTemplateID), + Versions: []string{version}, + } + + output, err := findLaunchTemplateVersion(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.LaunchTemplateId) != launchTemplateID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findLocalGatewayRouteTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTablesInput) (*awstypes.LocalGatewayRouteTable, error) { + output, err := findLocalGatewayRouteTables(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findLocalGatewayRouteTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTablesInput) ([]awstypes.LocalGatewayRouteTable, error) { + var output []awstypes.LocalGatewayRouteTable + + pages := ec2.NewDescribeLocalGatewayRouteTablesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err } - for _, v := range page.Vpcs { - if v != nil { - output = append(output, v) + output = append(output, page.LocalGatewayRouteTables...) + } + + return output, nil +} + +func findLocalGatewayRoutes(ctx context.Context, conn *ec2.Client, input *ec2.SearchLocalGatewayRoutesInput) ([]awstypes.LocalGatewayRoute, error) { + var output []awstypes.LocalGatewayRoute + + pages := ec2.NewSearchLocalGatewayRoutesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidLocalGatewayRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage + if err != nil { + return nil, err + } + + output = append(output, page.Routes...) + } + + return output, nil +} + +func findLocalGatewayRouteByTwoPartKey(ctx context.Context, conn *ec2.Client, localGatewayRouteTableID, destinationCIDRBlock string) (*awstypes.LocalGatewayRoute, error) { + input := &ec2.SearchLocalGatewayRoutesInput{ + Filters: []awstypes.Filter{ + { + Name: aws.String(names.AttrType), + Values: enum.Slice(awstypes.LocalGatewayRouteTypeStatic), + }, + }, + LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID), + } + + localGatewayRoutes, err := findLocalGatewayRoutes(ctx, conn, input) + + if err != nil { + return nil, err + } + + localGatewayRoutes = tfslices.Filter(localGatewayRoutes, func(v awstypes.LocalGatewayRoute) bool { + return aws.ToString(v.DestinationCidrBlock) == destinationCIDRBlock }) - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { + output, err := tfresource.AssertSingleValueResult(localGatewayRoutes) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.LocalGatewayRouteStateDeleted { return nil, &retry.NotFoundError{ - LastError: err, + Message: string(state), LastRequest: input, } } + return output, nil +} + +func findLocalGatewayRouteTableVPCAssociation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { + output, err := findLocalGatewayRouteTableVPCAssociations(ctx, conn, input) + if err != nil { return nil, err } + return tfresource.AssertSingleValueResult(output) +} + +func findLocalGatewayRouteTableVPCAssociations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput) ([]awstypes.LocalGatewayRouteTableVpcAssociation, error) { + var output []awstypes.LocalGatewayRouteTableVpcAssociation + + pages := ec2.NewDescribeLocalGatewayRouteTableVpcAssociationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.LocalGatewayRouteTableVpcAssociations...) + } + return output, nil } -func FindVPCByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.Vpc, error) { - input := &ec2.DescribeVpcsInput{ - VpcIds: aws.StringSlice([]string{id}), +func findLocalGatewayRouteTableVPCAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { + input := &ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput{ + LocalGatewayRouteTableVpcAssociationIds: []string{id}, } - output, err := FindVPC(ctx, conn, input) + output, err := findLocalGatewayRouteTableVPCAssociation(ctx, conn, input) if err != nil { return nil, err } + if state := aws.ToString(output.State); state == string(awstypes.RouteTableAssociationStateCodeDisassociated) { + return nil, &retry.NotFoundError{ + Message: state, + LastRequest: input, + } + } + // Eventual consistency check. - if aws.StringValue(output.VpcId) != id { + if aws.ToString(output.LocalGatewayRouteTableVpcAssociationId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -651,224 +931,5188 @@ func FindVPCByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.Vpc, error return output, nil } -func FindVPCDHCPOptionsAssociation(ctx context.Context, conn *ec2.EC2, vpcID string, dhcpOptionsID string) error { - vpc, err := FindVPCByID(ctx, conn, vpcID) +func findLocalGatewayVirtualInterface(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfacesInput) (*awstypes.LocalGatewayVirtualInterface, error) { + output, err := findLocalGatewayVirtualInterfaces(ctx, conn, input) if err != nil { - return err + return nil, err } - if aws.StringValue(vpc.DhcpOptionsId) != dhcpOptionsID { - return &retry.NotFoundError{ - LastError: fmt.Errorf("EC2 VPC (%s) DHCP Options Set (%s) Association not found", vpcID, dhcpOptionsID), + return tfresource.AssertSingleValueResult(output) +} + +func findLocalGatewayVirtualInterfaces(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfacesInput) ([]awstypes.LocalGatewayVirtualInterface, error) { + var output []awstypes.LocalGatewayVirtualInterface + + pages := ec2.NewDescribeLocalGatewayVirtualInterfacesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err } + + output = append(output, page.LocalGatewayVirtualInterfaces...) } - return nil + return output, nil } -func FindVPCCIDRBlockAssociationByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.VpcCidrBlockAssociation, *ec2.Vpc, error) { - input := &ec2.DescribeVpcsInput{ - Filters: newAttributeFilterList(map[string]string{ - "cidr-block-association.association-id": id, - }), +func findLocalGatewayVirtualInterfaceGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput) (*awstypes.LocalGatewayVirtualInterfaceGroup, error) { + output, err := findLocalGatewayVirtualInterfaceGroups(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findLocalGatewayVirtualInterfaceGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput) ([]awstypes.LocalGatewayVirtualInterfaceGroup, error) { + var output []awstypes.LocalGatewayVirtualInterfaceGroup + + pages := ec2.NewDescribeLocalGatewayVirtualInterfaceGroupsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.LocalGatewayVirtualInterfaceGroups...) } - vpc, err := FindVPC(ctx, conn, input) + return output, nil +} + +func findLocalGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewaysInput) (*awstypes.LocalGateway, error) { + output, err := findLocalGateways(ctx, conn, input) if err != nil { - return nil, nil, err + return nil, err } - for _, association := range vpc.CidrBlockAssociationSet { - if aws.StringValue(association.AssociationId) == id { - if state := aws.StringValue(association.CidrBlockState.State); state == ec2.VpcCidrBlockStateCodeDisassociated { - return nil, nil, &retry.NotFoundError{Message: state} - } + return tfresource.AssertSingleValueResult(output) +} + +func findLocalGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewaysInput) ([]awstypes.LocalGateway, error) { + var output []awstypes.LocalGateway - return association, vpc, nil + pages := ec2.NewDescribeLocalGatewaysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err } + + output = append(output, page.LocalGateways...) } - return nil, nil, &retry.NotFoundError{} + return output, nil } -func FindVPCIPv6CIDRBlockAssociationByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.VpcIpv6CidrBlockAssociation, *ec2.Vpc, error) { - input := &ec2.DescribeVpcsInput{ - Filters: newAttributeFilterList(map[string]string{ +func findPlacementGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribePlacementGroupsInput) (*awstypes.PlacementGroup, error) { + output, err := findPlacementGroups(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findPlacementGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribePlacementGroupsInput) ([]awstypes.PlacementGroup, error) { + output, err := conn.DescribePlacementGroups(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidPlacementGroupUnknown) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.PlacementGroups, nil +} + +func findPlacementGroupByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PlacementGroup, error) { + input := &ec2.DescribePlacementGroupsInput{ + GroupNames: []string{name}, + } + + output, err := findPlacementGroup(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.PlacementGroupStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + return output, nil +} + +func findPublicIPv4Pool(ctx context.Context, conn *ec2.Client, input *ec2.DescribePublicIpv4PoolsInput) (*awstypes.PublicIpv4Pool, error) { + output, err := findPublicIPv4Pools(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findPublicIPv4Pools(ctx context.Context, conn *ec2.Client, input *ec2.DescribePublicIpv4PoolsInput) ([]awstypes.PublicIpv4Pool, error) { + var output []awstypes.PublicIpv4Pool + + pages := ec2.NewDescribePublicIpv4PoolsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidPublicIpv4PoolIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.PublicIpv4Pools...) + } + + return output, nil +} + +func findPublicIPv4PoolByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.PublicIpv4Pool, error) { + input := &ec2.DescribePublicIpv4PoolsInput{ + PoolIds: []string{id}, + } + + output, err := findPublicIPv4Pool(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.PoolId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVolumeAttachmentInstanceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Instance, error) { + input := &ec2.DescribeInstancesInput{ + InstanceIds: []string{id}, + } + + output, err := findInstance(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State.Name; state == awstypes.InstanceStateNameTerminated { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.InstanceId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSpotDatafeedSubscription(ctx context.Context, conn *ec2.Client) (*awstypes.SpotDatafeedSubscription, error) { + input := &ec2.DescribeSpotDatafeedSubscriptionInput{} + + output, err := conn.DescribeSpotDatafeedSubscription(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotDatafeedNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil || output.SpotDatafeedSubscription == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.SpotDatafeedSubscription, nil +} + +func findSpotInstanceRequests(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotInstanceRequestsInput) ([]awstypes.SpotInstanceRequest, error) { + var output []awstypes.SpotInstanceRequest + + pages := ec2.NewDescribeSpotInstanceRequestsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotInstanceRequestIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.SpotInstanceRequests...) + } + + return output, nil +} + +func findSpotInstanceRequest(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotInstanceRequestsInput) (*awstypes.SpotInstanceRequest, error) { + output, err := findSpotInstanceRequests(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.SpotInstanceRequest) bool { return v.Status != nil }) +} + +func findSpotInstanceRequestByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SpotInstanceRequest, error) { + input := &ec2.DescribeSpotInstanceRequestsInput{ + SpotInstanceRequestIds: []string{id}, + } + + output, err := findSpotInstanceRequest(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.SpotInstanceStateCancelled || state == awstypes.SpotInstanceStateClosed { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.SpotInstanceRequestId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSpotPrices(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotPriceHistoryInput) ([]awstypes.SpotPrice, error) { + var output []awstypes.SpotPrice + pages := ec2.NewDescribeSpotPriceHistoryPaginator(conn, input) + + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.SpotPriceHistory...) + } + + return output, nil +} + +func findSpotPrice(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotPriceHistoryInput) (*awstypes.SpotPrice, error) { + output, err := findSpotPrices(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSubnetByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Subnet, error) { + input := &ec2.DescribeSubnetsInput{ + SubnetIds: []string{id}, + } + + output, err := findSubnet(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.SubnetId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSubnet(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSubnetsInput) (*awstypes.Subnet, error) { + output, err := findSubnets(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSubnets(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSubnetsInput) ([]awstypes.Subnet, error) { + var output []awstypes.Subnet + + pages := ec2.NewDescribeSubnetsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Subnets...) + } + + return output, nil +} + +func findSubnetCIDRReservationBySubnetIDAndReservationID(ctx context.Context, conn *ec2.Client, subnetID, reservationID string) (*awstypes.SubnetCidrReservation, error) { + input := &ec2.GetSubnetCidrReservationsInput{ + SubnetId: aws.String(subnetID), + } + + output, err := conn.GetSubnetCidrReservations(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + } + } + + if err != nil { + return nil, err + } + + if output == nil || (len(output.SubnetIpv4CidrReservations) == 0 && len(output.SubnetIpv6CidrReservations) == 0) { + return nil, tfresource.NewEmptyResultError(input) + } + + for _, r := range output.SubnetIpv4CidrReservations { + if aws.ToString(r.SubnetCidrReservationId) == reservationID { + return &r, nil + } + } + for _, r := range output.SubnetIpv6CidrReservations { + if aws.ToString(r.SubnetCidrReservationId) == reservationID { + return &r, nil + } + } + + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } +} + +func findSubnetIPv6CIDRBlockAssociationByID(ctx context.Context, conn *ec2.Client, associationID string) (*awstypes.SubnetIpv6CidrBlockAssociation, error) { + input := &ec2.DescribeSubnetsInput{ + Filters: newAttributeFilterList(map[string]string{ + "ipv6-cidr-block-association.association-id": associationID, + }), + } + + output, err := findSubnet(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, association := range output.Ipv6CidrBlockAssociationSet { + if aws.ToString(association.AssociationId) == associationID { + if state := association.Ipv6CidrBlockState.State; state == awstypes.SubnetCidrBlockStateCodeDisassociated { + return nil, &retry.NotFoundError{Message: string(state)} + } + + return &association, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findVolumeModifications(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesModificationsInput) ([]awstypes.VolumeModification, error) { + var output []awstypes.VolumeModification + + pages := ec2.NewDescribeVolumesModificationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVolumeNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.VolumesModifications...) + } + + return output, nil +} + +func findVolumeModification(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesModificationsInput) (*awstypes.VolumeModification, error) { + output, err := findVolumeModifications(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVolumeModificationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VolumeModification, error) { + input := &ec2.DescribeVolumesModificationsInput{ + VolumeIds: []string{id}, + } + + output, err := findVolumeModification(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.VolumeId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVPCAttribute(ctx context.Context, conn *ec2.Client, vpcID string, attribute awstypes.VpcAttributeName) (bool, error) { + input := &ec2.DescribeVpcAttributeInput{ + Attribute: attribute, + VpcId: aws.String(vpcID), + } + + output, err := conn.DescribeVpcAttribute(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { + return false, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return false, err + } + + if output == nil { + return false, tfresource.NewEmptyResultError(input) + } + + var v *awstypes.AttributeBooleanValue + switch attribute { + case awstypes.VpcAttributeNameEnableDnsHostnames: + v = output.EnableDnsHostnames + case awstypes.VpcAttributeNameEnableDnsSupport: + v = output.EnableDnsSupport + case awstypes.VpcAttributeNameEnableNetworkAddressUsageMetrics: + v = output.EnableNetworkAddressUsageMetrics + default: + return false, fmt.Errorf("unsupported VPC attribute: %s", attribute) + } + + if v == nil { + return false, tfresource.NewEmptyResultError(input) + } + + return aws.ToBool(v.Value), nil +} + +func findVPC(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcsInput) (*awstypes.Vpc, error) { + output, err := findVPCs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVPCs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcsInput) ([]awstypes.Vpc, error) { + var output []awstypes.Vpc + + pages := ec2.NewDescribeVpcsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Vpcs...) + } + + return output, nil +} + +func findVPCByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Vpc, error) { + input := &ec2.DescribeVpcsInput{ + VpcIds: []string{id}, + } + + return findVPC(ctx, conn, input) +} + +func findVPCCIDRBlockAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpcCidrBlockAssociation, *awstypes.Vpc, error) { + input := &ec2.DescribeVpcsInput{ + Filters: newAttributeFilterList(map[string]string{ + "cidr-block-association.association-id": id, + }), + } + + vpc, err := findVPC(ctx, conn, input) + + if err != nil { + return nil, nil, err + } + + for _, association := range vpc.CidrBlockAssociationSet { + if aws.ToString(association.AssociationId) == id { + if state := association.CidrBlockState.State; state == awstypes.VpcCidrBlockStateCodeDisassociated { + return nil, nil, &retry.NotFoundError{Message: string(state)} + } + + return &association, vpc, nil + } + } + + return nil, nil, &retry.NotFoundError{} +} + +func findVPCIPv6CIDRBlockAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpcIpv6CidrBlockAssociation, *awstypes.Vpc, error) { + input := &ec2.DescribeVpcsInput{ + Filters: newAttributeFilterList(map[string]string{ "ipv6-cidr-block-association.association-id": id, }), } - vpc, err := FindVPC(ctx, conn, input) + vpc, err := findVPC(ctx, conn, input) + + if err != nil { + return nil, nil, err + } + + for _, association := range vpc.Ipv6CidrBlockAssociationSet { + if aws.ToString(association.AssociationId) == id { + if state := association.Ipv6CidrBlockState.State; state == awstypes.VpcCidrBlockStateCodeDisassociated { + return nil, nil, &retry.NotFoundError{Message: string(state)} + } + + return &association, vpc, nil + } + } + + return nil, nil, &retry.NotFoundError{} +} + +func findVPCDefaultNetworkACL(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkAcl, error) { + input := &ec2.DescribeNetworkAclsInput{ + Filters: newAttributeFilterList(map[string]string{ + "default": "true", + "vpc-id": id, + }), + } + + return findNetworkACL(ctx, conn, input) +} + +func findNATGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNatGatewaysInput) (*awstypes.NatGateway, error) { + output, err := findNATGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findNATGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNatGatewaysInput) ([]awstypes.NatGateway, error) { + var output []awstypes.NatGateway + + pages := ec2.NewDescribeNatGatewaysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeNatGatewayNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.NatGateways...) + } + + return output, nil +} + +func findNATGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NatGateway, error) { + input := &ec2.DescribeNatGatewaysInput{ + NatGatewayIds: []string{id}, + } + + output, err := findNATGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.NatGatewayStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.NatGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findNATGatewayAddressByNATGatewayIDAndAllocationID(ctx context.Context, conn *ec2.Client, natGatewayID, allocationID string) (*awstypes.NatGatewayAddress, error) { + output, err := findNATGatewayByID(ctx, conn, natGatewayID) + + if err != nil { + return nil, err + } + + for _, v := range output.NatGatewayAddresses { + if aws.ToString(v.AllocationId) == allocationID { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx context.Context, conn *ec2.Client, natGatewayID, privateIP string) (*awstypes.NatGatewayAddress, error) { + output, err := findNATGatewayByID(ctx, conn, natGatewayID) + + if err != nil { + return nil, err + } + + for _, v := range output.NatGatewayAddresses { + if aws.ToString(v.PrivateIp) == privateIP { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findNetworkACLByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkAcl, error) { + input := &ec2.DescribeNetworkAclsInput{ + NetworkAclIds: []string{id}, + } + + output, err := findNetworkACL(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.NetworkAclId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findNetworkACL(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkAclsInput) (*awstypes.NetworkAcl, error) { + output, err := findNetworkACLs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findNetworkACLs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkAclsInput) ([]awstypes.NetworkAcl, error) { + var output []awstypes.NetworkAcl + + pages := ec2.NewDescribeNetworkAclsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkACLIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.NetworkAcls...) + } + + return output, nil +} + +func findNetworkACLAssociationByID(ctx context.Context, conn *ec2.Client, associationID string) (*awstypes.NetworkAclAssociation, error) { + input := &ec2.DescribeNetworkAclsInput{ + Filters: newAttributeFilterList(map[string]string{ + "association.association-id": associationID, + }), + } + + output, err := findNetworkACL(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, v := range output.Associations { + if aws.ToString(v.NetworkAclAssociationId) == associationID { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findNetworkACLAssociationBySubnetID(ctx context.Context, conn *ec2.Client, subnetID string) (*awstypes.NetworkAclAssociation, error) { + input := &ec2.DescribeNetworkAclsInput{ + Filters: newAttributeFilterList(map[string]string{ + "association.subnet-id": subnetID, + }), + } + + output, err := findNetworkACL(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, v := range output.Associations { + if aws.ToString(v.SubnetId) == subnetID { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findNetworkACLEntryByThreePartKey(ctx context.Context, conn *ec2.Client, naclID string, egress bool, ruleNumber int) (*awstypes.NetworkAclEntry, error) { + input := &ec2.DescribeNetworkAclsInput{ + Filters: newAttributeFilterList(map[string]string{ + "entry.egress": strconv.FormatBool(egress), + "entry.rule-number": strconv.Itoa(ruleNumber), + }), + NetworkAclIds: []string{naclID}, + } + + output, err := findNetworkACL(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, v := range output.Entries { + if aws.ToBool(v.Egress) == egress && aws.ToInt32(v.RuleNumber) == int32(ruleNumber) { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findVPCDefaultSecurityGroup(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SecurityGroup, error) { + input := &ec2.DescribeSecurityGroupsInput{ + Filters: newAttributeFilterList(map[string]string{ + "group-name": defaultSecurityGroupName, + "vpc-id": id, + }), + } + + return findSecurityGroup(ctx, conn, input) +} + +func findVPCDHCPOptionsAssociation(ctx context.Context, conn *ec2.Client, vpcID string, dhcpOptionsID string) error { + vpc, err := findVPCByID(ctx, conn, vpcID) + + if err != nil { + return err + } + + if aws.ToString(vpc.DhcpOptionsId) != dhcpOptionsID { + return &retry.NotFoundError{ + LastError: fmt.Errorf("EC2 VPC (%s) DHCP Options Set (%s) Association not found", vpcID, dhcpOptionsID), + } + } + + return nil +} + +func findVPCMainRouteTable(ctx context.Context, conn *ec2.Client, id string) (*awstypes.RouteTable, error) { + input := &ec2.DescribeRouteTablesInput{ + Filters: newAttributeFilterList(map[string]string{ + "association.main": "true", + "vpc-id": id, + }), + } + + return findRouteTable(ctx, conn, input) +} + +func findRouteTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeRouteTablesInput) (*awstypes.RouteTable, error) { + output, err := findRouteTables(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findRouteTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeRouteTablesInput) ([]awstypes.RouteTable, error) { + var output []awstypes.RouteTable + + pages := ec2.NewDescribeRouteTablesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.RouteTables...) + } + + return output, nil +} + +func findSecurityGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSecurityGroupsInput) (*awstypes.SecurityGroup, error) { + output, err := findSecurityGroups(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSecurityGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSecurityGroupsInput) ([]awstypes.SecurityGroup, error) { + var output []awstypes.SecurityGroup + + pages := ec2.NewDescribeSecurityGroupsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidGroupNotFound, errCodeInvalidSecurityGroupIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.SecurityGroups...) + } + + return output, nil +} + +// findSecurityGroupByNameAndVPCID looks up a security group by name, VPC ID. Returns a retry.NotFoundError if not found. +func findSecurityGroupByNameAndVPCID(ctx context.Context, conn *ec2.Client, name, vpcID string) (*awstypes.SecurityGroup, error) { + input := &ec2.DescribeSecurityGroupsInput{ + Filters: newAttributeFilterList( + map[string]string{ + "group-name": name, + "vpc-id": vpcID, + }, + ), + } + + return findSecurityGroup(ctx, conn, input) +} + +func findSecurityGroupByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SecurityGroup, error) { + input := &ec2.DescribeSecurityGroupsInput{ + GroupIds: []string{id}, + } + + output, err := findSecurityGroup(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.GroupId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSecurityGroupByDescriptionAndVPCID(ctx context.Context, conn *ec2.Client, description, vpcID string) (*awstypes.SecurityGroup, error) { + input := &ec2.DescribeSecurityGroupsInput{ + Filters: newAttributeFilterList( + map[string]string{ + "description": description, // nosemgrep:ci.literal-description-string-constant + "vpc-id": vpcID, + }, + ), + } + return findSecurityGroup(ctx, conn, input) +} + +func findSecurityGroupByNameAndVPCIDAndOwnerID(ctx context.Context, conn *ec2.Client, name, vpcID, ownerID string) (*awstypes.SecurityGroup, error) { + input := &ec2.DescribeSecurityGroupsInput{ + Filters: newAttributeFilterList( + map[string]string{ + "group-name": name, + "vpc-id": vpcID, + "owner-id": ownerID, + }, + ), + } + return findSecurityGroup(ctx, conn, input) +} + +func findSecurityGroupRule(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSecurityGroupRulesInput) (*awstypes.SecurityGroupRule, error) { + output, err := findSecurityGroupRules(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSecurityGroupRules(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSecurityGroupRulesInput) ([]awstypes.SecurityGroupRule, error) { + var output []awstypes.SecurityGroupRule + + pages := ec2.NewDescribeSecurityGroupRulesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSecurityGroupRuleIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.SecurityGroupRules...) + } + + return output, nil +} + +func findSecurityGroupRuleByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SecurityGroupRule, error) { + input := &ec2.DescribeSecurityGroupRulesInput{ + SecurityGroupRuleIds: []string{id}, + } + + output, err := findSecurityGroupRule(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.SecurityGroupRuleId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSecurityGroupEgressRuleByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SecurityGroupRule, error) { + output, err := findSecurityGroupRuleByID(ctx, conn, id) + + if err != nil { + return nil, err + } + + if !aws.ToBool(output.IsEgress) { + return nil, &retry.NotFoundError{} + } + + return output, nil +} + +func findSecurityGroupIngressRuleByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SecurityGroupRule, error) { + output, err := findSecurityGroupRuleByID(ctx, conn, id) + + if err != nil { + return nil, err + } + + if aws.ToBool(output.IsEgress) { + return nil, &retry.NotFoundError{} + } + + return output, nil +} + +func findSecurityGroupRulesBySecurityGroupID(ctx context.Context, conn *ec2.Client, id string) ([]awstypes.SecurityGroupRule, error) { + input := &ec2.DescribeSecurityGroupRulesInput{ + Filters: newAttributeFilterList(map[string]string{ + "group-id": id, + }), + } + + return findSecurityGroupRules(ctx, conn, input) +} + +func findNetworkInterfaces(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInterfacesInput) ([]awstypes.NetworkInterface, error) { + var output []awstypes.NetworkInterface + + pages := ec2.NewDescribeNetworkInterfacesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInterfaceIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.NetworkInterfaces...) + } + + return output, nil +} + +func findNetworkInterface(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInterfacesInput) (*awstypes.NetworkInterface, error) { + output, err := findNetworkInterfaces(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findNetworkInterfaceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInterface, error) { + input := &ec2.DescribeNetworkInterfacesInput{ + NetworkInterfaceIds: []string{id}, + } + + output, err := findNetworkInterface(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.NetworkInterfaceId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, err +} + +func findNetworkInterfaceAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInterfaceAttachment, error) { + input := &ec2.DescribeNetworkInterfacesInput{ + Filters: newAttributeFilterList(map[string]string{ + "attachment.attachment-id": id, + }), + } + + networkInterface, err := findNetworkInterface(ctx, conn, input) + + if err != nil { + return nil, err + } + + if networkInterface.Attachment == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return networkInterface.Attachment, nil +} + +func findNetworkInterfacesByAttachmentInstanceOwnerIDAndDescription(ctx context.Context, conn *ec2.Client, attachmentInstanceOwnerID, description string) ([]awstypes.NetworkInterface, error) { + input := &ec2.DescribeNetworkInterfacesInput{ + Filters: newAttributeFilterList(map[string]string{ + "attachment.instance-owner-id": attachmentInstanceOwnerID, + names.AttrDescription: description, + }), + } + + return findNetworkInterfaces(ctx, conn, input) +} + +func findNetworkInterfaceByAttachmentID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInterface, error) { + input := &ec2.DescribeNetworkInterfacesInput{ + Filters: newAttributeFilterList(map[string]string{ + "attachment.attachment-id": id, + }), + } + + networkInterface, err := findNetworkInterface(ctx, conn, input) + + if err != nil { + return nil, err + } + + if networkInterface == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return networkInterface, nil +} + +func findNetworkInterfaceSecurityGroup(ctx context.Context, conn *ec2.Client, networkInterfaceID string, securityGroupID string) (*awstypes.GroupIdentifier, error) { + networkInterface, err := findNetworkInterfaceByID(ctx, conn, networkInterfaceID) + + if err != nil { + return nil, err + } + + for _, groupIdentifier := range networkInterface.Groups { + if aws.ToString(groupIdentifier.GroupId) == securityGroupID { + return &groupIdentifier, nil + } + } + + return nil, &retry.NotFoundError{ + LastError: fmt.Errorf("Network Interface (%s) Security Group (%s) not found", networkInterfaceID, securityGroupID), + } +} + +func findEBSVolumes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesInput) ([]awstypes.Volume, error) { + var output []awstypes.Volume + + pages := ec2.NewDescribeVolumesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVolumeNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.Volumes...) + } + + return output, nil +} + +func findEBSVolume(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesInput) (*awstypes.Volume, error) { + output, err := findEBSVolumes(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findEBSVolumeByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Volume, error) { + input := &ec2.DescribeVolumesInput{ + VolumeIds: []string{id}, + } + + output, err := findEBSVolume(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.VolumeStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.VolumeId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findEgressOnlyInternetGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeEgressOnlyInternetGatewaysInput) (*awstypes.EgressOnlyInternetGateway, error) { + output, err := findEgressOnlyInternetGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findEgressOnlyInternetGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeEgressOnlyInternetGatewaysInput) ([]awstypes.EgressOnlyInternetGateway, error) { + var output []awstypes.EgressOnlyInternetGateway + + pages := ec2.NewDescribeEgressOnlyInternetGatewaysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.EgressOnlyInternetGateways...) + } + + return output, nil +} + +func findEgressOnlyInternetGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.EgressOnlyInternetGateway, error) { + input := &ec2.DescribeEgressOnlyInternetGatewaysInput{ + EgressOnlyInternetGatewayIds: []string{id}, + } + + output, err := findEgressOnlyInternetGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.EgressOnlyInternetGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findPrefixList(ctx context.Context, conn *ec2.Client, input *ec2.DescribePrefixListsInput) (*awstypes.PrefixList, error) { + output, err := findPrefixLists(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findPrefixLists(ctx context.Context, conn *ec2.Client, input *ec2.DescribePrefixListsInput) ([]awstypes.PrefixList, error) { + var output []awstypes.PrefixList + + pages := ec2.NewDescribePrefixListsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.PrefixLists...) + } + + return output, nil +} + +func findVPCEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpcEndpoint, error) { + input := &ec2.DescribeVpcEndpointsInput{ + VpcEndpointIds: []string{id}, + } + + output, err := findVPCEndpoint(ctx, conn, input) + + if err != nil { + return nil, err + } + + if output.State == awstypes.StateDeleted { + return nil, &retry.NotFoundError{ + Message: string(output.State), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.VpcEndpointId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVPCEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointsInput) (*awstypes.VpcEndpoint, error) { + output, err := findVPCEndpoints(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVPCEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointsInput) ([]awstypes.VpcEndpoint, error) { + var output []awstypes.VpcEndpoint + + pages := ec2.NewDescribeVpcEndpointsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.VpcEndpoints...) + } + + return output, nil +} + +func findPrefixListByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PrefixList, error) { + input := &ec2.DescribePrefixListsInput{ + Filters: newAttributeFilterList(map[string]string{ + "prefix-list-name": name, + }), + } + + return findPrefixList(ctx, conn, input) +} + +func findSpotFleetInstances(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetInstancesInput) ([]awstypes.ActiveInstance, error) { + var output []awstypes.ActiveInstance + + err := describeSpotFleetInstancesPages(ctx, conn, input, func(page *ec2.DescribeSpotFleetInstancesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + output = append(output, page.ActiveInstances...) + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotFleetRequestIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output, nil +} + +func findSpotFleetRequests(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetRequestsInput) ([]awstypes.SpotFleetRequestConfig, error) { + var output []awstypes.SpotFleetRequestConfig + + paginator := ec2.NewDescribeSpotFleetRequestsPaginator(conn, input) + for paginator.HasMorePages() { + page, err := paginator.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotFleetRequestIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.SpotFleetRequestConfigs...) + } + + return output, nil +} + +func findSpotFleetRequest(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetRequestsInput) (*awstypes.SpotFleetRequestConfig, error) { + output, err := findSpotFleetRequests(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.SpotFleetRequestConfig) bool { return v.SpotFleetRequestConfig != nil }) +} + +func findSpotFleetRequestByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SpotFleetRequestConfig, error) { + input := &ec2.DescribeSpotFleetRequestsInput{ + SpotFleetRequestIds: []string{id}, + } + + output, err := findSpotFleetRequest(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.SpotFleetRequestState; state == awstypes.BatchStateCancelled || state == awstypes.BatchStateCancelledRunning || state == awstypes.BatchStateCancelledTerminatingInstances { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.SpotFleetRequestId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSpotFleetRequestHistoryRecords(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetRequestHistoryInput) ([]awstypes.HistoryRecord, error) { + var output []awstypes.HistoryRecord + + err := describeSpotFleetRequestHistoryPages(ctx, conn, input, func(page *ec2.DescribeSpotFleetRequestHistoryOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + output = append(output, page.HistoryRecords...) + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotFleetRequestIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output, nil +} + +func findVPCEndpointServiceConfigurationByServiceName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.ServiceConfiguration, error) { + input := &ec2.DescribeVpcEndpointServiceConfigurationsInput{ + Filters: newAttributeFilterList(map[string]string{ + "service-name": name, + }), + } + + return findVPCEndpointServiceConfiguration(ctx, conn, input) +} + +func findVPCEndpointServiceConfiguration(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServiceConfigurationsInput) (*awstypes.ServiceConfiguration, error) { + output, err := findVPCEndpointServiceConfigurations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVPCEndpointServiceConfigurations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServiceConfigurationsInput) ([]awstypes.ServiceConfiguration, error) { + var output []awstypes.ServiceConfiguration + + pages := ec2.NewDescribeVpcEndpointServiceConfigurationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.ServiceConfigurations...) + } + + return output, nil +} + +// findRouteTableByID returns the route table corresponding to the specified identifier. +// Returns NotFoundError if no route table is found. +func findRouteTableByID(ctx context.Context, conn *ec2.Client, routeTableID string) (*awstypes.RouteTable, error) { + input := &ec2.DescribeRouteTablesInput{ + RouteTableIds: []string{routeTableID}, + } + + return findRouteTable(ctx, conn, input) +} + +// routeFinder returns the route corresponding to the specified destination. +// Returns NotFoundError if no route is found. +type routeFinder func(context.Context, *ec2.Client, string, string) (*awstypes.Route, error) + +// findRouteByIPv4Destination returns the route corresponding to the specified IPv4 destination. +// Returns NotFoundError if no route is found. +func findRouteByIPv4Destination(ctx context.Context, conn *ec2.Client, routeTableID, destinationCidr string) (*awstypes.Route, error) { + routeTable, err := findRouteTableByID(ctx, conn, routeTableID) + + if err != nil { + return nil, err + } + + for _, route := range routeTable.Routes { + if types.CIDRBlocksEqual(aws.ToString(route.DestinationCidrBlock), destinationCidr) { + return &route, nil + } + } + + return nil, &retry.NotFoundError{ + LastError: fmt.Errorf("Route in Route Table (%s) with IPv4 destination (%s) not found", routeTableID, destinationCidr), + } +} + +// findRouteByIPv6Destination returns the route corresponding to the specified IPv6 destination. +// Returns NotFoundError if no route is found. +func findRouteByIPv6Destination(ctx context.Context, conn *ec2.Client, routeTableID, destinationIpv6Cidr string) (*awstypes.Route, error) { + routeTable, err := findRouteTableByID(ctx, conn, routeTableID) + + if err != nil { + return nil, err + } + + for _, route := range routeTable.Routes { + if types.CIDRBlocksEqual(aws.ToString(route.DestinationIpv6CidrBlock), destinationIpv6Cidr) { + return &route, nil + } + } + + return nil, &retry.NotFoundError{ + LastError: fmt.Errorf("Route in Route Table (%s) with IPv6 destination (%s) not found", routeTableID, destinationIpv6Cidr), + } +} + +// findRouteByPrefixListIDDestination returns the route corresponding to the specified prefix list destination. +// Returns NotFoundError if no route is found. +func findRouteByPrefixListIDDestination(ctx context.Context, conn *ec2.Client, routeTableID, prefixListID string) (*awstypes.Route, error) { + routeTable, err := findRouteTableByID(ctx, conn, routeTableID) + if err != nil { + return nil, err + } + + for _, route := range routeTable.Routes { + if aws.ToString(route.DestinationPrefixListId) == prefixListID { + return &route, nil + } + } + + return nil, &retry.NotFoundError{ + LastError: fmt.Errorf("Route in Route Table (%s) with Prefix List ID destination (%s) not found", routeTableID, prefixListID), + } +} + +func findManagedPrefixList(ctx context.Context, conn *ec2.Client, input *ec2.DescribeManagedPrefixListsInput) (*awstypes.ManagedPrefixList, error) { + output, err := findManagedPrefixLists(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findManagedPrefixLists(ctx context.Context, conn *ec2.Client, input *ec2.DescribeManagedPrefixListsInput) ([]awstypes.ManagedPrefixList, error) { + var output []awstypes.ManagedPrefixList + + pages := ec2.NewDescribeManagedPrefixListsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.PrefixLists...) + } + + return output, nil +} + +func findManagedPrefixListByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ManagedPrefixList, error) { + input := &ec2.DescribeManagedPrefixListsInput{ + PrefixListIds: []string{id}, + } + + output, err := findManagedPrefixList(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.PrefixListStateDeleteComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.PrefixListId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findManagedPrefixListEntries(ctx context.Context, conn *ec2.Client, input *ec2.GetManagedPrefixListEntriesInput) ([]awstypes.PrefixListEntry, error) { + var output []awstypes.PrefixListEntry + + pages := ec2.NewGetManagedPrefixListEntriesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Entries...) + } + + return output, nil +} + +func findManagedPrefixListEntriesByID(ctx context.Context, conn *ec2.Client, id string) ([]awstypes.PrefixListEntry, error) { + input := &ec2.GetManagedPrefixListEntriesInput{ + PrefixListId: aws.String(id), + } + + return findManagedPrefixListEntries(ctx, conn, input) +} + +func findManagedPrefixListEntryByIDAndCIDR(ctx context.Context, conn *ec2.Client, id, cidr string) (*awstypes.PrefixListEntry, error) { + prefixListEntries, err := findManagedPrefixListEntriesByID(ctx, conn, id) + + if err != nil { + return nil, err + } + + for _, v := range prefixListEntries { + if aws.ToString(v.Cidr) == cidr { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +// findMainRouteTableAssociationByID returns the main route table association corresponding to the specified identifier. +// Returns NotFoundError if no route table association is found. +func findMainRouteTableAssociationByID(ctx context.Context, conn *ec2.Client, associationID string) (*awstypes.RouteTableAssociation, error) { + association, err := findRouteTableAssociationByID(ctx, conn, associationID) + + if err != nil { + return nil, err + } + + if !aws.ToBool(association.Main) { + return nil, &retry.NotFoundError{ + Message: fmt.Sprintf("%s is not the association with the main route table", associationID), + } + } + + return association, err +} + +// findMainRouteTableAssociationByVPCID returns the main route table association for the specified VPC. +// Returns NotFoundError if no route table association is found. +func findMainRouteTableAssociationByVPCID(ctx context.Context, conn *ec2.Client, vpcID string) (*awstypes.RouteTableAssociation, error) { + routeTable, err := findMainRouteTableByVPCID(ctx, conn, vpcID) + + if err != nil { + return nil, err + } + + for _, association := range routeTable.Associations { + if aws.ToBool(association.Main) { + if association.AssociationState != nil { + if state := association.AssociationState.State; state == awstypes.RouteTableAssociationStateCodeDisassociated { + continue + } + } + + return &association, nil + } + } + + return nil, &retry.NotFoundError{} +} + +// findRouteTableAssociationByID returns the route table association corresponding to the specified identifier. +// Returns NotFoundError if no route table association is found. +func findRouteTableAssociationByID(ctx context.Context, conn *ec2.Client, associationID string) (*awstypes.RouteTableAssociation, error) { + input := &ec2.DescribeRouteTablesInput{ + Filters: newAttributeFilterList(map[string]string{ + "association.route-table-association-id": associationID, + }), + } + + routeTable, err := findRouteTable(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, association := range routeTable.Associations { + if aws.ToString(association.RouteTableAssociationId) == associationID { + if association.AssociationState != nil { + if state := association.AssociationState.State; state == awstypes.RouteTableAssociationStateCodeDisassociated { + return nil, &retry.NotFoundError{Message: string(state)} + } + } + + return &association, nil + } + } + + return nil, &retry.NotFoundError{} +} + +// findMainRouteTableByVPCID returns the main route table for the specified VPC. +// Returns NotFoundError if no route table is found. +func findMainRouteTableByVPCID(ctx context.Context, conn *ec2.Client, vpcID string) (*awstypes.RouteTable, error) { + input := &ec2.DescribeRouteTablesInput{ + Filters: newAttributeFilterList(map[string]string{ + "association.main": "true", + "vpc-id": vpcID, + }), + } + + return findRouteTable(ctx, conn, input) +} + +// findVPNGatewayRoutePropagationExists returns NotFoundError if no route propagation for the specified VPN gateway is found. +func findVPNGatewayRoutePropagationExists(ctx context.Context, conn *ec2.Client, routeTableID, gatewayID string) error { + routeTable, err := findRouteTableByID(ctx, conn, routeTableID) + + if err != nil { + return err + } + + for _, v := range routeTable.PropagatingVgws { + if aws.ToString(v.GatewayId) == gatewayID { + return nil + } + } + + return &retry.NotFoundError{ + LastError: fmt.Errorf("Route Table (%s) VPN Gateway (%s) route propagation not found", routeTableID, gatewayID), + } +} + +func findVPCEndpointServiceConfigurationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ServiceConfiguration, error) { + input := &ec2.DescribeVpcEndpointServiceConfigurationsInput{ + ServiceIds: []string{id}, + } + + output, err := findVPCEndpointServiceConfiguration(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.ServiceState; state == awstypes.ServiceStateDeleted || state == awstypes.ServiceStateFailed { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.ServiceId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVPCEndpointServicePrivateDNSNameConfigurationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.PrivateDnsNameConfiguration, error) { + out, err := findVPCEndpointServiceConfigurationByID(ctx, conn, id) + if err != nil { + return nil, err + } + + return out.PrivateDnsNameConfiguration, nil +} + +func findVPCEndpointServicePermissions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServicePermissionsInput) ([]awstypes.AllowedPrincipal, error) { + var output []awstypes.AllowedPrincipal + + pages := ec2.NewDescribeVpcEndpointServicePermissionsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.AllowedPrincipals...) + } + + return output, nil +} + +func findVPCEndpointServicePermissionsByServiceID(ctx context.Context, conn *ec2.Client, id string) ([]awstypes.AllowedPrincipal, error) { + input := &ec2.DescribeVpcEndpointServicePermissionsInput{ + ServiceId: aws.String(id), + } + + return findVPCEndpointServicePermissions(ctx, conn, input) +} + +func findVPCEndpointServices(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServicesInput) ([]awstypes.ServiceDetail, []string, error) { + var serviceDetails []awstypes.ServiceDetail + var serviceNames []string + + err := describeVPCEndpointServicesPages(ctx, conn, input, func(page *ec2.DescribeVpcEndpointServicesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + serviceDetails = append(serviceDetails, page.ServiceDetails...) + serviceNames = append(serviceNames, page.ServiceNames...) + + return !lastPage + }) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidServiceName) { + return nil, nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, nil, err + } + + return serviceDetails, serviceNames, nil +} + +// findVPCEndpointRouteTableAssociationExists returns NotFoundError if no association for the specified VPC endpoint and route table IDs is found. +func findVPCEndpointRouteTableAssociationExists(ctx context.Context, conn *ec2.Client, vpcEndpointID string, routeTableID string) error { + vpcEndpoint, err := findVPCEndpointByID(ctx, conn, vpcEndpointID) + + if err != nil { + return err + } + + for _, vpcEndpointRouteTableID := range vpcEndpoint.RouteTableIds { + if vpcEndpointRouteTableID == routeTableID { + return nil + } + } + + return &retry.NotFoundError{ + LastError: fmt.Errorf("VPC Endpoint (%s) Route Table (%s) Association not found", vpcEndpointID, routeTableID), + } +} + +// findVPCEndpointSecurityGroupAssociationExists returns NotFoundError if no association for the specified VPC endpoint and security group IDs is found. +func findVPCEndpointSecurityGroupAssociationExists(ctx context.Context, conn *ec2.Client, vpcEndpointID, securityGroupID string) error { + vpcEndpoint, err := findVPCEndpointByID(ctx, conn, vpcEndpointID) + + if err != nil { + return err + } + + for _, group := range vpcEndpoint.Groups { + if aws.ToString(group.GroupId) == securityGroupID { + return nil + } + } + + return &retry.NotFoundError{ + LastError: fmt.Errorf("VPC Endpoint (%s) Security Group (%s) Association not found", vpcEndpointID, securityGroupID), + } +} + +// findVPCEndpointSubnetAssociationExists returns NotFoundError if no association for the specified VPC endpoint and subnet IDs is found. +func findVPCEndpointSubnetAssociationExists(ctx context.Context, conn *ec2.Client, vpcEndpointID string, subnetID string) error { + vpcEndpoint, err := findVPCEndpointByID(ctx, conn, vpcEndpointID) + + if err != nil { + return err + } + + for _, vpcEndpointSubnetID := range vpcEndpoint.SubnetIds { + if vpcEndpointSubnetID == subnetID { + return nil + } + } + + return &retry.NotFoundError{ + LastError: fmt.Errorf("VPC Endpoint (%s) Subnet (%s) Association not found", vpcEndpointID, subnetID), + } +} + +func findVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx context.Context, conn *ec2.Client, serviceID, vpcEndpointID string) (*awstypes.VpcEndpointConnection, error) { + input := &ec2.DescribeVpcEndpointConnectionsInput{ + Filters: newAttributeFilterList(map[string]string{ + "service-id": serviceID, + // "InvalidFilter: The filter vpc-endpoint-id is invalid" + // "vpc-endpoint-id ": vpcEndpointID, + }), + } + + var output *awstypes.VpcEndpointConnection + + pages := ec2.NewDescribeVpcEndpointConnectionsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + if err != nil { + return nil, err + } + + for _, v := range page.VpcEndpointConnections { + v := v + if aws.ToString(v.VpcEndpointId) == vpcEndpointID { + output = &v + break + } + } + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + if vpcEndpointState := string(output.VpcEndpointState); vpcEndpointState == vpcEndpointStateDeleted { + return nil, &retry.NotFoundError{ + Message: vpcEndpointState, + LastRequest: input, + } + } + + return output, nil +} + +func findVPCEndpointConnectionNotification(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointConnectionNotificationsInput) (*awstypes.ConnectionNotification, error) { + output, err := findVPCEndpointConnectionNotifications(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVPCEndpointConnectionNotifications(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointConnectionNotificationsInput) ([]awstypes.ConnectionNotification, error) { + var output []awstypes.ConnectionNotification + + pages := ec2.NewDescribeVpcEndpointConnectionNotificationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidConnectionNotification) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.ConnectionNotificationSet...) + } + + return output, nil +} + +func findVPCEndpointConnectionNotificationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ConnectionNotification, error) { + input := &ec2.DescribeVpcEndpointConnectionNotificationsInput{ + ConnectionNotificationId: aws.String(id), + } + + output, err := findVPCEndpointConnectionNotification(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.ConnectionNotificationId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVPCEndpointServicePermission(ctx context.Context, conn *ec2.Client, serviceID, principalARN string) (*awstypes.AllowedPrincipal, error) { + // Applying a server-side filter on "principal" can lead to errors like + // "An error occurred (InvalidFilter) when calling the DescribeVpcEndpointServicePermissions operation: The filter value arn:aws:iam::123456789012:role/developer contains unsupported characters". + // Apply the filter client-side. + input := &ec2.DescribeVpcEndpointServicePermissionsInput{ + ServiceId: aws.String(serviceID), + } + + allowedPrincipals, err := findVPCEndpointServicePermissions(ctx, conn, input) + + if err != nil { + return nil, err + } + + allowedPrincipals = tfslices.Filter(allowedPrincipals, func(v awstypes.AllowedPrincipal) bool { + return aws.ToString(v.Principal) == principalARN + }) + + return tfresource.AssertSingleValueResult(allowedPrincipals) +} + +func findVPCPeeringConnection(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcPeeringConnectionsInput) (*awstypes.VpcPeeringConnection, error) { + output, err := findVPCPeeringConnections(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.VpcPeeringConnection) bool { return v.Status != nil }) +} + +func findVPCPeeringConnections(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcPeeringConnectionsInput) ([]awstypes.VpcPeeringConnection, error) { + var output []awstypes.VpcPeeringConnection + + pages := ec2.NewDescribeVpcPeeringConnectionsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCPeeringConnectionIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.VpcPeeringConnections...) + } + + return output, nil +} + +func findVPCPeeringConnectionByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpcPeeringConnection, error) { + input := &ec2.DescribeVpcPeeringConnectionsInput{ + VpcPeeringConnectionIds: []string{id}, + } + + output, err := findVPCPeeringConnection(ctx, conn, input) + + if err != nil { + return nil, err + } + + // See https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-lifecycle. + switch statusCode := output.Status.Code; statusCode { + case awstypes.VpcPeeringConnectionStateReasonCodeDeleted, + awstypes.VpcPeeringConnectionStateReasonCodeExpired, + awstypes.VpcPeeringConnectionStateReasonCodeFailed, + awstypes.VpcPeeringConnectionStateReasonCodeRejected: + return nil, &retry.NotFoundError{ + Message: string(statusCode), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.VpcPeeringConnectionId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findClientVPNEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnEndpointsInput) (*awstypes.ClientVpnEndpoint, error) { + output, err := findClientVPNEndpoints(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findClientVPNEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnEndpointsInput) ([]awstypes.ClientVpnEndpoint, error) { + var output []awstypes.ClientVpnEndpoint + + pages := ec2.NewDescribeClientVpnEndpointsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.ClientVpnEndpoints...) + } + + return output, nil +} + +func findClientVPNEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ClientVpnEndpoint, error) { + input := &ec2.DescribeClientVpnEndpointsInput{ + ClientVpnEndpointIds: []string{id}, + } + + output, err := findClientVPNEndpoint(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.Status.Code; state == awstypes.ClientVpnEndpointStatusCodeDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.ClientVpnEndpointId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findClientVPNEndpointClientConnectResponseOptionsByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ClientConnectResponseOptions, error) { + output, err := findClientVPNEndpointByID(ctx, conn, id) + + if err != nil { + return nil, err + } + + if output.ClientConnectOptions == nil || output.ClientConnectOptions.Status == nil { + return nil, tfresource.NewEmptyResultError(id) + } + + return output.ClientConnectOptions, nil +} + +func findClientVPNAuthorizationRule(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnAuthorizationRulesInput) (*awstypes.AuthorizationRule, error) { + output, err := findClientVPNAuthorizationRules(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findClientVPNAuthorizationRules(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnAuthorizationRulesInput) ([]awstypes.AuthorizationRule, error) { + var output []awstypes.AuthorizationRule + + pages := ec2.NewDescribeClientVpnAuthorizationRulesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.AuthorizationRules...) + } + + return output, nil +} + +func findClientVPNAuthorizationRuleByThreePartKey(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string) (*awstypes.AuthorizationRule, error) { + filters := map[string]string{ + "destination-cidr": targetNetworkCIDR, + } + if accessGroupID != "" { + filters["group-id"] = accessGroupID + } + input := &ec2.DescribeClientVpnAuthorizationRulesInput{ + ClientVpnEndpointId: aws.String(endpointID), + Filters: newAttributeFilterList(filters), + } + + return findClientVPNAuthorizationRule(ctx, conn, input) +} + +func findClientVPNNetworkAssociation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnTargetNetworksInput) (*awstypes.TargetNetwork, error) { + output, err := findClientVPNNetworkAssociations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findClientVPNNetworkAssociations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnTargetNetworksInput) ([]awstypes.TargetNetwork, error) { + var output []awstypes.TargetNetwork + + pages := ec2.NewDescribeClientVpnTargetNetworksPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound, errCodeInvalidClientVPNAssociationIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.ClientVpnTargetNetworks...) + } + + return output, nil +} + +func findClientVPNNetworkAssociationByTwoPartKey(ctx context.Context, conn *ec2.Client, associationID, endpointID string) (*awstypes.TargetNetwork, error) { + input := &ec2.DescribeClientVpnTargetNetworksInput{ + AssociationIds: []string{associationID}, + ClientVpnEndpointId: aws.String(endpointID), + } + + output, err := findClientVPNNetworkAssociation(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.Status.Code; state == awstypes.AssociationStatusCodeDisassociated { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.ClientVpnEndpointId) != endpointID || aws.ToString(output.AssociationId) != associationID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findClientVPNRoute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnRoutesInput) (*awstypes.ClientVpnRoute, error) { + output, err := findClientVPNRoutes(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findClientVPNRoutes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnRoutesInput) ([]awstypes.ClientVpnRoute, error) { + var output []awstypes.ClientVpnRoute + + pages := ec2.NewDescribeClientVpnRoutesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Routes...) + } + + return output, nil +} + +func findClientVPNRouteByThreePartKey(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string) (*awstypes.ClientVpnRoute, error) { + input := &ec2.DescribeClientVpnRoutesInput{ + ClientVpnEndpointId: aws.String(endpointID), + Filters: newAttributeFilterList(map[string]string{ + "destination-cidr": destinationCIDR, + "target-subnet": targetSubnetID, + }), + } + + return findClientVPNRoute(ctx, conn, input) +} + +func findCarrierGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCarrierGatewaysInput) (*awstypes.CarrierGateway, error) { + output, err := findCarrierGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findCarrierGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCarrierGatewaysInput) ([]awstypes.CarrierGateway, error) { + var output []awstypes.CarrierGateway + + pages := ec2.NewDescribeCarrierGatewaysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidCarrierGatewayIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.CarrierGateways...) + } + + return output, nil +} + +func findCarrierGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CarrierGateway, error) { + input := &ec2.DescribeCarrierGatewaysInput{ + CarrierGatewayIds: []string{id}, + } + + output, err := findCarrierGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.CarrierGatewayStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.CarrierGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVPNConnection(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnConnectionsInput) (*awstypes.VpnConnection, error) { + output, err := findVPNConnections(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVPNConnections(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnConnectionsInput) ([]awstypes.VpnConnection, error) { + output, err := conn.DescribeVpnConnections(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPNConnectionIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output.VpnConnections, nil +} + +func findVPNConnectionByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { + input := &ec2.DescribeVpnConnectionsInput{ + VpnConnectionIds: []string{id}, + } + + output, err := findVPNConnection(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.VpnStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.VpnConnectionId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVPNConnectionRouteByTwoPartKey(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) (*awstypes.VpnStaticRoute, error) { + input := &ec2.DescribeVpnConnectionsInput{ + Filters: newAttributeFilterList(map[string]string{ + "route.destination-cidr-block": cidrBlock, + "vpn-connection-id": vpnConnectionID, + }), + } + + output, err := findVPNConnection(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, v := range output.Routes { + if aws.ToString(v.DestinationCidrBlock) == cidrBlock && v.State != awstypes.VpnStateDeleted { + return &v, nil + } + } + + return nil, &retry.NotFoundError{ + LastError: fmt.Errorf("EC2 VPN Connection (%s) Route (%s) not found", vpnConnectionID, cidrBlock), + } +} + +func findVPNGatewayVPCAttachmentByTwoPartKey(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) (*awstypes.VpcAttachment, error) { + vpnGateway, err := findVPNGatewayByID(ctx, conn, vpnGatewayID) + + if err != nil { + return nil, err + } + + for _, vpcAttachment := range vpnGateway.VpcAttachments { + if aws.ToString(vpcAttachment.VpcId) == vpcID { + if state := vpcAttachment.State; state == awstypes.AttachmentStatusDetached { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: vpcID, + } + } + + return &vpcAttachment, nil + } + } + + return nil, tfresource.NewEmptyResultError(vpcID) +} + +func findVPNGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnGatewaysInput) (*awstypes.VpnGateway, error) { + output, err := findVPNGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVPNGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnGatewaysInput) ([]awstypes.VpnGateway, error) { + output, err := conn.DescribeVpnGateways(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPNGatewayIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.VpnGateways, nil +} + +func findVPNGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnGateway, error) { + input := &ec2.DescribeVpnGatewaysInput{ + VpnGatewayIds: []string{id}, + } + + output, err := findVPNGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.VpnStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.VpnGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findCustomerGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCustomerGatewaysInput) (*awstypes.CustomerGateway, error) { + output, err := findCustomerGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findCustomerGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCustomerGatewaysInput) ([]awstypes.CustomerGateway, error) { + output, err := conn.DescribeCustomerGateways(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidCustomerGatewayIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.CustomerGateways, nil +} + +func findCustomerGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CustomerGateway, error) { + input := &ec2.DescribeCustomerGatewaysInput{ + CustomerGatewayIds: []string{id}, + } + + output, err := findCustomerGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := aws.ToString(output.State); state == customerGatewayStateDeleted { + return nil, &retry.NotFoundError{ + Message: state, + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.CustomerGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAM(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamsInput) (*awstypes.Ipam, error) { + output, err := findIPAMs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamsInput) ([]awstypes.Ipam, error) { + var output []awstypes.Ipam + + pages := ec2.NewDescribeIpamsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Ipams...) + } + + return output, nil +} + +func findIPAMByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Ipam, error) { + input := &ec2.DescribeIpamsInput{ + IpamIds: []string{id}, + } + + output, err := findIPAM(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.IpamStateDeleteComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.IpamId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMPool(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamPoolsInput) (*awstypes.IpamPool, error) { + output, err := findIPAMPools(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMPools(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamPoolsInput) ([]awstypes.IpamPool, error) { + var output []awstypes.IpamPool + + pages := ec2.NewDescribeIpamPoolsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMPoolIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.IpamPools...) + } + + return output, nil +} + +func findIPAMPoolByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamPool, error) { + input := &ec2.DescribeIpamPoolsInput{ + IpamPoolIds: []string{id}, + } + + output, err := findIPAMPool(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.IpamPoolStateDeleteComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.IpamPoolId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMPoolAllocation(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolAllocationsInput) (*awstypes.IpamPoolAllocation, error) { + output, err := findIPAMPoolAllocations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMPoolAllocations(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolAllocationsInput) ([]awstypes.IpamPoolAllocation, error) { + var output []awstypes.IpamPoolAllocation + + pages := ec2.NewGetIpamPoolAllocationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMPoolAllocationIdNotFound, errCodeInvalidIPAMPoolIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.IpamPoolAllocations...) + } + + return output, nil +} + +func findIPAMPoolAllocationByTwoPartKey(ctx context.Context, conn *ec2.Client, allocationID, poolID string) (*awstypes.IpamPoolAllocation, error) { + input := &ec2.GetIpamPoolAllocationsInput{ + IpamPoolAllocationId: aws.String(allocationID), + IpamPoolId: aws.String(poolID), + } + + output, err := findIPAMPoolAllocation(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.IpamPoolAllocationId) != allocationID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMPoolCIDR(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolCidrsInput) (*awstypes.IpamPoolCidr, error) { + output, err := findIPAMPoolCIDRs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMPoolCIDRs(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolCidrsInput) ([]awstypes.IpamPoolCidr, error) { + var output []awstypes.IpamPoolCidr + + pages := ec2.NewGetIpamPoolCidrsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMPoolIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.IpamPoolCidrs...) + } + + return output, nil +} + +func findIPAMPoolCIDRByTwoPartKey(ctx context.Context, conn *ec2.Client, cidrBlock, poolID string) (*awstypes.IpamPoolCidr, error) { + input := &ec2.GetIpamPoolCidrsInput{ + Filters: newAttributeFilterList(map[string]string{ + "cidr": cidrBlock, + }), + IpamPoolId: aws.String(poolID), + } + + output, err := findIPAMPoolCIDR(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.IpamPoolCidrStateDeprovisioned { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.Cidr) != cidrBlock { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMPoolCIDRByPoolCIDRIDAndPoolID(ctx context.Context, conn *ec2.Client, poolCIDRID, poolID string) (*awstypes.IpamPoolCidr, error) { + input := &ec2.GetIpamPoolCidrsInput{ + Filters: newAttributeFilterList(map[string]string{ + "ipam-pool-cidr-id": poolCIDRID, + }), + IpamPoolId: aws.String(poolID), + } + + output, err := findIPAMPoolCIDR(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check + if aws.ToString(output.Cidr) == "" { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + if state := output.State; state == awstypes.IpamPoolCidrStateDeprovisioned { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMResourceDiscovery(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveriesInput) (*awstypes.IpamResourceDiscovery, error) { + output, err := findIPAMResourceDiscoveries(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMResourceDiscoveries(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveriesInput) ([]awstypes.IpamResourceDiscovery, error) { + var output []awstypes.IpamResourceDiscovery + + pages := ec2.NewDescribeIpamResourceDiscoveriesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMResourceDiscoveryIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.IpamResourceDiscoveries...) + } + + return output, nil +} + +func findIPAMResourceDiscoveryByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamResourceDiscovery, error) { + input := &ec2.DescribeIpamResourceDiscoveriesInput{ + IpamResourceDiscoveryIds: []string{id}, + } + + output, err := findIPAMResourceDiscovery(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.IpamResourceDiscoveryStateDeleteComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.IpamResourceDiscoveryId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMResourceDiscoveryAssociation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveryAssociationsInput) (*awstypes.IpamResourceDiscoveryAssociation, error) { + output, err := findIPAMResourceDiscoveryAssociations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMResourceDiscoveryAssociations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveryAssociationsInput) ([]awstypes.IpamResourceDiscoveryAssociation, error) { + var output []awstypes.IpamResourceDiscoveryAssociation + + pages := ec2.NewDescribeIpamResourceDiscoveryAssociationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMResourceDiscoveryAssociationIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.IpamResourceDiscoveryAssociations...) + } + + return output, nil +} + +func findIPAMResourceDiscoveryAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamResourceDiscoveryAssociation, error) { + input := &ec2.DescribeIpamResourceDiscoveryAssociationsInput{ + IpamResourceDiscoveryAssociationIds: []string{id}, + } + + output, err := findIPAMResourceDiscoveryAssociation(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.IpamResourceDiscoveryAssociationStateDisassociateComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.IpamResourceDiscoveryAssociationId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findIPAMScope(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamScopesInput) (*awstypes.IpamScope, error) { + output, err := findIPAMScopes(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findIPAMScopes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamScopesInput) ([]awstypes.IpamScope, error) { + var output []awstypes.IpamScope + + pages := ec2.NewDescribeIpamScopesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMScopeIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.IpamScopes...) + } + + return output, nil +} + +func findIPAMScopeByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamScope, error) { + input := &ec2.DescribeIpamScopesInput{ + IpamScopeIds: []string{id}, + } + + output, err := findIPAMScope(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.IpamScopeStateDeleteComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.IpamScopeId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findImages(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImagesInput) ([]awstypes.Image, error) { + var output []awstypes.Image + + pages := ec2.NewDescribeImagesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Images...) + } + + return output, nil +} + +func findImage(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImagesInput) (*awstypes.Image, error) { + output, err := findImages(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findImageByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Image, error) { + input := &ec2.DescribeImagesInput{ + ImageIds: []string{id}, + } + + output, err := findImage(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.ImageStateDeregistered { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.ImageId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findImageAttribute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImageAttributeInput) (*ec2.DescribeImageAttributeOutput, error) { + output, err := conn.DescribeImageAttribute(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDNotFound, errCodeInvalidAMIIDUnavailable) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +func findImageBlockPublicAccessState(ctx context.Context, conn *ec2.Client) (*string, error) { + input := &ec2.GetImageBlockPublicAccessStateInput{} + output, err := conn.GetImageBlockPublicAccessState(ctx, input) + + if err != nil { + return nil, err + } + + if output == nil || output.ImageBlockPublicAccessState == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.ImageBlockPublicAccessState, nil +} + +func findImageLaunchPermissionsByID(ctx context.Context, conn *ec2.Client, id string) ([]awstypes.LaunchPermission, error) { + input := &ec2.DescribeImageAttributeInput{ + Attribute: awstypes.ImageAttributeNameLaunchPermission, + ImageId: aws.String(id), + } + + output, err := findImageAttribute(ctx, conn, input) + + if err != nil { + return nil, err + } + + if len(output.LaunchPermissions) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.LaunchPermissions, nil +} + +func findImageLaunchPermission(ctx context.Context, conn *ec2.Client, imageID, accountID, group, organizationARN, organizationalUnitARN string) (*awstypes.LaunchPermission, error) { + output, err := findImageLaunchPermissionsByID(ctx, conn, imageID) + + if err != nil { + return nil, err + } + + for _, v := range output { + if (accountID != "" && aws.ToString(v.UserId) == accountID) || + (group != "" && string(v.Group) == group) || + (organizationARN != "" && aws.ToString(v.OrganizationArn) == organizationARN) || + (organizationalUnitARN != "" && aws.ToString(v.OrganizationalUnitArn) == organizationalUnitARN) { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findTransitGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewaysInput) (*awstypes.TransitGateway, error) { + output, err := findTransitGateways(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGateway) bool { return v.Options != nil }) +} + +func findTransitGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewaysInput) ([]awstypes.TransitGateway, error) { + var output []awstypes.TransitGateway + + pages := ec2.NewDescribeTransitGatewaysPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGateways...) + } + + return output, nil +} + +func findTransitGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGateway, error) { + input := &ec2.DescribeTransitGatewaysInput{ + TransitGatewayIds: []string{id}, + } + + output, err := findTransitGateway(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayAttachment(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayAttachmentsInput) (*awstypes.TransitGatewayAttachment, error) { + output, err := findTransitGatewayAttachments(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayAttachments(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayAttachmentsInput) ([]awstypes.TransitGatewayAttachment, error) { + var output []awstypes.TransitGatewayAttachment + + pages := ec2.NewDescribeTransitGatewayAttachmentsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayAttachments...) + } + + return output, nil +} + +func findTransitGatewayAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayAttachment, error) { + input := &ec2.DescribeTransitGatewayAttachmentsInput{ + TransitGatewayAttachmentIds: []string{id}, + } + + output, err := findTransitGatewayAttachment(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayConnect(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectsInput) (*awstypes.TransitGatewayConnect, error) { + output, err := findTransitGatewayConnects(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayConnect) bool { return v.Options != nil }) +} + +func findTransitGatewayConnects(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectsInput) ([]awstypes.TransitGatewayConnect, error) { + var output []awstypes.TransitGatewayConnect + + pages := ec2.NewDescribeTransitGatewayConnectsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayConnects...) + } + + return output, nil +} + +func findTransitGatewayConnectByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayConnect, error) { + input := &ec2.DescribeTransitGatewayConnectsInput{ + TransitGatewayAttachmentIds: []string{id}, + } + + output, err := findTransitGatewayConnect(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayAttachmentStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayConnectPeer(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectPeersInput) (*awstypes.TransitGatewayConnectPeer, error) { + output, err := findTransitGatewayConnectPeers(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, + func(v *awstypes.TransitGatewayConnectPeer) bool { return v.ConnectPeerConfiguration != nil }, + func(v *awstypes.TransitGatewayConnectPeer) bool { + return len(v.ConnectPeerConfiguration.BgpConfigurations) > 0 + }, + ) +} + +func findTransitGatewayConnectPeers(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectPeersInput) ([]awstypes.TransitGatewayConnectPeer, error) { + var output []awstypes.TransitGatewayConnectPeer + + pages := ec2.NewDescribeTransitGatewayConnectPeersPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayConnectPeerIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayConnectPeers...) + } + + return output, nil +} + +func findTransitGatewayConnectPeerByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayConnectPeer, error) { + input := &ec2.DescribeTransitGatewayConnectPeersInput{ + TransitGatewayConnectPeerIds: []string{id}, + } + + output, err := findTransitGatewayConnectPeer(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayConnectPeerStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayConnectPeerId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayMulticastDomain(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayMulticastDomainsInput) (*awstypes.TransitGatewayMulticastDomain, error) { + output, err := findTransitGatewayMulticastDomains(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayMulticastDomain) bool { return v.Options != nil }) +} + +func findTransitGatewayMulticastDomains(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayMulticastDomainsInput) ([]awstypes.TransitGatewayMulticastDomain, error) { + var output []awstypes.TransitGatewayMulticastDomain + + pages := ec2.NewDescribeTransitGatewayMulticastDomainsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayMulticastDomainIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayMulticastDomains...) + } + + return output, nil +} + +func findTransitGatewayMulticastDomainByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayMulticastDomain, error) { + input := &ec2.DescribeTransitGatewayMulticastDomainsInput{ + TransitGatewayMulticastDomainIds: []string{id}, + } + + output, err := findTransitGatewayMulticastDomain(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayMulticastDomainStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayMulticastDomainId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayMulticastDomainAssociation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayMulticastDomainAssociationsInput) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { + output, err := findTransitGatewayMulticastDomainAssociations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayMulticastDomainAssociation) bool { return v.Subnet != nil }) +} + +func findTransitGatewayMulticastDomainAssociations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayMulticastDomainAssociationsInput) ([]awstypes.TransitGatewayMulticastDomainAssociation, error) { + var output []awstypes.TransitGatewayMulticastDomainAssociation + + pages := ec2.NewGetTransitGatewayMulticastDomainAssociationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayMulticastDomainIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.MulticastDomainAssociations...) + } + + return output, nil +} + +func findTransitGatewayMulticastDomainAssociationByThreePartKey(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { + input := &ec2.GetTransitGatewayMulticastDomainAssociationsInput{ + Filters: newAttributeFilterList(map[string]string{ + "subnet-id": subnetID, + "transit-gateway-attachment-id": attachmentID, + }), + TransitGatewayMulticastDomainId: aws.String(multicastDomainID), + } + + output, err := findTransitGatewayMulticastDomainAssociation(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.Subnet.State; state == awstypes.TransitGatewayMulitcastDomainAssociationStateDisassociated { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != attachmentID || aws.ToString(output.Subnet.SubnetId) != subnetID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayMulticastGroups(ctx context.Context, conn *ec2.Client, input *ec2.SearchTransitGatewayMulticastGroupsInput) ([]awstypes.TransitGatewayMulticastGroup, error) { + var output []awstypes.TransitGatewayMulticastGroup + + pages := ec2.NewSearchTransitGatewayMulticastGroupsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayMulticastDomainIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.MulticastGroups...) + } + + return output, nil +} + +func findTransitGatewayMulticastGroupMemberByThreePartKey(ctx context.Context, conn *ec2.Client, multicastDomainID, groupIPAddress, eniID string) (*awstypes.TransitGatewayMulticastGroup, error) { + input := &ec2.SearchTransitGatewayMulticastGroupsInput{ + Filters: newAttributeFilterList(map[string]string{ + "group-ip-address": groupIPAddress, + "is-group-member": "true", + "is-group-source": "false", + }), + TransitGatewayMulticastDomainId: aws.String(multicastDomainID), + } + + output, err := findTransitGatewayMulticastGroups(ctx, conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + for _, v := range output { + if aws.ToString(v.NetworkInterfaceId) == eniID { + // Eventual consistency check. + if aws.ToString(v.GroupIpAddress) != groupIPAddress || !aws.ToBool(v.GroupMember) { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return &v, nil + } + } + + return nil, tfresource.NewEmptyResultError(input) +} + +func findTransitGatewayMulticastGroupSourceByThreePartKey(ctx context.Context, conn *ec2.Client, multicastDomainID, groupIPAddress, eniID string) (*awstypes.TransitGatewayMulticastGroup, error) { + input := &ec2.SearchTransitGatewayMulticastGroupsInput{ + Filters: newAttributeFilterList(map[string]string{ + "group-ip-address": groupIPAddress, + "is-group-member": "false", + "is-group-source": "true", + }), + TransitGatewayMulticastDomainId: aws.String(multicastDomainID), + } + + output, err := findTransitGatewayMulticastGroups(ctx, conn, input) + + if err != nil { + return nil, err + } + + if len(output) == 0 { + return nil, tfresource.NewEmptyResultError(input) + } + + for _, v := range output { + if aws.ToString(v.NetworkInterfaceId) == eniID { + // Eventual consistency check. + if aws.ToString(v.GroupIpAddress) != groupIPAddress || !aws.ToBool(v.GroupSource) { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return &v, nil + } + } + + return nil, tfresource.NewEmptyResultError(input) +} + +func findTransitGatewayPeeringAttachment(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPeeringAttachmentsInput) (*awstypes.TransitGatewayPeeringAttachment, error) { + output, err := findTransitGatewayPeeringAttachments(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, + func(v *awstypes.TransitGatewayPeeringAttachment) bool { return v.AccepterTgwInfo != nil }, + func(v *awstypes.TransitGatewayPeeringAttachment) bool { return v.RequesterTgwInfo != nil }, + ) +} + +func findTransitGatewayPeeringAttachments(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPeeringAttachmentsInput) ([]awstypes.TransitGatewayPeeringAttachment, error) { + var output []awstypes.TransitGatewayPeeringAttachment + + pages := ec2.NewDescribeTransitGatewayPeeringAttachmentsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayPeeringAttachments...) + } + + return output, nil +} + +func findTransitGatewayPeeringAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPeeringAttachment, error) { + input := &ec2.DescribeTransitGatewayPeeringAttachmentsInput{ + TransitGatewayAttachmentIds: []string{id}, + } + + output, err := findTransitGatewayPeeringAttachment(ctx, conn, input) + + if err != nil { + return nil, err + } + + // See https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#vpc-attachment-lifecycle. + switch state := output.State; state { + case awstypes.TransitGatewayAttachmentStateDeleted, + awstypes.TransitGatewayAttachmentStateFailed, + awstypes.TransitGatewayAttachmentStateRejected: + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayPrefixListReference(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPrefixListReferencesInput) (*awstypes.TransitGatewayPrefixListReference, error) { + output, err := findTransitGatewayPrefixListReferences(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayPrefixListReferences(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPrefixListReferencesInput) ([]awstypes.TransitGatewayPrefixListReference, error) { + var output []awstypes.TransitGatewayPrefixListReference + + pages := ec2.NewGetTransitGatewayPrefixListReferencesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayPrefixListReferences...) + } + + return output, nil +} + +func findTransitGatewayPrefixListReferenceByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { + input := &ec2.GetTransitGatewayPrefixListReferencesInput{ + Filters: newAttributeFilterList(map[string]string{ + "prefix-list-id": prefixListID, + }), + TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), + } + + output, err := findTransitGatewayPrefixListReference(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.PrefixListId) != prefixListID || aws.ToString(output.TransitGatewayRouteTableId) != transitGatewayRouteTableID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayStaticRoute(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) (*awstypes.TransitGatewayRoute, error) { + input := &ec2.SearchTransitGatewayRoutesInput{ + Filters: newAttributeFilterList(map[string]string{ + names.AttrType: string(awstypes.TransitGatewayRouteTypeStatic), + "route-search.exact-match": destination, + }), + TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), + } + + output, err := findTransitGatewayRoutes(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, route := range output { + if v := aws.ToString(route.DestinationCidrBlock); types.CIDRBlocksEqual(v, destination) { + if state := route.State; state == awstypes.TransitGatewayRouteStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + route.DestinationCidrBlock = aws.String(types.CanonicalCIDRBlock(v)) + + return &route, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findTransitGatewayRoutes(ctx context.Context, conn *ec2.Client, input *ec2.SearchTransitGatewayRoutesInput) ([]awstypes.TransitGatewayRoute, error) { + output, err := conn.SearchTransitGatewayRoutes(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Routes, err +} + +func findTransitGatewayPolicyTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPolicyTablesInput) (*awstypes.TransitGatewayPolicyTable, error) { + output, err := findTransitGatewayPolicyTables(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayRouteTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayRouteTablesInput) (*awstypes.TransitGatewayRouteTable, error) { + output, err := findTransitGatewayRouteTables(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayPolicyTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPolicyTablesInput) ([]awstypes.TransitGatewayPolicyTable, error) { + var output []awstypes.TransitGatewayPolicyTable + + pages := ec2.NewDescribeTransitGatewayPolicyTablesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayPolicyTableIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayPolicyTables...) + } + + return output, nil +} + +func findTransitGatewayRouteTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayRouteTablesInput) ([]awstypes.TransitGatewayRouteTable, error) { + var output []awstypes.TransitGatewayRouteTable + + pages := ec2.NewDescribeTransitGatewayRouteTablesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayRouteTables...) + } + + return output, nil +} + +func findTransitGatewayPolicyTableByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPolicyTable, error) { + input := &ec2.DescribeTransitGatewayPolicyTablesInput{ + TransitGatewayPolicyTableIds: []string{id}, + } + + output, err := findTransitGatewayPolicyTable(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayPolicyTableId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayRouteTableByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayRouteTable, error) { + input := &ec2.DescribeTransitGatewayRouteTablesInput{ + TransitGatewayRouteTableIds: []string{id}, + } + + output, err := findTransitGatewayRouteTable(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayRouteTableStateDeleted { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayRouteTableId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findTransitGatewayPolicyTableAssociationByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayPolicyTableAssociation, error) { + input := &ec2.GetTransitGatewayPolicyTableAssociationsInput{ + Filters: newAttributeFilterList(map[string]string{ + "transit-gateway-attachment-id": transitGatewayAttachmentID, + }), + TransitGatewayPolicyTableId: aws.String(transitGatewayPolicyTableID), + } + + output, err := findTransitGatewayPolicyTableAssociation(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayAssociationStateDisassociated { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != transitGatewayAttachmentID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, err +} + +func findTransitGatewayRouteTableAssociationByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayRouteTableAssociation, error) { + input := &ec2.GetTransitGatewayRouteTableAssociationsInput{ + Filters: newAttributeFilterList(map[string]string{ + "transit-gateway-attachment-id": transitGatewayAttachmentID, + }), + TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), + } + + output, err := findTransitGatewayRouteTableAssociation(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayAssociationStateDisassociated { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != transitGatewayAttachmentID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, err +} + +func findTransitGatewayRouteTableAssociation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTableAssociationsInput) (*awstypes.TransitGatewayRouteTableAssociation, error) { + output, err := findTransitGatewayRouteTableAssociations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayPolicyTableAssociations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPolicyTableAssociationsInput) ([]awstypes.TransitGatewayPolicyTableAssociation, error) { + var output []awstypes.TransitGatewayPolicyTableAssociation + + pages := ec2.NewGetTransitGatewayPolicyTableAssociationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayPolicyTableIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Associations...) + } + + return output, nil +} + +func findTransitGatewayPolicyTableAssociation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPolicyTableAssociationsInput) (*awstypes.TransitGatewayPolicyTableAssociation, error) { + output, err := findTransitGatewayPolicyTableAssociations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayRouteTableAssociations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTableAssociationsInput) ([]awstypes.TransitGatewayRouteTableAssociation, error) { + var output []awstypes.TransitGatewayRouteTableAssociation + + pages := ec2.NewGetTransitGatewayRouteTableAssociationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.Associations...) + } + + return output, nil +} + +func findTransitGatewayRouteTablePropagationByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) (*awstypes.TransitGatewayRouteTablePropagation, error) { + input := &ec2.GetTransitGatewayRouteTablePropagationsInput{ + Filters: newAttributeFilterList(map[string]string{ + "transit-gateway-attachment-id": transitGatewayAttachmentID, + }), + TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), + } + + output, err := findTransitGatewayRouteTablePropagation(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.TransitGatewayPropagationStateDisabled { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != transitGatewayAttachmentID { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, err +} + +func findTransitGatewayRouteTablePropagation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTablePropagationsInput) (*awstypes.TransitGatewayRouteTablePropagation, error) { + output, err := findTransitGatewayRouteTablePropagations(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findTransitGatewayRouteTablePropagations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTablePropagationsInput) ([]awstypes.TransitGatewayRouteTablePropagation, error) { + var output []awstypes.TransitGatewayRouteTablePropagation + + pages := ec2.NewGetTransitGatewayRouteTablePropagationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayRouteTablePropagations...) + } + + return output, nil +} + +func findTransitGatewayVPCAttachment(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayVpcAttachmentsInput) (*awstypes.TransitGatewayVpcAttachment, error) { + output, err := findTransitGatewayVPCAttachments(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayVpcAttachment) bool { return v.Options != nil }) +} + +func findTransitGatewayVPCAttachments(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayVpcAttachmentsInput) ([]awstypes.TransitGatewayVpcAttachment, error) { + var output []awstypes.TransitGatewayVpcAttachment + + pages := ec2.NewDescribeTransitGatewayVpcAttachmentsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.TransitGatewayVpcAttachments...) + } + + return output, nil +} + +func findTransitGatewayVPCAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { + input := &ec2.DescribeTransitGatewayVpcAttachmentsInput{ + TransitGatewayAttachmentIds: []string{id}, + } + + output, err := findTransitGatewayVPCAttachment(ctx, conn, input) + + if err != nil { + return nil, err + } + + // See https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#vpc-attachment-lifecycle. + switch state := output.State; state { + case awstypes.TransitGatewayAttachmentStateDeleted, + awstypes.TransitGatewayAttachmentStateFailed, + awstypes.TransitGatewayAttachmentStateRejected: + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.TransitGatewayAttachmentId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findEIPs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesInput) ([]awstypes.Address, error) { + output, err := conn.DescribeAddresses(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidAddressNotFound, errCodeInvalidAllocationIDNotFound) || + tfawserr.ErrMessageContains(err, errCodeAuthFailure, "does not belong to you") { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output.Addresses, nil +} + +func findEIP(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesInput) (*awstypes.Address, error) { + output, err := findEIPs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findEIPByAllocationID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Address, error) { + input := &ec2.DescribeAddressesInput{ + AllocationIds: []string{id}, + } + + output, err := findEIP(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.AllocationId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findEIPByAssociationID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Address, error) { + input := &ec2.DescribeAddressesInput{ + Filters: newAttributeFilterList(map[string]string{ + "association-id": id, + }), + } + + output, err := findEIP(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.AssociationId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findEIPAttributes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesAttributeInput) ([]awstypes.AddressAttribute, error) { + var output []awstypes.AddressAttribute + + pages := ec2.NewDescribeAddressesAttributePaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.Addresses...) + } + + return output, nil +} + +func findEIPAttribute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesAttributeInput) (*awstypes.AddressAttribute, error) { + output, err := findEIPAttributes(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findEIPDomainNameAttributeByAllocationID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.AddressAttribute, error) { + input := &ec2.DescribeAddressesAttributeInput{ + AllocationIds: []string{id}, + Attribute: awstypes.AddressAttributeNameDomainName, + } + + output, err := findEIPAttribute(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.AllocationId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findKeyPair(ctx context.Context, conn *ec2.Client, input *ec2.DescribeKeyPairsInput) (*awstypes.KeyPairInfo, error) { + output, err := findKeyPairs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findKeyPairs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeKeyPairsInput) ([]awstypes.KeyPairInfo, error) { + output, err := conn.DescribeKeyPairs(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidKeyPairNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + return output.KeyPairs, nil +} + +func findKeyPairByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.KeyPairInfo, error) { + input := &ec2.DescribeKeyPairsInput{ + KeyNames: []string{name}, + } + + output, err := findKeyPair(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.KeyName) != name { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findImportSnapshotTasks(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImportSnapshotTasksInput) ([]awstypes.ImportSnapshotTask, error) { + var output []awstypes.ImportSnapshotTask + + pages := ec2.NewDescribeImportSnapshotTasksPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidConversionTaskIdMalformed, "not found") { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.ImportSnapshotTasks...) + } + + return output, nil +} + +func findImportSnapshotTask(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImportSnapshotTasksInput) (*awstypes.ImportSnapshotTask, error) { + output, err := findImportSnapshotTasks(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output, func(v *awstypes.ImportSnapshotTask) bool { return v.SnapshotTaskDetail != nil }) +} + +func findImportSnapshotTaskByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ImportSnapshotTask, error) { + input := &ec2.DescribeImportSnapshotTasksInput{ + ImportTaskIds: []string{id}, + } + + output, err := findImportSnapshotTask(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.ImportTaskId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSnapshots(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotsInput) ([]awstypes.Snapshot, error) { + var output []awstypes.Snapshot + + pages := ec2.NewDescribeSnapshotsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + if tfawserr.ErrCodeEquals(err, errCodeInvalidSnapshotNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + return nil, err + } + + output = append(output, page.Snapshots...) + } + + return output, nil +} + +func findSnapshot(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotsInput) (*awstypes.Snapshot, error) { + output, err := findSnapshots(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSnapshotByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Snapshot, error) { + input := &ec2.DescribeSnapshotsInput{ + SnapshotIds: []string{id}, + } + + output, err := findSnapshot(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.SnapshotId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findSnapshotAttribute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotAttributeInput) (*ec2.DescribeSnapshotAttributeOutput, error) { + output, err := conn.DescribeSnapshotAttribute(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidSnapshotNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +func findCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx context.Context, conn *ec2.Client, snapshotID, accountID string) (awstypes.CreateVolumePermission, error) { + input := &ec2.DescribeSnapshotAttributeInput{ + Attribute: awstypes.SnapshotAttributeNameCreateVolumePermission, + SnapshotId: aws.String(snapshotID), + } + + output, err := findSnapshotAttribute(ctx, conn, input) + + if err != nil { + return awstypes.CreateVolumePermission{}, err + } + + for _, v := range output.CreateVolumePermissions { + if aws.ToString(v.UserId) == accountID { + return v, nil + } + } + + return awstypes.CreateVolumePermission{}, &retry.NotFoundError{LastRequest: input} +} + +func findFindSnapshotTierStatuses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotTierStatusInput) ([]awstypes.SnapshotTierStatus, error) { + var output []awstypes.SnapshotTierStatus + + pages := ec2.NewDescribeSnapshotTierStatusPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.SnapshotTierStatuses...) + } + + return output, nil +} + +func findFindSnapshotTierStatus(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotTierStatusInput) (*awstypes.SnapshotTierStatus, error) { + output, err := findFindSnapshotTierStatuses(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findFlowLogByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.FlowLog, error) { + input := &ec2.DescribeFlowLogsInput{ + FlowLogIds: []string{id}, + } + + output, err := findFlowLog(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.FlowLogId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findFlowLogs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFlowLogsInput) ([]awstypes.FlowLog, error) { + var output []awstypes.FlowLog + + pages := ec2.NewDescribeFlowLogsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.FlowLogs...) + } + + return output, nil +} + +func findFlowLog(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFlowLogsInput) (*awstypes.FlowLog, error) { + output, err := findFlowLogs(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findSnapshotTierStatusBySnapshotID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SnapshotTierStatus, error) { + input := &ec2.DescribeSnapshotTierStatusInput{ + Filters: newAttributeFilterList(map[string]string{ + "snapshot-id": id, + }), + } + + output, err := findFindSnapshotTierStatus(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.SnapshotId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findNetworkPerformanceMetricSubscriptions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAwsNetworkPerformanceMetricSubscriptionsInput) ([]awstypes.Subscription, error) { + var output []awstypes.Subscription + + pages := ec2.NewDescribeAwsNetworkPerformanceMetricSubscriptionsPaginator(conn, input, func(o *ec2.DescribeAwsNetworkPerformanceMetricSubscriptionsPaginatorOptions) { + o.Limit = 100 + }) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if err != nil { + return nil, err + } + + output = append(output, page.Subscriptions...) + } + + return output, nil +} + +func findNetworkPerformanceMetricSubscriptionByFourPartKey(ctx context.Context, conn *ec2.Client, source, destination, metric, statistic string) (*awstypes.Subscription, error) { + input := &ec2.DescribeAwsNetworkPerformanceMetricSubscriptionsInput{} + + output, err := findNetworkPerformanceMetricSubscriptions(ctx, conn, input) + + if err != nil { + return nil, err + } + + for _, v := range output { + if aws.ToString(v.Source) == source && aws.ToString(v.Destination) == destination && string(v.Metric) == metric && string(v.Statistic) == statistic { + return &v, nil + } + } + + return nil, &retry.NotFoundError{} +} + +func findInstanceConnectEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceConnectEndpointsInput) (*awstypes.Ec2InstanceConnectEndpoint, error) { + output, err := findInstanceConnectEndpoints(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findInstanceConnectEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceConnectEndpointsInput) ([]awstypes.Ec2InstanceConnectEndpoint, error) { + var output []awstypes.Ec2InstanceConnectEndpoint + + pages := ec2.NewDescribeInstanceConnectEndpointsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceConnectEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.InstanceConnectEndpoints...) + } + + return output, nil +} + +func findInstanceConnectEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Ec2InstanceConnectEndpoint, error) { + input := &ec2.DescribeInstanceConnectEndpointsInput{ + InstanceConnectEndpointIds: []string{id}, + } + output, err := findInstanceConnectEndpoint(ctx, conn, input) + + if err != nil { + return nil, err + } + + if state := output.State; state == awstypes.Ec2InstanceConnectEndpointStateDeleteComplete { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + // Eventual consistency check. + if aws.ToString(output.InstanceConnectEndpointId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVerifiedAccessGroupPolicyByID(ctx context.Context, conn *ec2.Client, id string) (*ec2.GetVerifiedAccessGroupPolicyOutput, error) { + input := &ec2.GetVerifiedAccessGroupPolicyInput{ + VerifiedAccessGroupId: &id, + } + output, err := conn.GetVerifiedAccessGroupPolicy(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessGroupIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +func findVerifiedAccessEndpointPolicyByID(ctx context.Context, conn *ec2.Client, id string) (*ec2.GetVerifiedAccessEndpointPolicyOutput, error) { + input := &ec2.GetVerifiedAccessEndpointPolicyInput{ + VerifiedAccessEndpointId: &id, + } + output, err := conn.GetVerifiedAccessEndpointPolicy(ctx, input) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + if output == nil { + return nil, tfresource.NewEmptyResultError(input) + } + + return output, nil +} + +func findVerifiedAccessGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessGroupsInput) (*awstypes.VerifiedAccessGroup, error) { + output, err := findVerifiedAccessGroups(ctx, conn, input) + + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findVerifiedAccessGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessGroupsInput) ([]awstypes.VerifiedAccessGroup, error) { + var output []awstypes.VerifiedAccessGroup + + pages := ec2.NewDescribeVerifiedAccessGroupsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessGroupIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err + } + + output = append(output, page.VerifiedAccessGroups...) + } + + return output, nil +} + +func findVerifiedAccessGroupByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessGroup, error) { + input := &ec2.DescribeVerifiedAccessGroupsInput{ + VerifiedAccessGroupIds: []string{id}, + } + output, err := findVerifiedAccessGroup(ctx, conn, input) + + if err != nil { + return nil, err + } + + // Eventual consistency check. + if aws.ToString(output.VerifiedAccessGroupId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } + } + + return output, nil +} + +func findVerifiedAccessInstance(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstancesInput) (*awstypes.VerifiedAccessInstance, error) { + output, err := findVerifiedAccessInstances(ctx, conn, input) if err != nil { - return nil, nil, err + return nil, err } - for _, association := range vpc.Ipv6CidrBlockAssociationSet { - if aws.StringValue(association.AssociationId) == id { - if state := aws.StringValue(association.Ipv6CidrBlockState.State); state == ec2.VpcCidrBlockStateCodeDisassociated { - return nil, nil, &retry.NotFoundError{Message: state} + return tfresource.AssertSingleValueResult(output) +} + +func findVerifiedAccessInstances(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstancesInput) ([]awstypes.VerifiedAccessInstance, error) { + var output []awstypes.VerifiedAccessInstance + + pages := ec2.NewDescribeVerifiedAccessInstancesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessInstanceIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } + } - return association, vpc, nil + if err != nil { + return nil, err } + + output = append(output, page.VerifiedAccessInstances...) } - return nil, nil, &retry.NotFoundError{} + return output, nil } -func FindVPCDefaultNetworkACL(ctx context.Context, conn *ec2.EC2, id string) (*ec2.NetworkAcl, error) { - input := &ec2.DescribeNetworkAclsInput{ - Filters: newAttributeFilterList(map[string]string{ - "default": "true", - "vpc-id": id, - }), +func findVerifiedAccessInstanceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessInstance, error) { + input := &ec2.DescribeVerifiedAccessInstancesInput{ + VerifiedAccessInstanceIds: []string{id}, } + output, err := findVerifiedAccessInstance(ctx, conn, input) - return FindNetworkACL(ctx, conn, input) -} + if err != nil { + return nil, err + } -func FindVPCDefaultSecurityGroup(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SecurityGroup, error) { - input := &ec2.DescribeSecurityGroupsInput{ - Filters: newAttributeFilterList(map[string]string{ - "group-name": DefaultSecurityGroupName, - "vpc-id": id, - }), + // Eventual consistency check. + if aws.ToString(output.VerifiedAccessInstanceId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, + } } - return FindSecurityGroup(ctx, conn, input) + return output, nil } -func FindVPCPeeringConnection(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeVpcPeeringConnectionsInput) (*ec2.VpcPeeringConnection, error) { - output, err := FindVPCPeeringConnections(ctx, conn, input) +func findVerifiedAccessInstanceLoggingConfiguration(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstanceLoggingConfigurationsInput) (*awstypes.VerifiedAccessInstanceLoggingConfiguration, error) { + output, err := findVerifiedAccessInstanceLoggingConfigurations(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output, func(v *ec2.VpcPeeringConnection) bool { return v.Status != nil }) + return tfresource.AssertSingleValueResult(output) } -func FindVPCPeeringConnections(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeVpcPeeringConnectionsInput) ([]*ec2.VpcPeeringConnection, error) { - var output []*ec2.VpcPeeringConnection +func findVerifiedAccessInstanceLoggingConfigurations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstanceLoggingConfigurationsInput) ([]awstypes.VerifiedAccessInstanceLoggingConfiguration, error) { + var output []awstypes.VerifiedAccessInstanceLoggingConfiguration - err := conn.DescribeVpcPeeringConnectionsPagesWithContext(ctx, input, func(page *ec2.DescribeVpcPeeringConnectionsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeVerifiedAccessInstanceLoggingConfigurationsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.VpcPeeringConnections { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessInstanceIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCPeeringConnectionIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.LoggingConfigurations...) } return output, nil } -func FindVPCPeeringConnectionByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.VpcPeeringConnection, error) { - input := &ec2.DescribeVpcPeeringConnectionsInput{ - VpcPeeringConnectionIds: aws.StringSlice([]string{id}), +func findVerifiedAccessInstanceLoggingConfigurationByInstanceID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessInstanceLoggingConfiguration, error) { + input := &ec2.DescribeVerifiedAccessInstanceLoggingConfigurationsInput{ + VerifiedAccessInstanceIds: []string{id}, } - - output, err := FindVPCPeeringConnection(ctx, conn, input) + output, err := findVerifiedAccessInstanceLoggingConfiguration(ctx, conn, input) if err != nil { return nil, err } - // See https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html#vpc-peering-lifecycle. - switch statusCode := aws.StringValue(output.Status.Code); statusCode { - case ec2.VpcPeeringConnectionStateReasonCodeDeleted, - ec2.VpcPeeringConnectionStateReasonCodeExpired, - ec2.VpcPeeringConnectionStateReasonCodeFailed, - ec2.VpcPeeringConnectionStateReasonCodeRejected: + // Eventual consistency check. + if aws.ToString(output.VerifiedAccessInstanceId) != id { return nil, &retry.NotFoundError{ - Message: statusCode, LastRequest: input, } } - // Eventual consistency check. - if aws.StringValue(output.VpcPeeringConnectionId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, + return output, nil +} + +func findVerifiedAccessInstanceTrustProviderAttachmentExists(ctx context.Context, conn *ec2.Client, vaiID, vatpID string) error { + output, err := findVerifiedAccessInstanceByID(ctx, conn, vaiID) + + if err != nil { + return err + } + + for _, v := range output.VerifiedAccessTrustProviders { + if aws.ToString(v.VerifiedAccessTrustProviderId) == vatpID { + return nil } } - return output, nil + return &retry.NotFoundError{ + LastError: fmt.Errorf("Verified Access Instance (%s) Trust Provider (%s) Attachment not found", vaiID, vatpID), + } } -func FindDHCPOptions(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeDhcpOptionsInput) (*ec2.DhcpOptions, error) { - output, err := FindDHCPOptionses(ctx, conn, input) +func findVerifiedAccessTrustProvider(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessTrustProvidersInput) (*awstypes.VerifiedAccessTrustProvider, error) { + output, err := findVerifiedAccessTrustProviders(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindDHCPOptionses(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeDhcpOptionsInput) ([]*ec2.DhcpOptions, error) { - var output []*ec2.DhcpOptions +func findVerifiedAccessTrustProviders(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessTrustProvidersInput) ([]awstypes.VerifiedAccessTrustProvider, error) { + var output []awstypes.VerifiedAccessTrustProvider - err := conn.DescribeDhcpOptionsPagesWithContext(ctx, input, func(page *ec2.DescribeDhcpOptionsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeVerifiedAccessTrustProvidersPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.DhcpOptions { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidDHCPOptionIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.VerifiedAccessTrustProviders...) } return output, nil } -func FindDHCPOptionsByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.DhcpOptions, error) { - input := &ec2.DescribeDhcpOptionsInput{ - DhcpOptionsIds: aws.StringSlice([]string{id}), +func findVerifiedAccessTrustProviderByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessTrustProvider, error) { + input := &ec2.DescribeVerifiedAccessTrustProvidersInput{ + VerifiedAccessTrustProviderIds: []string{id}, } - - output, err := FindDHCPOptions(ctx, conn, input) + output, err := findVerifiedAccessTrustProvider(ctx, conn, input) if err != nil { return nil, err } // Eventual consistency check. - if aws.StringValue(output.DhcpOptionsId) != id { + if aws.ToString(output.VerifiedAccessTrustProviderId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -877,53 +6121,59 @@ func FindDHCPOptionsByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.Dh return output, nil } -func FindEgressOnlyInternetGateway(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeEgressOnlyInternetGatewaysInput) (*ec2.EgressOnlyInternetGateway, error) { - output, err := FindEgressOnlyInternetGateways(ctx, conn, input) +func findVerifiedAccessEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessEndpointsInput) (*awstypes.VerifiedAccessEndpoint, error) { + output, err := findVerifiedAccessEndpoints(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindEgressOnlyInternetGateways(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeEgressOnlyInternetGatewaysInput) ([]*ec2.EgressOnlyInternetGateway, error) { - var output []*ec2.EgressOnlyInternetGateway +func findVerifiedAccessEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessEndpointsInput) ([]awstypes.VerifiedAccessEndpoint, error) { + var output []awstypes.VerifiedAccessEndpoint - err := conn.DescribeEgressOnlyInternetGatewaysPagesWithContext(ctx, input, func(page *ec2.DescribeEgressOnlyInternetGatewaysOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeVerifiedAccessEndpointsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.EgressOnlyInternetGateways { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessEndpointIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) + if err != nil { + return nil, err + } - if err != nil { - return nil, err + output = append(output, page.VerifiedAccessEndpoints...) } return output, nil } -func FindEgressOnlyInternetGatewayByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.EgressOnlyInternetGateway, error) { - input := &ec2.DescribeEgressOnlyInternetGatewaysInput{ - EgressOnlyInternetGatewayIds: aws.StringSlice([]string{id}), +func findVerifiedAccessEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessEndpoint, error) { + input := &ec2.DescribeVerifiedAccessEndpointsInput{ + VerifiedAccessEndpointIds: []string{id}, } - - output, err := FindEgressOnlyInternetGateway(ctx, conn, input) + output, err := findVerifiedAccessEndpoint(ctx, conn, input) if err != nil { return nil, err } + if status := output.Status; status != nil && status.Code == awstypes.VerifiedAccessEndpointStatusCodeDeleted { + return nil, &retry.NotFoundError{ + Message: string(status.Code), + LastRequest: input, + } + } + // Eventual consistency check. - if aws.StringValue(output.EgressOnlyInternetGatewayId) != id { + if aws.ToString(output.VerifiedAccessEndpointId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -932,115 +6182,104 @@ func FindEgressOnlyInternetGatewayByID(ctx context.Context, conn *ec2.EC2, id st return output, nil } -func FindFlowLogByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.FlowLog, error) { - input := &ec2.DescribeFlowLogsInput{ - FlowLogIds: aws.StringSlice([]string{id}), - } - - output, err := FindFlowLog(ctx, conn, input) +func findFastSnapshotRestore(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFastSnapshotRestoresInput) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { + output, err := findFastSnapshotRestores(ctx, conn, input) if err != nil { return nil, err } - // Eventual consistency check. - if aws.StringValue(output.FlowLogId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil + return tfresource.AssertSingleValueResult(output) } -func FindFlowLogs(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeFlowLogsInput) ([]*ec2.FlowLog, error) { - var output []*ec2.FlowLog +func findFastSnapshotRestores(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFastSnapshotRestoresInput) ([]awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { + var output []awstypes.DescribeFastSnapshotRestoreSuccessItem - err := conn.DescribeFlowLogsPagesWithContext(ctx, input, func(page *ec2.DescribeFlowLogsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeFastSnapshotRestoresPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.FlowLogs { - if v != nil { - output = append(output, v) - } + if err != nil { + return nil, err } - return !lastPage - }) - - if err != nil { - return nil, err + output = append(output, page.FastSnapshotRestores...) } return output, nil } -func FindFlowLog(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeFlowLogsInput) (*ec2.FlowLog, error) { - output, err := FindFlowLogs(ctx, conn, input) +func findFastSnapshotRestoreByTwoPartKey(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { + input := &ec2.DescribeFastSnapshotRestoresInput{ + Filters: newAttributeFilterList(map[string]string{ + "availability-zone": availabilityZone, + "snapshot-id": snapshotID, + }), + } + + output, err := findFastSnapshotRestore(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + if state := output.State; state == awstypes.FastSnapshotRestoreStateCodeDisabled { + return nil, &retry.NotFoundError{ + Message: string(state), + LastRequest: input, + } + } + + return output, nil } -func FindInternetGateway(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeInternetGatewaysInput) (*ec2.InternetGateway, error) { - output, err := FindInternetGateways(ctx, conn, input) +func findTrafficMirrorFilter(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorFiltersInput) (*awstypes.TrafficMirrorFilter, error) { + output, err := findTrafficMirrorFilters(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindInternetGateways(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeInternetGatewaysInput) ([]*ec2.InternetGateway, error) { - var output []*ec2.InternetGateway +func findTrafficMirrorFilters(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorFiltersInput) ([]awstypes.TrafficMirrorFilter, error) { + var output []awstypes.TrafficMirrorFilter - err := conn.DescribeInternetGatewaysPagesWithContext(ctx, input, func(page *ec2.DescribeInternetGatewaysOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeTrafficMirrorFiltersPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.InternetGateways { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidTrafficMirrorFilterIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidInternetGatewayIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.TrafficMirrorFilters...) } return output, nil } -func FindInternetGatewayByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.InternetGateway, error) { - input := &ec2.DescribeInternetGatewaysInput{ - InternetGatewayIds: aws.StringSlice([]string{id}), +func findTrafficMirrorFilterByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TrafficMirrorFilter, error) { + input := &ec2.DescribeTrafficMirrorFiltersInput{ + TrafficMirrorFilterIds: []string{id}, } - output, err := FindInternetGateway(ctx, conn, input) + output, err := findTrafficMirrorFilter(ctx, conn, input) if err != nil { return nil, err } // Eventual consistency check. - if aws.StringValue(output.InternetGatewayId) != id { + if aws.ToString(output.TrafficMirrorFilterId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -1049,91 +6288,65 @@ func FindInternetGatewayByID(ctx context.Context, conn *ec2.EC2, id string) (*ec return output, nil } -func FindInternetGatewayAttachment(ctx context.Context, conn *ec2.EC2, internetGatewayID, vpcID string) (*ec2.InternetGatewayAttachment, error) { - internetGateway, err := FindInternetGatewayByID(ctx, conn, internetGatewayID) +func findTrafficMirrorFilterRuleByTwoPartKey(ctx context.Context, conn *ec2.Client, filterID, ruleID string) (*awstypes.TrafficMirrorFilterRule, error) { + output, err := findTrafficMirrorFilterByID(ctx, conn, filterID) if err != nil { return nil, err } - if len(internetGateway.Attachments) == 0 || internetGateway.Attachments[0] == nil { - return nil, tfresource.NewEmptyResultError(internetGatewayID) - } - - if count := len(internetGateway.Attachments); count > 1 { - return nil, tfresource.NewTooManyResultsError(count, internetGatewayID) - } - - attachment := internetGateway.Attachments[0] - - if aws.StringValue(attachment.VpcId) != vpcID { - return nil, tfresource.NewEmptyResultError(vpcID) - } - - return attachment, nil + return tfresource.AssertSingleValueResult(tfslices.Filter(slices.Concat(output.IngressFilterRules, output.EgressFilterRules), func(v awstypes.TrafficMirrorFilterRule) bool { + return aws.ToString(v.TrafficMirrorFilterRuleId) == ruleID + })) } -func FindManagedPrefixList(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeManagedPrefixListsInput) (*ec2.ManagedPrefixList, error) { - output, err := FindManagedPrefixLists(ctx, conn, input) +func findTrafficMirrorSession(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorSessionsInput) (*awstypes.TrafficMirrorSession, error) { + output, err := findTrafficMirrorSessions(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindManagedPrefixLists(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeManagedPrefixListsInput) ([]*ec2.ManagedPrefixList, error) { - var output []*ec2.ManagedPrefixList +func findTrafficMirrorSessions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorSessionsInput) ([]awstypes.TrafficMirrorSession, error) { + var output []awstypes.TrafficMirrorSession - err := conn.DescribeManagedPrefixListsPagesWithContext(ctx, input, func(page *ec2.DescribeManagedPrefixListsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeTrafficMirrorSessionsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.PrefixLists { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidTrafficMirrorSessionIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.TrafficMirrorSessions...) } return output, nil } -func FindManagedPrefixListByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.ManagedPrefixList, error) { - input := &ec2.DescribeManagedPrefixListsInput{ - PrefixListIds: aws.StringSlice([]string{id}), +func findTrafficMirrorSessionByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TrafficMirrorSession, error) { + input := &ec2.DescribeTrafficMirrorSessionsInput{ + TrafficMirrorSessionIds: []string{id}, } - output, err := FindManagedPrefixList(ctx, conn, input) + output, err := findTrafficMirrorSession(ctx, conn, input) if err != nil { return nil, err } - if state := aws.StringValue(output.State); state == ec2.PrefixListStateDeleteComplete { - return nil, &retry.NotFoundError{ - Message: state, - LastRequest: input, - } - } - // Eventual consistency check. - if aws.StringValue(output.PrefixListId) != id { + if aws.ToString(output.TrafficMirrorSessionId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -1142,122 +6355,118 @@ func FindManagedPrefixListByID(ctx context.Context, conn *ec2.EC2, id string) (* return output, nil } -func FindManagedPrefixListEntries(ctx context.Context, conn *ec2.EC2, input *ec2.GetManagedPrefixListEntriesInput) ([]*ec2.PrefixListEntry, error) { - var output []*ec2.PrefixListEntry +func findTrafficMirrorTarget(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorTargetsInput) (*awstypes.TrafficMirrorTarget, error) { + output, err := findTrafficMirrorTargets(ctx, conn, input) - err := conn.GetManagedPrefixListEntriesPagesWithContext(ctx, input, func(page *ec2.GetManagedPrefixListEntriesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} - for _, v := range page.Entries { - if v != nil { - output = append(output, v) +func findTrafficMirrorTargets(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorTargetsInput) ([]awstypes.TrafficMirrorTarget, error) { + var output []awstypes.TrafficMirrorTarget + + pages := ec2.NewDescribeTrafficMirrorTargetsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidTrafficMirrorTargetIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.TrafficMirrorTargets...) } return output, nil } -func FindManagedPrefixListEntriesByID(ctx context.Context, conn *ec2.EC2, id string) ([]*ec2.PrefixListEntry, error) { - input := &ec2.GetManagedPrefixListEntriesInput{ - PrefixListId: aws.String(id), +func findTrafficMirrorTargetByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TrafficMirrorTarget, error) { + input := &ec2.DescribeTrafficMirrorTargetsInput{ + TrafficMirrorTargetIds: []string{id}, } - return FindManagedPrefixListEntries(ctx, conn, input) -} - -func FindManagedPrefixListEntryByIDAndCIDR(ctx context.Context, conn *ec2.EC2, id, cidr string) (*ec2.PrefixListEntry, error) { - prefixListEntries, err := FindManagedPrefixListEntriesByID(ctx, conn, id) + output, err := findTrafficMirrorTarget(ctx, conn, input) if err != nil { return nil, err } - for _, v := range prefixListEntries { - if aws.StringValue(v.Cidr) == cidr { - return v, nil + // Eventual consistency check. + if aws.ToString(output.TrafficMirrorTargetId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, } } - return nil, &retry.NotFoundError{} + return output, nil } -func FindNATGateway(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeNatGatewaysInput) (*ec2.NatGateway, error) { - output, err := FindNATGateways(ctx, conn, input) +func findNetworkInsightsPath(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsPathsInput) (*awstypes.NetworkInsightsPath, error) { + output, err := findNetworkInsightsPaths(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindNATGateways(ctx context.Context, conn *ec2.EC2, input *ec2.DescribeNatGatewaysInput) ([]*ec2.NatGateway, error) { - var output []*ec2.NatGateway +func findNetworkInsightsAnalysis(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsAnalysesInput) (*awstypes.NetworkInsightsAnalysis, error) { + output, err := findNetworkInsightsAnalyses(ctx, conn, input) - err := conn.DescribeNatGatewaysPagesWithContext(ctx, input, func(page *ec2.DescribeNatGatewaysOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + if err != nil { + return nil, err + } + + return tfresource.AssertSingleValueResult(output) +} + +func findNetworkInsightsAnalyses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsAnalysesInput) ([]awstypes.NetworkInsightsAnalysis, error) { + var output []awstypes.NetworkInsightsAnalysis + + pages := ec2.NewDescribeNetworkInsightsAnalysesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.NatGateways { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInsightsAnalysisIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeNatGatewayNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.NetworkInsightsAnalyses...) } return output, nil } -func FindNATGatewayByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.NatGateway, error) { - input := &ec2.DescribeNatGatewaysInput{ - NatGatewayIds: aws.StringSlice([]string{id}), +func findNetworkInsightsAnalysisByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInsightsAnalysis, error) { + input := &ec2.DescribeNetworkInsightsAnalysesInput{ + NetworkInsightsAnalysisIds: []string{id}, } - output, err := FindNATGateway(ctx, conn, input) + output, err := findNetworkInsightsAnalysis(ctx, conn, input) if err != nil { return nil, err } - if state := aws.StringValue(output.State); state == ec2.NatGatewayStateDeleted { - return nil, &retry.NotFoundError{ - Message: state, - LastRequest: input, - } - } - // Eventual consistency check. - if aws.StringValue(output.NatGatewayId) != id { + if aws.ToString(output.NetworkInsightsAnalysisId) != id { return nil, &retry.NotFoundError{ LastRequest: input, } @@ -1266,85 +6475,81 @@ func FindNATGatewayByID(ctx context.Context, conn *ec2.EC2, id string) (*ec2.Nat return output, nil } -func FindNATGatewayAddressByNATGatewayIDAndAllocationID(ctx context.Context, conn *ec2.EC2, natGatewayID, allocationID string) (*ec2.NatGatewayAddress, error) { - output, err := FindNATGatewayByID(ctx, conn, natGatewayID) +func findNetworkInsightsPaths(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsPathsInput) ([]awstypes.NetworkInsightsPath, error) { + var output []awstypes.NetworkInsightsPath - if err != nil { - return nil, err - } + pages := ec2.NewDescribeNetworkInsightsPathsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range output.NatGatewayAddresses { - if aws.StringValue(v.AllocationId) == allocationID { - return v, nil + if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInsightsPathIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, + } + } + + if err != nil { + return nil, err } + + output = append(output, page.NetworkInsightsPaths...) } - return nil, &retry.NotFoundError{} + return output, nil } -func FindNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx context.Context, conn *ec2.EC2, natGatewayID, privateIP string) (*ec2.NatGatewayAddress, error) { - output, err := FindNATGatewayByID(ctx, conn, natGatewayID) +func findNetworkInsightsPathByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInsightsPath, error) { + input := &ec2.DescribeNetworkInsightsPathsInput{ + NetworkInsightsPathIds: []string{id}, + } + + output, err := findNetworkInsightsPath(ctx, conn, input) if err != nil { return nil, err } - for _, v := range output.NatGatewayAddresses { - if aws.StringValue(v.PrivateIp) == privateIP { - return v, nil + // Eventual consistency check. + if aws.ToString(output.NetworkInsightsPathId) != id { + return nil, &retry.NotFoundError{ + LastRequest: input, } } - return nil, &retry.NotFoundError{} + return output, nil } -func FindPrefixList(ctx context.Context, conn *ec2.EC2, input *ec2.DescribePrefixListsInput) (*ec2.PrefixList, error) { - output, err := FindPrefixLists(ctx, conn, input) +func findCapacityBlockOffering(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCapacityBlockOfferingsInput) (*awstypes.CapacityBlockOffering, error) { + output, err := findCapacityBlockOfferings(ctx, conn, input) if err != nil { return nil, err } - return tfresource.AssertSinglePtrResult(output) + return tfresource.AssertSingleValueResult(output) } -func FindPrefixLists(ctx context.Context, conn *ec2.EC2, input *ec2.DescribePrefixListsInput) ([]*ec2.PrefixList, error) { - var output []*ec2.PrefixList +func findCapacityBlockOfferings(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCapacityBlockOfferingsInput) ([]awstypes.CapacityBlockOffering, error) { + var output []awstypes.CapacityBlockOffering - err := conn.DescribePrefixListsPagesWithContext(ctx, input, func(page *ec2.DescribePrefixListsOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } + pages := ec2.NewDescribeCapacityBlockOfferingsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - for _, v := range page.PrefixLists { - if v != nil { - output = append(output, v) + if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInsightsAnalysisIdNotFound) { + return nil, &retry.NotFoundError{ + LastError: err, + LastRequest: input, } } - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, + if err != nil { + return nil, err } - } - if err != nil { - return nil, err + output = append(output, page.CapacityBlockOfferings...) } return output, nil } - -func FindPrefixListByName(ctx context.Context, conn *ec2.EC2, name string) (*ec2.PrefixList, error) { - input := &ec2.DescribePrefixListsInput{ - Filters: newAttributeFilterList(map[string]string{ - "prefix-list-name": name, - }), - } - - return FindPrefixList(ctx, conn, input) -} diff --git a/internal/service/ec2/findv2.go b/internal/service/ec2/findv2.go deleted file mode 100644 index 7588c8c2186..00000000000 --- a/internal/service/ec2/findv2.go +++ /dev/null @@ -1,5636 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package ec2 - -import ( - "context" - "fmt" - "slices" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/ec2" - awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/enum" - tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" - "github.com/hashicorp/terraform-provider-aws/internal/types" - "github.com/hashicorp/terraform-provider-aws/names" -) - -func findAvailabilityZones(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAvailabilityZonesInput) ([]awstypes.AvailabilityZone, error) { - output, err := conn.DescribeAvailabilityZones(ctx, input) - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.AvailabilityZones, nil -} - -func findAvailabilityZone(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAvailabilityZonesInput) (*awstypes.AvailabilityZone, error) { - output, err := findAvailabilityZones(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findAvailabilityZoneGroupByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.AvailabilityZone, error) { - input := &ec2.DescribeAvailabilityZonesInput{ - AllAvailabilityZones: aws.Bool(true), - Filters: newAttributeFilterListV2(map[string]string{ - "group-name": name, - }), - } - - output, err := findAvailabilityZones(ctx, conn, input) - - if err != nil { - return nil, err - } - - if len(output) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - // An AZ group may contain more than one AZ. - availabilityZone := output[0] - - // Eventual consistency check. - if aws.ToString(availabilityZone.GroupName) != name { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return &availabilityZone, nil -} - -func findCapacityReservation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCapacityReservationsInput) (*awstypes.CapacityReservation, error) { - output, err := findCapacityReservations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findCapacityReservations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCapacityReservationsInput) ([]awstypes.CapacityReservation, error) { - var output []awstypes.CapacityReservation - - pages := ec2.NewDescribeCapacityReservationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidCapacityReservationIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.CapacityReservations...) - } - - return output, nil -} - -func findCapacityReservationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CapacityReservation, error) { - input := &ec2.DescribeCapacityReservationsInput{ - CapacityReservationIds: []string{id}, - } - - output, err := findCapacityReservation(ctx, conn, input) - - if err != nil { - return nil, err - } - - // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#capacity-reservations-view. - if state := output.State; state == awstypes.CapacityReservationStateCancelled || state == awstypes.CapacityReservationStateExpired { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.CapacityReservationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findCOIPPool(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCoipPoolsInput) (*awstypes.CoipPool, error) { - output, err := findCOIPPools(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findCOIPPools(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCoipPoolsInput) ([]awstypes.CoipPool, error) { - var output []awstypes.CoipPool - - pages := ec2.NewDescribeCoipPoolsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidPoolIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.CoipPools...) - } - - return output, nil -} - -func findFleet(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFleetsInput) (*awstypes.FleetData, error) { - output, err := findFleets(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findFleets(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFleetsInput) ([]awstypes.FleetData, error) { - var output []awstypes.FleetData - - pages := ec2.NewDescribeFleetsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidFleetIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Fleets...) - } - - return output, nil -} - -func findFleetByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.FleetData, error) { - input := &ec2.DescribeFleetsInput{ - FleetIds: []string{id}, - } - - output, err := findFleet(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.FleetState; state == awstypes.FleetStateCodeDeleted || state == awstypes.FleetStateCodeDeletedRunning || state == awstypes.FleetStateCodeDeletedTerminatingInstances { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.FleetId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findHostByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Host, error) { - input := &ec2.DescribeHostsInput{ - HostIds: []string{id}, - } - - output, err := findHost(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.AllocationStateReleased || state == awstypes.AllocationStateReleasedPermanentFailure { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.HostId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findHosts(ctx context.Context, conn *ec2.Client, input *ec2.DescribeHostsInput) ([]awstypes.Host, error) { - var output []awstypes.Host - - pages := ec2.NewDescribeHostsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidHostIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Hosts...) - } - - return output, nil -} - -func findHost(ctx context.Context, conn *ec2.Client, input *ec2.DescribeHostsInput) (*awstypes.Host, error) { - output, err := findHosts(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.Host) bool { return v.HostProperties != nil }) -} - -func findInstanceCreditSpecifications(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceCreditSpecificationsInput) ([]awstypes.InstanceCreditSpecification, error) { - var output []awstypes.InstanceCreditSpecification - - pages := ec2.NewDescribeInstanceCreditSpecificationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.InstanceCreditSpecifications...) - } - - return output, nil -} - -func findInstanceCreditSpecification(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceCreditSpecificationsInput) (*awstypes.InstanceCreditSpecification, error) { - output, err := findInstanceCreditSpecifications(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findInstanceCreditSpecificationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.InstanceCreditSpecification, error) { - input := &ec2.DescribeInstanceCreditSpecificationsInput{ - InstanceIds: []string{id}, - } - - output, err := findInstanceCreditSpecification(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.InstanceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findInstances(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstancesInput) ([]awstypes.Instance, error) { - var output []awstypes.Instance - - pages := ec2.NewDescribeInstancesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - for _, v := range page.Reservations { - output = append(output, v.Instances...) - } - } - - return output, nil -} - -func findInstance(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstancesInput) (*awstypes.Instance, error) { - output, err := findInstances(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.Instance) bool { return v.State != nil }) -} - -func findInstanceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Instance, error) { - input := &ec2.DescribeInstancesInput{ - InstanceIds: []string{id}, - } - - output, err := findInstance(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State.Name; state == awstypes.InstanceStateNameTerminated { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.InstanceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findInstanceStatus(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceStatusInput) (*awstypes.InstanceStatus, error) { - output, err := findInstanceStatuses(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findInstanceStatuses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceStatusInput) ([]awstypes.InstanceStatus, error) { - var output []awstypes.InstanceStatus - - pages := ec2.NewDescribeInstanceStatusPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.InstanceStatuses...) - } - - return output, nil -} - -func findInstanceState(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceStatusInput) (*awstypes.InstanceState, error) { - output, err := findInstanceStatus(ctx, conn, input) - - if err != nil { - return nil, err - } - - if output.InstanceState == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.InstanceState, nil -} - -func findInstanceStateByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.InstanceState, error) { - input := &ec2.DescribeInstanceStatusInput{ - InstanceIds: []string{id}, - IncludeAllInstances: aws.Bool(true), - } - - output, err := findInstanceState(ctx, conn, input) - - if err != nil { - return nil, err - } - - if name := output.Name; name == awstypes.InstanceStateNameTerminated { - return nil, &retry.NotFoundError{ - Message: string(name), - LastRequest: input, - } - } - - return output, nil -} - -func findInstanceTypes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceTypesInput) ([]awstypes.InstanceTypeInfo, error) { - var output []awstypes.InstanceTypeInfo - - pages := ec2.NewDescribeInstanceTypesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.InstanceTypes...) - } - - return output, nil -} - -func findInstanceType(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceTypesInput) (*awstypes.InstanceTypeInfo, error) { - output, err := findInstanceTypes(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findInstanceTypeByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.InstanceTypeInfo, error) { - input := &ec2.DescribeInstanceTypesInput{ - InstanceTypes: []awstypes.InstanceType{awstypes.InstanceType(name)}, - } - - output, err := findInstanceType(ctx, conn, input) - - if err != nil { - return nil, err - } - - return output, nil -} - -func findInstanceTypeOfferings(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceTypeOfferingsInput) ([]awstypes.InstanceTypeOffering, error) { - var output []awstypes.InstanceTypeOffering - - pages := ec2.NewDescribeInstanceTypeOfferingsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.InstanceTypeOfferings...) - } - - return output, nil -} - -func findLaunchTemplate(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplatesInput) (*awstypes.LaunchTemplate, error) { - output, err := findLaunchTemplates(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLaunchTemplates(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplatesInput) ([]awstypes.LaunchTemplate, error) { - var output []awstypes.LaunchTemplate - - pages := ec2.NewDescribeLaunchTemplatesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidLaunchTemplateIdMalformed, errCodeInvalidLaunchTemplateIdNotFound, errCodeInvalidLaunchTemplateNameNotFoundException) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.LaunchTemplates...) - } - - return output, nil -} - -func findLaunchTemplateByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LaunchTemplate, error) { - input := &ec2.DescribeLaunchTemplatesInput{ - LaunchTemplateIds: []string{id}, - } - - output, err := findLaunchTemplate(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.LaunchTemplateId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findLaunchTemplateVersion(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplateVersionsInput) (*awstypes.LaunchTemplateVersion, error) { - output, err := findLaunchTemplateVersions(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.LaunchTemplateVersion) bool { return v.LaunchTemplateData != nil }) -} - -func findLaunchTemplateVersions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLaunchTemplateVersionsInput) ([]awstypes.LaunchTemplateVersion, error) { - var output []awstypes.LaunchTemplateVersion - - pages := ec2.NewDescribeLaunchTemplateVersionsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidLaunchTemplateIdNotFound, errCodeInvalidLaunchTemplateNameNotFoundException, errCodeInvalidLaunchTemplateIdVersionNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.LaunchTemplateVersions...) - } - - return output, nil -} - -func findLaunchTemplateVersionByTwoPartKey(ctx context.Context, conn *ec2.Client, launchTemplateID, version string) (*awstypes.LaunchTemplateVersion, error) { - input := &ec2.DescribeLaunchTemplateVersionsInput{ - LaunchTemplateId: aws.String(launchTemplateID), - Versions: []string{version}, - } - - output, err := findLaunchTemplateVersion(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.LaunchTemplateId) != launchTemplateID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findLocalGatewayRouteTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTablesInput) (*awstypes.LocalGatewayRouteTable, error) { - output, err := findLocalGatewayRouteTables(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLocalGatewayRouteTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTablesInput) ([]awstypes.LocalGatewayRouteTable, error) { - var output []awstypes.LocalGatewayRouteTable - - pages := ec2.NewDescribeLocalGatewayRouteTablesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.LocalGatewayRouteTables...) - } - - return output, nil -} - -func findLocalGatewayRoutes(ctx context.Context, conn *ec2.Client, input *ec2.SearchLocalGatewayRoutesInput) ([]awstypes.LocalGatewayRoute, error) { - var output []awstypes.LocalGatewayRoute - - pages := ec2.NewSearchLocalGatewayRoutesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidLocalGatewayRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Routes...) - } - - return output, nil -} - -func findLocalGatewayRouteByTwoPartKey(ctx context.Context, conn *ec2.Client, localGatewayRouteTableID, destinationCIDRBlock string) (*awstypes.LocalGatewayRoute, error) { - input := &ec2.SearchLocalGatewayRoutesInput{ - Filters: []awstypes.Filter{ - { - Name: aws.String(names.AttrType), - Values: enum.Slice(awstypes.LocalGatewayRouteTypeStatic), - }, - }, - LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID), - } - - localGatewayRoutes, err := findLocalGatewayRoutes(ctx, conn, input) - - if err != nil { - return nil, err - } - - localGatewayRoutes = tfslices.Filter(localGatewayRoutes, func(v awstypes.LocalGatewayRoute) bool { - return aws.ToString(v.DestinationCidrBlock) == destinationCIDRBlock - }) - - output, err := tfresource.AssertSingleValueResult(localGatewayRoutes) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.LocalGatewayRouteStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - return output, nil -} - -func findLocalGatewayRouteTableVPCAssociation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { - output, err := findLocalGatewayRouteTableVPCAssociations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLocalGatewayRouteTableVPCAssociations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput) ([]awstypes.LocalGatewayRouteTableVpcAssociation, error) { - var output []awstypes.LocalGatewayRouteTableVpcAssociation - - pages := ec2.NewDescribeLocalGatewayRouteTableVpcAssociationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.LocalGatewayRouteTableVpcAssociations...) - } - - return output, nil -} - -func findLocalGatewayRouteTableVPCAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { - input := &ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput{ - LocalGatewayRouteTableVpcAssociationIds: []string{id}, - } - - output, err := findLocalGatewayRouteTableVPCAssociation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := aws.ToString(output.State); state == string(awstypes.RouteTableAssociationStateCodeDisassociated) { - return nil, &retry.NotFoundError{ - Message: state, - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.LocalGatewayRouteTableVpcAssociationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findLocalGatewayVirtualInterface(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfacesInput) (*awstypes.LocalGatewayVirtualInterface, error) { - output, err := findLocalGatewayVirtualInterfaces(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLocalGatewayVirtualInterfaces(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfacesInput) ([]awstypes.LocalGatewayVirtualInterface, error) { - var output []awstypes.LocalGatewayVirtualInterface - - pages := ec2.NewDescribeLocalGatewayVirtualInterfacesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.LocalGatewayVirtualInterfaces...) - } - - return output, nil -} - -func findLocalGatewayVirtualInterfaceGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput) (*awstypes.LocalGatewayVirtualInterfaceGroup, error) { - output, err := findLocalGatewayVirtualInterfaceGroups(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLocalGatewayVirtualInterfaceGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput) ([]awstypes.LocalGatewayVirtualInterfaceGroup, error) { - var output []awstypes.LocalGatewayVirtualInterfaceGroup - - pages := ec2.NewDescribeLocalGatewayVirtualInterfaceGroupsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.LocalGatewayVirtualInterfaceGroups...) - } - - return output, nil -} - -func findLocalGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewaysInput) (*awstypes.LocalGateway, error) { - output, err := findLocalGateways(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findLocalGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeLocalGatewaysInput) ([]awstypes.LocalGateway, error) { - var output []awstypes.LocalGateway - - pages := ec2.NewDescribeLocalGatewaysPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.LocalGateways...) - } - - return output, nil -} - -func findPlacementGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribePlacementGroupsInput) (*awstypes.PlacementGroup, error) { - output, err := findPlacementGroups(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findPlacementGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribePlacementGroupsInput) ([]awstypes.PlacementGroup, error) { - output, err := conn.DescribePlacementGroups(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidPlacementGroupUnknown) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.PlacementGroups, nil -} - -func findPlacementGroupByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PlacementGroup, error) { - input := &ec2.DescribePlacementGroupsInput{ - GroupNames: []string{name}, - } - - output, err := findPlacementGroup(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.PlacementGroupStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - return output, nil -} - -func findPublicIPv4Pool(ctx context.Context, conn *ec2.Client, input *ec2.DescribePublicIpv4PoolsInput) (*awstypes.PublicIpv4Pool, error) { - output, err := findPublicIPv4Pools(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findPublicIPv4Pools(ctx context.Context, conn *ec2.Client, input *ec2.DescribePublicIpv4PoolsInput) ([]awstypes.PublicIpv4Pool, error) { - var output []awstypes.PublicIpv4Pool - - pages := ec2.NewDescribePublicIpv4PoolsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidPublicIpv4PoolIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.PublicIpv4Pools...) - } - - return output, nil -} - -func findPublicIPv4PoolByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.PublicIpv4Pool, error) { - input := &ec2.DescribePublicIpv4PoolsInput{ - PoolIds: []string{id}, - } - - output, err := findPublicIPv4Pool(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.PoolId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVolumeAttachmentInstanceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Instance, error) { - input := &ec2.DescribeInstancesInput{ - InstanceIds: []string{id}, - } - - output, err := findInstance(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State.Name; state == awstypes.InstanceStateNameTerminated { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.InstanceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findSpotDatafeedSubscription(ctx context.Context, conn *ec2.Client) (*awstypes.SpotDatafeedSubscription, error) { - input := &ec2.DescribeSpotDatafeedSubscriptionInput{} - - output, err := conn.DescribeSpotDatafeedSubscription(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotDatafeedNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil || output.SpotDatafeedSubscription == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.SpotDatafeedSubscription, nil -} - -func findSpotInstanceRequests(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotInstanceRequestsInput) ([]awstypes.SpotInstanceRequest, error) { - var output []awstypes.SpotInstanceRequest - - pages := ec2.NewDescribeSpotInstanceRequestsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotInstanceRequestIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.SpotInstanceRequests...) - } - - return output, nil -} - -func findSpotInstanceRequest(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotInstanceRequestsInput) (*awstypes.SpotInstanceRequest, error) { - output, err := findSpotInstanceRequests(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.SpotInstanceRequest) bool { return v.Status != nil }) -} - -func findSpotInstanceRequestByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SpotInstanceRequest, error) { - input := &ec2.DescribeSpotInstanceRequestsInput{ - SpotInstanceRequestIds: []string{id}, - } - - output, err := findSpotInstanceRequest(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.SpotInstanceStateCancelled || state == awstypes.SpotInstanceStateClosed { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.SpotInstanceRequestId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findSpotPrices(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotPriceHistoryInput) ([]awstypes.SpotPrice, error) { - var output []awstypes.SpotPrice - pages := ec2.NewDescribeSpotPriceHistoryPaginator(conn, input) - - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.SpotPriceHistory...) - } - - return output, nil -} - -func findSpotPrice(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotPriceHistoryInput) (*awstypes.SpotPrice, error) { - output, err := findSpotPrices(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findSubnets(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSubnetsInput) ([]awstypes.Subnet, error) { - var output []awstypes.Subnet - - pages := ec2.NewDescribeSubnetsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSubnetIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Subnets...) - } - - return output, nil -} - -func findVolumeModifications(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesModificationsInput) ([]awstypes.VolumeModification, error) { - var output []awstypes.VolumeModification - - pages := ec2.NewDescribeVolumesModificationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVolumeNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.VolumesModifications...) - } - - return output, nil -} - -func findVolumeModification(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesModificationsInput) (*awstypes.VolumeModification, error) { - output, err := findVolumeModifications(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVolumeModificationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VolumeModification, error) { - input := &ec2.DescribeVolumesModificationsInput{ - VolumeIds: []string{id}, - } - - output, err := findVolumeModification(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.VolumeId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVPCAttribute(ctx context.Context, conn *ec2.Client, vpcID string, attribute awstypes.VpcAttributeName) (bool, error) { - input := &ec2.DescribeVpcAttributeInput{ - Attribute: attribute, - VpcId: aws.String(vpcID), - } - - output, err := conn.DescribeVpcAttribute(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { - return false, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return false, err - } - - if output == nil { - return false, tfresource.NewEmptyResultError(input) - } - - var v *awstypes.AttributeBooleanValue - switch attribute { - case awstypes.VpcAttributeNameEnableDnsHostnames: - v = output.EnableDnsHostnames - case awstypes.VpcAttributeNameEnableDnsSupport: - v = output.EnableDnsSupport - case awstypes.VpcAttributeNameEnableNetworkAddressUsageMetrics: - v = output.EnableNetworkAddressUsageMetrics - default: - return false, fmt.Errorf("unsupported VPC attribute: %s", attribute) - } - - if v == nil { - return false, tfresource.NewEmptyResultError(input) - } - - return aws.ToBool(v.Value), nil -} - -func findVPC(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcsInput) (*awstypes.Vpc, error) { - output, err := findVPCs(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVPCs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcsInput) ([]awstypes.Vpc, error) { - var output []awstypes.Vpc - - pages := ec2.NewDescribeVpcsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Vpcs...) - } - - return output, nil -} - -func findVPCByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Vpc, error) { - input := &ec2.DescribeVpcsInput{ - VpcIds: []string{id}, - } - - return findVPC(ctx, conn, input) -} - -func findVPCIPv6CIDRBlockAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpcIpv6CidrBlockAssociation, *awstypes.Vpc, error) { - input := &ec2.DescribeVpcsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "ipv6-cidr-block-association.association-id": id, - }), - } - - vpc, err := findVPC(ctx, conn, input) - - if err != nil { - return nil, nil, err - } - - for _, association := range vpc.Ipv6CidrBlockAssociationSet { - if aws.ToString(association.AssociationId) == id { - if state := association.Ipv6CidrBlockState.State; state == awstypes.VpcCidrBlockStateCodeDisassociated { - return nil, nil, &retry.NotFoundError{Message: string(state)} - } - - return &association, vpc, nil - } - } - - return nil, nil, &retry.NotFoundError{} -} - -func findVPCDefaultNetworkACL(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkAcl, error) { - input := &ec2.DescribeNetworkAclsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "default": "true", - "vpc-id": id, - }), - } - - return findNetworkACL(ctx, conn, input) -} - -func findNetworkACLByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkAcl, error) { - input := &ec2.DescribeNetworkAclsInput{ - NetworkAclIds: []string{id}, - } - - output, err := findNetworkACL(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.NetworkAclId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findNetworkACL(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkAclsInput) (*awstypes.NetworkAcl, error) { - output, err := findNetworkACLs(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findNetworkACLs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkAclsInput) ([]awstypes.NetworkAcl, error) { - var output []awstypes.NetworkAcl - - pages := ec2.NewDescribeNetworkAclsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkACLIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.NetworkAcls...) - } - - return output, nil -} - -func findVPCDefaultSecurityGroup(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SecurityGroup, error) { - input := &ec2.DescribeSecurityGroupsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "group-name": DefaultSecurityGroupName, - "vpc-id": id, - }), - } - - return findSecurityGroup(ctx, conn, input) -} - -func findVPCMainRouteTable(ctx context.Context, conn *ec2.Client, id string) (*awstypes.RouteTable, error) { - input := &ec2.DescribeRouteTablesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "association.main": "true", - "vpc-id": id, - }), - } - - return findRouteTable(ctx, conn, input) -} - -func findRouteTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeRouteTablesInput) (*awstypes.RouteTable, error) { - output, err := findRouteTables(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findRouteTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeRouteTablesInput) ([]awstypes.RouteTable, error) { - var output []awstypes.RouteTable - - pages := ec2.NewDescribeRouteTablesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.RouteTables...) - } - - return output, nil -} - -func findSecurityGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSecurityGroupsInput) (*awstypes.SecurityGroup, error) { - output, err := findSecurityGroups(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findSecurityGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSecurityGroupsInput) ([]awstypes.SecurityGroup, error) { - var output []awstypes.SecurityGroup - - pages := ec2.NewDescribeSecurityGroupsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidGroupNotFound, errCodeInvalidSecurityGroupIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.SecurityGroups...) - } - - return output, nil -} - -// findSecurityGroupByNameAndVPCID looks up a security group by name, VPC ID. Returns a retry.NotFoundError if not found. -func findSecurityGroupByNameAndVPCID(ctx context.Context, conn *ec2.Client, name, vpcID string) (*awstypes.SecurityGroup, error) { - input := &ec2.DescribeSecurityGroupsInput{ - Filters: newAttributeFilterListV2( - map[string]string{ - "group-name": name, - "vpc-id": vpcID, - }, - ), - } - return findSecurityGroup(ctx, conn, input) -} - -func findNetworkInterfaces(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInterfacesInput) ([]awstypes.NetworkInterface, error) { - var output []awstypes.NetworkInterface - - pages := ec2.NewDescribeNetworkInterfacesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInterfaceIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.NetworkInterfaces...) - } - - return output, nil -} - -func findNetworkInterface(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInterfacesInput) (*awstypes.NetworkInterface, error) { - output, err := findNetworkInterfaces(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findNetworkInterfaceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInterface, error) { - input := &ec2.DescribeNetworkInterfacesInput{ - NetworkInterfaceIds: []string{id}, - } - - output, err := findNetworkInterface(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.NetworkInterfaceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, err -} - -func findNetworkInterfaceAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInterfaceAttachment, error) { - input := &ec2.DescribeNetworkInterfacesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "attachment.attachment-id": id, - }), - } - - networkInterface, err := findNetworkInterface(ctx, conn, input) - - if err != nil { - return nil, err - } - - if networkInterface.Attachment == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return networkInterface.Attachment, nil -} - -func findNetworkInterfacesByAttachmentInstanceOwnerIDAndDescription(ctx context.Context, conn *ec2.Client, attachmentInstanceOwnerID, description string) ([]awstypes.NetworkInterface, error) { - input := &ec2.DescribeNetworkInterfacesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "attachment.instance-owner-id": attachmentInstanceOwnerID, - names.AttrDescription: description, - }), - } - - return findNetworkInterfaces(ctx, conn, input) -} - -func findEBSVolumes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesInput) ([]awstypes.Volume, error) { - var output []awstypes.Volume - - pages := ec2.NewDescribeVolumesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidVolumeNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.Volumes...) - } - - return output, nil -} - -func findEBSVolume(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVolumesInput) (*awstypes.Volume, error) { - output, err := findEBSVolumes(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findEBSVolumeByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Volume, error) { - input := &ec2.DescribeVolumesInput{ - VolumeIds: []string{id}, - } - - output, err := findEBSVolume(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.VolumeStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.VolumeId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findPrefixList(ctx context.Context, conn *ec2.Client, input *ec2.DescribePrefixListsInput) (*awstypes.PrefixList, error) { - output, err := findPrefixLists(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findPrefixLists(ctx context.Context, conn *ec2.Client, input *ec2.DescribePrefixListsInput) ([]awstypes.PrefixList, error) { - var output []awstypes.PrefixList - - pages := ec2.NewDescribePrefixListsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidPrefixListIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.PrefixLists...) - } - - return output, nil -} - -func findVPCEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpcEndpoint, error) { - input := &ec2.DescribeVpcEndpointsInput{ - VpcEndpointIds: []string{id}, - } - - output, err := findVPCEndpoint(ctx, conn, input) - - if err != nil { - return nil, err - } - - if output.State == awstypes.StateDeleted { - return nil, &retry.NotFoundError{ - Message: string(output.State), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.VpcEndpointId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVPCEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointsInput) (*awstypes.VpcEndpoint, error) { - output, err := findVPCEndpoints(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVPCEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointsInput) ([]awstypes.VpcEndpoint, error) { - var output []awstypes.VpcEndpoint - - pages := ec2.NewDescribeVpcEndpointsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.VpcEndpoints...) - } - - return output, nil -} - -func findPrefixListByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PrefixList, error) { - input := &ec2.DescribePrefixListsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "prefix-list-name": name, - }), - } - - return findPrefixList(ctx, conn, input) -} - -func findSpotFleetInstances(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetInstancesInput) ([]awstypes.ActiveInstance, error) { - var output []awstypes.ActiveInstance - - err := describeSpotFleetInstancesPages(ctx, conn, input, func(page *ec2.DescribeSpotFleetInstancesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - output = append(output, page.ActiveInstances...) - - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotFleetRequestIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - return output, nil -} - -func findSpotFleetRequests(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetRequestsInput) ([]awstypes.SpotFleetRequestConfig, error) { - var output []awstypes.SpotFleetRequestConfig - - paginator := ec2.NewDescribeSpotFleetRequestsPaginator(conn, input) - for paginator.HasMorePages() { - page, err := paginator.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotFleetRequestIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.SpotFleetRequestConfigs...) - } - - return output, nil -} - -func findSpotFleetRequest(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetRequestsInput) (*awstypes.SpotFleetRequestConfig, error) { - output, err := findSpotFleetRequests(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.SpotFleetRequestConfig) bool { return v.SpotFleetRequestConfig != nil }) -} - -func findSpotFleetRequestByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SpotFleetRequestConfig, error) { - input := &ec2.DescribeSpotFleetRequestsInput{ - SpotFleetRequestIds: []string{id}, - } - - output, err := findSpotFleetRequest(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.SpotFleetRequestState; state == awstypes.BatchStateCancelled || state == awstypes.BatchStateCancelledRunning || state == awstypes.BatchStateCancelledTerminatingInstances { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.SpotFleetRequestId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findSpotFleetRequestHistoryRecords(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSpotFleetRequestHistoryInput) ([]awstypes.HistoryRecord, error) { - var output []awstypes.HistoryRecord - - err := describeSpotFleetRequestHistoryPages(ctx, conn, input, func(page *ec2.DescribeSpotFleetRequestHistoryOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - output = append(output, page.HistoryRecords...) - - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSpotFleetRequestIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - return output, nil -} - -func findVPCEndpointServiceConfigurationByServiceName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.ServiceConfiguration, error) { - input := &ec2.DescribeVpcEndpointServiceConfigurationsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "service-name": name, - }), - } - - return findVPCEndpointServiceConfiguration(ctx, conn, input) -} - -func findVPCEndpointServiceConfiguration(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServiceConfigurationsInput) (*awstypes.ServiceConfiguration, error) { - output, err := findVPCEndpointServiceConfigurations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVPCEndpointServiceConfigurations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServiceConfigurationsInput) ([]awstypes.ServiceConfiguration, error) { - var output []awstypes.ServiceConfiguration - - pages := ec2.NewDescribeVpcEndpointServiceConfigurationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.ServiceConfigurations...) - } - - return output, nil -} - -// findRouteTableByID returns the route table corresponding to the specified identifier. -// Returns NotFoundError if no route table is found. -func findRouteTableByID(ctx context.Context, conn *ec2.Client, routeTableID string) (*awstypes.RouteTable, error) { - input := &ec2.DescribeRouteTablesInput{ - RouteTableIds: []string{routeTableID}, - } - - return findRouteTable(ctx, conn, input) -} - -// routeFinder returns the route corresponding to the specified destination. -// Returns NotFoundError if no route is found. -type routeFinder func(context.Context, *ec2.Client, string, string) (*awstypes.Route, error) - -// findRouteByIPv4Destination returns the route corresponding to the specified IPv4 destination. -// Returns NotFoundError if no route is found. -func findRouteByIPv4Destination(ctx context.Context, conn *ec2.Client, routeTableID, destinationCidr string) (*awstypes.Route, error) { - routeTable, err := findRouteTableByID(ctx, conn, routeTableID) - - if err != nil { - return nil, err - } - - for _, route := range routeTable.Routes { - if types.CIDRBlocksEqual(aws.ToString(route.DestinationCidrBlock), destinationCidr) { - return &route, nil - } - } - - return nil, &retry.NotFoundError{ - LastError: fmt.Errorf("Route in Route Table (%s) with IPv4 destination (%s) not found", routeTableID, destinationCidr), - } -} - -// findRouteByIPv6Destination returns the route corresponding to the specified IPv6 destination. -// Returns NotFoundError if no route is found. -func findRouteByIPv6Destination(ctx context.Context, conn *ec2.Client, routeTableID, destinationIpv6Cidr string) (*awstypes.Route, error) { - routeTable, err := findRouteTableByID(ctx, conn, routeTableID) - - if err != nil { - return nil, err - } - - for _, route := range routeTable.Routes { - if types.CIDRBlocksEqual(aws.ToString(route.DestinationIpv6CidrBlock), destinationIpv6Cidr) { - return &route, nil - } - } - - return nil, &retry.NotFoundError{ - LastError: fmt.Errorf("Route in Route Table (%s) with IPv6 destination (%s) not found", routeTableID, destinationIpv6Cidr), - } -} - -// findRouteByPrefixListIDDestination returns the route corresponding to the specified prefix list destination. -// Returns NotFoundError if no route is found. -func findRouteByPrefixListIDDestination(ctx context.Context, conn *ec2.Client, routeTableID, prefixListID string) (*awstypes.Route, error) { - routeTable, err := findRouteTableByID(ctx, conn, routeTableID) - if err != nil { - return nil, err - } - - for _, route := range routeTable.Routes { - if aws.ToString(route.DestinationPrefixListId) == prefixListID { - return &route, nil - } - } - - return nil, &retry.NotFoundError{ - LastError: fmt.Errorf("Route in Route Table (%s) with Prefix List ID destination (%s) not found", routeTableID, prefixListID), - } -} - -// findMainRouteTableAssociationByID returns the main route table association corresponding to the specified identifier. -// Returns NotFoundError if no route table association is found. -func findMainRouteTableAssociationByID(ctx context.Context, conn *ec2.Client, associationID string) (*awstypes.RouteTableAssociation, error) { - association, err := findRouteTableAssociationByID(ctx, conn, associationID) - - if err != nil { - return nil, err - } - - if !aws.ToBool(association.Main) { - return nil, &retry.NotFoundError{ - Message: fmt.Sprintf("%s is not the association with the main route table", associationID), - } - } - - return association, err -} - -// findMainRouteTableAssociationByVPCID returns the main route table association for the specified VPC. -// Returns NotFoundError if no route table association is found. -func findMainRouteTableAssociationByVPCID(ctx context.Context, conn *ec2.Client, vpcID string) (*awstypes.RouteTableAssociation, error) { - routeTable, err := findMainRouteTableByVPCID(ctx, conn, vpcID) - - if err != nil { - return nil, err - } - - for _, association := range routeTable.Associations { - if aws.ToBool(association.Main) { - if association.AssociationState != nil { - if state := association.AssociationState.State; state == awstypes.RouteTableAssociationStateCodeDisassociated { - continue - } - } - - return &association, nil - } - } - - return nil, &retry.NotFoundError{} -} - -// findRouteTableAssociationByID returns the route table association corresponding to the specified identifier. -// Returns NotFoundError if no route table association is found. -func findRouteTableAssociationByID(ctx context.Context, conn *ec2.Client, associationID string) (*awstypes.RouteTableAssociation, error) { - input := &ec2.DescribeRouteTablesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "association.route-table-association-id": associationID, - }), - } - - routeTable, err := findRouteTable(ctx, conn, input) - - if err != nil { - return nil, err - } - - for _, association := range routeTable.Associations { - if aws.ToString(association.RouteTableAssociationId) == associationID { - if association.AssociationState != nil { - if state := association.AssociationState.State; state == awstypes.RouteTableAssociationStateCodeDisassociated { - return nil, &retry.NotFoundError{Message: string(state)} - } - } - - return &association, nil - } - } - - return nil, &retry.NotFoundError{} -} - -// findMainRouteTableByVPCID returns the main route table for the specified VPC. -// Returns NotFoundError if no route table is found. -func findMainRouteTableByVPCID(ctx context.Context, conn *ec2.Client, vpcID string) (*awstypes.RouteTable, error) { - input := &ec2.DescribeRouteTablesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "association.main": "true", - "vpc-id": vpcID, - }), - } - - return findRouteTable(ctx, conn, input) -} - -// findVPNGatewayRoutePropagationExists returns NotFoundError if no route propagation for the specified VPN gateway is found. -func findVPNGatewayRoutePropagationExists(ctx context.Context, conn *ec2.Client, routeTableID, gatewayID string) error { - routeTable, err := findRouteTableByID(ctx, conn, routeTableID) - - if err != nil { - return err - } - - for _, v := range routeTable.PropagatingVgws { - if aws.ToString(v.GatewayId) == gatewayID { - return nil - } - } - - return &retry.NotFoundError{ - LastError: fmt.Errorf("Route Table (%s) VPN Gateway (%s) route propagation not found", routeTableID, gatewayID), - } -} - -func findVPCEndpointServiceConfigurationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ServiceConfiguration, error) { - input := &ec2.DescribeVpcEndpointServiceConfigurationsInput{ - ServiceIds: []string{id}, - } - - output, err := findVPCEndpointServiceConfiguration(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.ServiceState; state == awstypes.ServiceStateDeleted || state == awstypes.ServiceStateFailed { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.ServiceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVPCEndpointServicePrivateDNSNameConfigurationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.PrivateDnsNameConfiguration, error) { - out, err := findVPCEndpointServiceConfigurationByID(ctx, conn, id) - if err != nil { - return nil, err - } - - return out.PrivateDnsNameConfiguration, nil -} - -func findVPCEndpointServicePermissions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServicePermissionsInput) ([]awstypes.AllowedPrincipal, error) { - var output []awstypes.AllowedPrincipal - - pages := ec2.NewDescribeVpcEndpointServicePermissionsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.AllowedPrincipals...) - } - - return output, nil -} - -func findVPCEndpointServicePermissionsByServiceID(ctx context.Context, conn *ec2.Client, id string) ([]awstypes.AllowedPrincipal, error) { - input := &ec2.DescribeVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(id), - } - - return findVPCEndpointServicePermissions(ctx, conn, input) -} - -func findVPCEndpointServices(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointServicesInput) ([]awstypes.ServiceDetail, []string, error) { - var serviceDetails []awstypes.ServiceDetail - var serviceNames []string - - err := describeVPCEndpointServicesPages(ctx, conn, input, func(page *ec2.DescribeVpcEndpointServicesOutput, lastPage bool) bool { - if page == nil { - return !lastPage - } - - serviceDetails = append(serviceDetails, page.ServiceDetails...) - serviceNames = append(serviceNames, page.ServiceNames...) - - return !lastPage - }) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidServiceName) { - return nil, nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, nil, err - } - - return serviceDetails, serviceNames, nil -} - -// findVPCEndpointRouteTableAssociationExists returns NotFoundError if no association for the specified VPC endpoint and route table IDs is found. -func findVPCEndpointRouteTableAssociationExists(ctx context.Context, conn *ec2.Client, vpcEndpointID string, routeTableID string) error { - vpcEndpoint, err := findVPCEndpointByID(ctx, conn, vpcEndpointID) - - if err != nil { - return err - } - - for _, vpcEndpointRouteTableID := range vpcEndpoint.RouteTableIds { - if vpcEndpointRouteTableID == routeTableID { - return nil - } - } - - return &retry.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint (%s) Route Table (%s) Association not found", vpcEndpointID, routeTableID), - } -} - -// findVPCEndpointSecurityGroupAssociationExists returns NotFoundError if no association for the specified VPC endpoint and security group IDs is found. -func findVPCEndpointSecurityGroupAssociationExists(ctx context.Context, conn *ec2.Client, vpcEndpointID, securityGroupID string) error { - vpcEndpoint, err := findVPCEndpointByID(ctx, conn, vpcEndpointID) - - if err != nil { - return err - } - - for _, group := range vpcEndpoint.Groups { - if aws.ToString(group.GroupId) == securityGroupID { - return nil - } - } - - return &retry.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint (%s) Security Group (%s) Association not found", vpcEndpointID, securityGroupID), - } -} - -// findVPCEndpointSubnetAssociationExists returns NotFoundError if no association for the specified VPC endpoint and subnet IDs is found. -func findVPCEndpointSubnetAssociationExists(ctx context.Context, conn *ec2.Client, vpcEndpointID string, subnetID string) error { - vpcEndpoint, err := findVPCEndpointByID(ctx, conn, vpcEndpointID) - - if err != nil { - return err - } - - for _, vpcEndpointSubnetID := range vpcEndpoint.SubnetIds { - if vpcEndpointSubnetID == subnetID { - return nil - } - } - - return &retry.NotFoundError{ - LastError: fmt.Errorf("VPC Endpoint (%s) Subnet (%s) Association not found", vpcEndpointID, subnetID), - } -} - -func findVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx context.Context, conn *ec2.Client, serviceID, vpcEndpointID string) (*awstypes.VpcEndpointConnection, error) { - input := &ec2.DescribeVpcEndpointConnectionsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "service-id": serviceID, - // "InvalidFilter: The filter vpc-endpoint-id is invalid" - // "vpc-endpoint-id ": vpcEndpointID, - }), - } - - var output *awstypes.VpcEndpointConnection - - pages := ec2.NewDescribeVpcEndpointConnectionsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - if err != nil { - return nil, err - } - - for _, v := range page.VpcEndpointConnections { - v := v - if aws.ToString(v.VpcEndpointId) == vpcEndpointID { - output = &v - break - } - } - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - if vpcEndpointState := string(output.VpcEndpointState); vpcEndpointState == vpcEndpointStateDeleted { - return nil, &retry.NotFoundError{ - Message: vpcEndpointState, - LastRequest: input, - } - } - - return output, nil -} - -func findVPCEndpointConnectionNotification(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointConnectionNotificationsInput) (*awstypes.ConnectionNotification, error) { - output, err := findVPCEndpointConnectionNotifications(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVPCEndpointConnectionNotifications(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpcEndpointConnectionNotificationsInput) ([]awstypes.ConnectionNotification, error) { - var output []awstypes.ConnectionNotification - - pages := ec2.NewDescribeVpcEndpointConnectionNotificationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidConnectionNotification) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.ConnectionNotificationSet...) - } - - return output, nil -} - -func findVPCEndpointConnectionNotificationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ConnectionNotification, error) { - input := &ec2.DescribeVpcEndpointConnectionNotificationsInput{ - ConnectionNotificationId: aws.String(id), - } - - output, err := findVPCEndpointConnectionNotification(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.ConnectionNotificationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVPCEndpointServicePermission(ctx context.Context, conn *ec2.Client, serviceID, principalARN string) (*awstypes.AllowedPrincipal, error) { - // Applying a server-side filter on "principal" can lead to errors like - // "An error occurred (InvalidFilter) when calling the DescribeVpcEndpointServicePermissions operation: The filter value arn:aws:iam::123456789012:role/developer contains unsupported characters". - // Apply the filter client-side. - input := &ec2.DescribeVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(serviceID), - } - - allowedPrincipals, err := findVPCEndpointServicePermissions(ctx, conn, input) - - if err != nil { - return nil, err - } - - allowedPrincipals = tfslices.Filter(allowedPrincipals, func(v awstypes.AllowedPrincipal) bool { - return aws.ToString(v.Principal) == principalARN - }) - - return tfresource.AssertSingleValueResult(allowedPrincipals) -} - -func findClientVPNEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnEndpointsInput) (*awstypes.ClientVpnEndpoint, error) { - output, err := findClientVPNEndpoints(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findClientVPNEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnEndpointsInput) ([]awstypes.ClientVpnEndpoint, error) { - var output []awstypes.ClientVpnEndpoint - - pages := ec2.NewDescribeClientVpnEndpointsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.ClientVpnEndpoints...) - } - - return output, nil -} - -func findClientVPNEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ClientVpnEndpoint, error) { - input := &ec2.DescribeClientVpnEndpointsInput{ - ClientVpnEndpointIds: []string{id}, - } - - output, err := findClientVPNEndpoint(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.Status.Code; state == awstypes.ClientVpnEndpointStatusCodeDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.ClientVpnEndpointId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findClientVPNEndpointClientConnectResponseOptionsByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ClientConnectResponseOptions, error) { - output, err := findClientVPNEndpointByID(ctx, conn, id) - - if err != nil { - return nil, err - } - - if output.ClientConnectOptions == nil || output.ClientConnectOptions.Status == nil { - return nil, tfresource.NewEmptyResultError(id) - } - - return output.ClientConnectOptions, nil -} - -func findClientVPNAuthorizationRule(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnAuthorizationRulesInput) (*awstypes.AuthorizationRule, error) { - output, err := findClientVPNAuthorizationRules(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findClientVPNAuthorizationRules(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnAuthorizationRulesInput) ([]awstypes.AuthorizationRule, error) { - var output []awstypes.AuthorizationRule - - pages := ec2.NewDescribeClientVpnAuthorizationRulesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.AuthorizationRules...) - } - - return output, nil -} - -func findClientVPNAuthorizationRuleByThreePartKey(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string) (*awstypes.AuthorizationRule, error) { - filters := map[string]string{ - "destination-cidr": targetNetworkCIDR, - } - if accessGroupID != "" { - filters["group-id"] = accessGroupID - } - input := &ec2.DescribeClientVpnAuthorizationRulesInput{ - ClientVpnEndpointId: aws.String(endpointID), - Filters: newAttributeFilterListV2(filters), - } - - return findClientVPNAuthorizationRule(ctx, conn, input) -} - -func findClientVPNNetworkAssociation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnTargetNetworksInput) (*awstypes.TargetNetwork, error) { - output, err := findClientVPNNetworkAssociations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findClientVPNNetworkAssociations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnTargetNetworksInput) ([]awstypes.TargetNetwork, error) { - var output []awstypes.TargetNetwork - - pages := ec2.NewDescribeClientVpnTargetNetworksPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound, errCodeInvalidClientVPNAssociationIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.ClientVpnTargetNetworks...) - } - - return output, nil -} - -func findClientVPNNetworkAssociationByTwoPartKey(ctx context.Context, conn *ec2.Client, associationID, endpointID string) (*awstypes.TargetNetwork, error) { - input := &ec2.DescribeClientVpnTargetNetworksInput{ - AssociationIds: []string{associationID}, - ClientVpnEndpointId: aws.String(endpointID), - } - - output, err := findClientVPNNetworkAssociation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.Status.Code; state == awstypes.AssociationStatusCodeDisassociated { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.ClientVpnEndpointId) != endpointID || aws.ToString(output.AssociationId) != associationID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findClientVPNRoute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnRoutesInput) (*awstypes.ClientVpnRoute, error) { - output, err := findClientVPNRoutes(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findClientVPNRoutes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeClientVpnRoutesInput) ([]awstypes.ClientVpnRoute, error) { - var output []awstypes.ClientVpnRoute - - pages := ec2.NewDescribeClientVpnRoutesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidClientVPNEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Routes...) - } - - return output, nil -} - -func findClientVPNRouteByThreePartKey(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string) (*awstypes.ClientVpnRoute, error) { - input := &ec2.DescribeClientVpnRoutesInput{ - ClientVpnEndpointId: aws.String(endpointID), - Filters: newAttributeFilterListV2(map[string]string{ - "destination-cidr": destinationCIDR, - "target-subnet": targetSubnetID, - }), - } - - return findClientVPNRoute(ctx, conn, input) -} - -func findCarrierGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCarrierGatewaysInput) (*awstypes.CarrierGateway, error) { - output, err := findCarrierGateways(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findCarrierGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCarrierGatewaysInput) ([]awstypes.CarrierGateway, error) { - var output []awstypes.CarrierGateway - - pages := ec2.NewDescribeCarrierGatewaysPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidCarrierGatewayIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.CarrierGateways...) - } - - return output, nil -} - -func findCarrierGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CarrierGateway, error) { - input := &ec2.DescribeCarrierGatewaysInput{ - CarrierGatewayIds: []string{id}, - } - - output, err := findCarrierGateway(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.CarrierGatewayStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.CarrierGatewayId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVPNConnection(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnConnectionsInput) (*awstypes.VpnConnection, error) { - output, err := findVPNConnections(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVPNConnections(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnConnectionsInput) ([]awstypes.VpnConnection, error) { - output, err := conn.DescribeVpnConnections(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPNConnectionIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - return output.VpnConnections, nil -} - -func findVPNConnectionByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { - input := &ec2.DescribeVpnConnectionsInput{ - VpnConnectionIds: []string{id}, - } - - output, err := findVPNConnection(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.VpnStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.VpnConnectionId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVPNConnectionRouteByTwoPartKey(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) (*awstypes.VpnStaticRoute, error) { - input := &ec2.DescribeVpnConnectionsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "route.destination-cidr-block": cidrBlock, - "vpn-connection-id": vpnConnectionID, - }), - } - - output, err := findVPNConnection(ctx, conn, input) - - if err != nil { - return nil, err - } - - for _, v := range output.Routes { - if aws.ToString(v.DestinationCidrBlock) == cidrBlock && v.State != awstypes.VpnStateDeleted { - return &v, nil - } - } - - return nil, &retry.NotFoundError{ - LastError: fmt.Errorf("EC2 VPN Connection (%s) Route (%s) not found", vpnConnectionID, cidrBlock), - } -} - -func findVPNGatewayVPCAttachmentByTwoPartKey(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) (*awstypes.VpcAttachment, error) { - vpnGateway, err := findVPNGatewayByID(ctx, conn, vpnGatewayID) - - if err != nil { - return nil, err - } - - for _, vpcAttachment := range vpnGateway.VpcAttachments { - if aws.ToString(vpcAttachment.VpcId) == vpcID { - if state := vpcAttachment.State; state == awstypes.AttachmentStatusDetached { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: vpcID, - } - } - - return &vpcAttachment, nil - } - } - - return nil, tfresource.NewEmptyResultError(vpcID) -} - -func findVPNGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnGatewaysInput) (*awstypes.VpnGateway, error) { - output, err := findVPNGateways(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVPNGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVpnGatewaysInput) ([]awstypes.VpnGateway, error) { - output, err := conn.DescribeVpnGateways(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVPNGatewayIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.VpnGateways, nil -} - -func findVPNGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnGateway, error) { - input := &ec2.DescribeVpnGatewaysInput{ - VpnGatewayIds: []string{id}, - } - - output, err := findVPNGateway(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.VpnStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.VpnGatewayId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findCustomerGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCustomerGatewaysInput) (*awstypes.CustomerGateway, error) { - output, err := findCustomerGateways(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findCustomerGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeCustomerGatewaysInput) ([]awstypes.CustomerGateway, error) { - output, err := conn.DescribeCustomerGateways(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidCustomerGatewayIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.CustomerGateways, nil -} - -func findCustomerGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CustomerGateway, error) { - input := &ec2.DescribeCustomerGatewaysInput{ - CustomerGatewayIds: []string{id}, - } - - output, err := findCustomerGateway(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := aws.ToString(output.State); state == CustomerGatewayStateDeleted { - return nil, &retry.NotFoundError{ - Message: state, - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.CustomerGatewayId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAM(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamsInput) (*awstypes.Ipam, error) { - output, err := findIPAMs(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamsInput) ([]awstypes.Ipam, error) { - var output []awstypes.Ipam - - pages := ec2.NewDescribeIpamsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Ipams...) - } - - return output, nil -} - -func findIPAMByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Ipam, error) { - input := &ec2.DescribeIpamsInput{ - IpamIds: []string{id}, - } - - output, err := findIPAM(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.IpamStateDeleteComplete { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.IpamId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMPool(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamPoolsInput) (*awstypes.IpamPool, error) { - output, err := findIPAMPools(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMPools(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamPoolsInput) ([]awstypes.IpamPool, error) { - var output []awstypes.IpamPool - - pages := ec2.NewDescribeIpamPoolsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMPoolIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.IpamPools...) - } - - return output, nil -} - -func findIPAMPoolByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamPool, error) { - input := &ec2.DescribeIpamPoolsInput{ - IpamPoolIds: []string{id}, - } - - output, err := findIPAMPool(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.IpamPoolStateDeleteComplete { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.IpamPoolId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMPoolAllocation(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolAllocationsInput) (*awstypes.IpamPoolAllocation, error) { - output, err := findIPAMPoolAllocations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMPoolAllocations(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolAllocationsInput) ([]awstypes.IpamPoolAllocation, error) { - var output []awstypes.IpamPoolAllocation - - pages := ec2.NewGetIpamPoolAllocationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMPoolAllocationIdNotFound, errCodeInvalidIPAMPoolIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.IpamPoolAllocations...) - } - - return output, nil -} - -func findIPAMPoolAllocationByTwoPartKey(ctx context.Context, conn *ec2.Client, allocationID, poolID string) (*awstypes.IpamPoolAllocation, error) { - input := &ec2.GetIpamPoolAllocationsInput{ - IpamPoolAllocationId: aws.String(allocationID), - IpamPoolId: aws.String(poolID), - } - - output, err := findIPAMPoolAllocation(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.IpamPoolAllocationId) != allocationID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMPoolCIDR(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolCidrsInput) (*awstypes.IpamPoolCidr, error) { - output, err := findIPAMPoolCIDRs(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMPoolCIDRs(ctx context.Context, conn *ec2.Client, input *ec2.GetIpamPoolCidrsInput) ([]awstypes.IpamPoolCidr, error) { - var output []awstypes.IpamPoolCidr - - pages := ec2.NewGetIpamPoolCidrsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMPoolIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.IpamPoolCidrs...) - } - - return output, nil -} - -func findIPAMPoolCIDRByTwoPartKey(ctx context.Context, conn *ec2.Client, cidrBlock, poolID string) (*awstypes.IpamPoolCidr, error) { - input := &ec2.GetIpamPoolCidrsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "cidr": cidrBlock, - }), - IpamPoolId: aws.String(poolID), - } - - output, err := findIPAMPoolCIDR(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.IpamPoolCidrStateDeprovisioned { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.Cidr) != cidrBlock { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMPoolCIDRByPoolCIDRIDAndPoolID(ctx context.Context, conn *ec2.Client, poolCIDRID, poolID string) (*awstypes.IpamPoolCidr, error) { - input := &ec2.GetIpamPoolCidrsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "ipam-pool-cidr-id": poolCIDRID, - }), - IpamPoolId: aws.String(poolID), - } - - output, err := findIPAMPoolCIDR(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check - if aws.ToString(output.Cidr) == "" { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - if state := output.State; state == awstypes.IpamPoolCidrStateDeprovisioned { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMResourceDiscovery(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveriesInput) (*awstypes.IpamResourceDiscovery, error) { - output, err := findIPAMResourceDiscoveries(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMResourceDiscoveries(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveriesInput) ([]awstypes.IpamResourceDiscovery, error) { - var output []awstypes.IpamResourceDiscovery - - pages := ec2.NewDescribeIpamResourceDiscoveriesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMResourceDiscoveryIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.IpamResourceDiscoveries...) - } - - return output, nil -} - -func findIPAMResourceDiscoveryByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamResourceDiscovery, error) { - input := &ec2.DescribeIpamResourceDiscoveriesInput{ - IpamResourceDiscoveryIds: []string{id}, - } - - output, err := findIPAMResourceDiscovery(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.IpamResourceDiscoveryStateDeleteComplete { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.IpamResourceDiscoveryId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMResourceDiscoveryAssociation(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveryAssociationsInput) (*awstypes.IpamResourceDiscoveryAssociation, error) { - output, err := findIPAMResourceDiscoveryAssociations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMResourceDiscoveryAssociations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamResourceDiscoveryAssociationsInput) ([]awstypes.IpamResourceDiscoveryAssociation, error) { - var output []awstypes.IpamResourceDiscoveryAssociation - - pages := ec2.NewDescribeIpamResourceDiscoveryAssociationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMResourceDiscoveryAssociationIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.IpamResourceDiscoveryAssociations...) - } - - return output, nil -} - -func findIPAMResourceDiscoveryAssociationByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamResourceDiscoveryAssociation, error) { - input := &ec2.DescribeIpamResourceDiscoveryAssociationsInput{ - IpamResourceDiscoveryAssociationIds: []string{id}, - } - - output, err := findIPAMResourceDiscoveryAssociation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.IpamResourceDiscoveryAssociationStateDisassociateComplete { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.IpamResourceDiscoveryAssociationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findIPAMScope(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamScopesInput) (*awstypes.IpamScope, error) { - output, err := findIPAMScopes(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findIPAMScopes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeIpamScopesInput) ([]awstypes.IpamScope, error) { - var output []awstypes.IpamScope - - pages := ec2.NewDescribeIpamScopesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidIPAMScopeIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.IpamScopes...) - } - - return output, nil -} - -func findIPAMScopeByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.IpamScope, error) { - input := &ec2.DescribeIpamScopesInput{ - IpamScopeIds: []string{id}, - } - - output, err := findIPAMScope(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.IpamScopeStateDeleteComplete { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.IpamScopeId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findImages(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImagesInput) ([]awstypes.Image, error) { - var output []awstypes.Image - - pages := ec2.NewDescribeImagesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Images...) - } - - return output, nil -} - -func findImage(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImagesInput) (*awstypes.Image, error) { - output, err := findImages(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findImageByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Image, error) { - input := &ec2.DescribeImagesInput{ - ImageIds: []string{id}, - } - - output, err := findImage(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.ImageStateDeregistered { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.ImageId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findImageAttribute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImageAttributeInput) (*ec2.DescribeImageAttributeOutput, error) { - output, err := conn.DescribeImageAttribute(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidAMIIDNotFound, errCodeInvalidAMIIDUnavailable) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output, nil -} - -func findImageBlockPublicAccessState(ctx context.Context, conn *ec2.Client) (*string, error) { - input := &ec2.GetImageBlockPublicAccessStateInput{} - output, err := conn.GetImageBlockPublicAccessState(ctx, input) - - if err != nil { - return nil, err - } - - if output == nil || output.ImageBlockPublicAccessState == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.ImageBlockPublicAccessState, nil -} - -func findImageLaunchPermissionsByID(ctx context.Context, conn *ec2.Client, id string) ([]awstypes.LaunchPermission, error) { - input := &ec2.DescribeImageAttributeInput{ - Attribute: awstypes.ImageAttributeNameLaunchPermission, - ImageId: aws.String(id), - } - - output, err := findImageAttribute(ctx, conn, input) - - if err != nil { - return nil, err - } - - if len(output.LaunchPermissions) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.LaunchPermissions, nil -} - -func findImageLaunchPermission(ctx context.Context, conn *ec2.Client, imageID, accountID, group, organizationARN, organizationalUnitARN string) (*awstypes.LaunchPermission, error) { - output, err := findImageLaunchPermissionsByID(ctx, conn, imageID) - - if err != nil { - return nil, err - } - - for _, v := range output { - if (accountID != "" && aws.ToString(v.UserId) == accountID) || - (group != "" && string(v.Group) == group) || - (organizationARN != "" && aws.ToString(v.OrganizationArn) == organizationARN) || - (organizationalUnitARN != "" && aws.ToString(v.OrganizationalUnitArn) == organizationalUnitARN) { - return &v, nil - } - } - - return nil, &retry.NotFoundError{} -} - -func findTransitGateway(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewaysInput) (*awstypes.TransitGateway, error) { - output, err := findTransitGateways(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGateway) bool { return v.Options != nil }) -} - -func findTransitGateways(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewaysInput) ([]awstypes.TransitGateway, error) { - var output []awstypes.TransitGateway - - pages := ec2.NewDescribeTransitGatewaysPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGateways...) - } - - return output, nil -} - -func findTransitGatewayByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGateway, error) { - input := &ec2.DescribeTransitGatewaysInput{ - TransitGatewayIds: []string{id}, - } - - output, err := findTransitGateway(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayAttachment(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayAttachmentsInput) (*awstypes.TransitGatewayAttachment, error) { - output, err := findTransitGatewayAttachments(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayAttachments(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayAttachmentsInput) ([]awstypes.TransitGatewayAttachment, error) { - var output []awstypes.TransitGatewayAttachment - - pages := ec2.NewDescribeTransitGatewayAttachmentsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayAttachments...) - } - - return output, nil -} - -func findTransitGatewayAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayAttachment, error) { - input := &ec2.DescribeTransitGatewayAttachmentsInput{ - TransitGatewayAttachmentIds: []string{id}, - } - - output, err := findTransitGatewayAttachment(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayConnect(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectsInput) (*awstypes.TransitGatewayConnect, error) { - output, err := findTransitGatewayConnects(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayConnect) bool { return v.Options != nil }) -} - -func findTransitGatewayConnects(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectsInput) ([]awstypes.TransitGatewayConnect, error) { - var output []awstypes.TransitGatewayConnect - - pages := ec2.NewDescribeTransitGatewayConnectsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayConnects...) - } - - return output, nil -} - -func findTransitGatewayConnectByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayConnect, error) { - input := &ec2.DescribeTransitGatewayConnectsInput{ - TransitGatewayAttachmentIds: []string{id}, - } - - output, err := findTransitGatewayConnect(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayAttachmentStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayConnectPeer(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectPeersInput) (*awstypes.TransitGatewayConnectPeer, error) { - output, err := findTransitGatewayConnectPeers(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, - func(v *awstypes.TransitGatewayConnectPeer) bool { return v.ConnectPeerConfiguration != nil }, - func(v *awstypes.TransitGatewayConnectPeer) bool { - return len(v.ConnectPeerConfiguration.BgpConfigurations) > 0 - }, - ) -} - -func findTransitGatewayConnectPeers(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayConnectPeersInput) ([]awstypes.TransitGatewayConnectPeer, error) { - var output []awstypes.TransitGatewayConnectPeer - - pages := ec2.NewDescribeTransitGatewayConnectPeersPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayConnectPeerIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayConnectPeers...) - } - - return output, nil -} - -func findTransitGatewayConnectPeerByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayConnectPeer, error) { - input := &ec2.DescribeTransitGatewayConnectPeersInput{ - TransitGatewayConnectPeerIds: []string{id}, - } - - output, err := findTransitGatewayConnectPeer(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayConnectPeerStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayConnectPeerId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayMulticastDomain(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayMulticastDomainsInput) (*awstypes.TransitGatewayMulticastDomain, error) { - output, err := findTransitGatewayMulticastDomains(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayMulticastDomain) bool { return v.Options != nil }) -} - -func findTransitGatewayMulticastDomains(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayMulticastDomainsInput) ([]awstypes.TransitGatewayMulticastDomain, error) { - var output []awstypes.TransitGatewayMulticastDomain - - pages := ec2.NewDescribeTransitGatewayMulticastDomainsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayMulticastDomainIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayMulticastDomains...) - } - - return output, nil -} - -func findTransitGatewayMulticastDomainByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayMulticastDomain, error) { - input := &ec2.DescribeTransitGatewayMulticastDomainsInput{ - TransitGatewayMulticastDomainIds: []string{id}, - } - - output, err := findTransitGatewayMulticastDomain(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayMulticastDomainStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayMulticastDomainId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayMulticastDomainAssociation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayMulticastDomainAssociationsInput) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { - output, err := findTransitGatewayMulticastDomainAssociations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayMulticastDomainAssociation) bool { return v.Subnet != nil }) -} - -func findTransitGatewayMulticastDomainAssociations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayMulticastDomainAssociationsInput) ([]awstypes.TransitGatewayMulticastDomainAssociation, error) { - var output []awstypes.TransitGatewayMulticastDomainAssociation - - pages := ec2.NewGetTransitGatewayMulticastDomainAssociationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayMulticastDomainIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.MulticastDomainAssociations...) - } - - return output, nil -} - -func findTransitGatewayMulticastDomainAssociationByThreePartKey(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { - input := &ec2.GetTransitGatewayMulticastDomainAssociationsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "subnet-id": subnetID, - "transit-gateway-attachment-id": attachmentID, - }), - TransitGatewayMulticastDomainId: aws.String(multicastDomainID), - } - - output, err := findTransitGatewayMulticastDomainAssociation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.Subnet.State; state == awstypes.TransitGatewayMulitcastDomainAssociationStateDisassociated { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != attachmentID || aws.ToString(output.Subnet.SubnetId) != subnetID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayMulticastGroups(ctx context.Context, conn *ec2.Client, input *ec2.SearchTransitGatewayMulticastGroupsInput) ([]awstypes.TransitGatewayMulticastGroup, error) { - var output []awstypes.TransitGatewayMulticastGroup - - pages := ec2.NewSearchTransitGatewayMulticastGroupsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayMulticastDomainIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.MulticastGroups...) - } - - return output, nil -} - -func findTransitGatewayMulticastGroupMemberByThreePartKey(ctx context.Context, conn *ec2.Client, multicastDomainID, groupIPAddress, eniID string) (*awstypes.TransitGatewayMulticastGroup, error) { - input := &ec2.SearchTransitGatewayMulticastGroupsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "group-ip-address": groupIPAddress, - "is-group-member": "true", - "is-group-source": "false", - }), - TransitGatewayMulticastDomainId: aws.String(multicastDomainID), - } - - output, err := findTransitGatewayMulticastGroups(ctx, conn, input) - - if err != nil { - return nil, err - } - - if len(output) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - for _, v := range output { - if aws.ToString(v.NetworkInterfaceId) == eniID { - // Eventual consistency check. - if aws.ToString(v.GroupIpAddress) != groupIPAddress || !aws.ToBool(v.GroupMember) { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return &v, nil - } - } - - return nil, tfresource.NewEmptyResultError(input) -} - -func findTransitGatewayMulticastGroupSourceByThreePartKey(ctx context.Context, conn *ec2.Client, multicastDomainID, groupIPAddress, eniID string) (*awstypes.TransitGatewayMulticastGroup, error) { - input := &ec2.SearchTransitGatewayMulticastGroupsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "group-ip-address": groupIPAddress, - "is-group-member": "false", - "is-group-source": "true", - }), - TransitGatewayMulticastDomainId: aws.String(multicastDomainID), - } - - output, err := findTransitGatewayMulticastGroups(ctx, conn, input) - - if err != nil { - return nil, err - } - - if len(output) == 0 { - return nil, tfresource.NewEmptyResultError(input) - } - - for _, v := range output { - if aws.ToString(v.NetworkInterfaceId) == eniID { - // Eventual consistency check. - if aws.ToString(v.GroupIpAddress) != groupIPAddress || !aws.ToBool(v.GroupSource) { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return &v, nil - } - } - - return nil, tfresource.NewEmptyResultError(input) -} - -func findTransitGatewayPeeringAttachment(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPeeringAttachmentsInput) (*awstypes.TransitGatewayPeeringAttachment, error) { - output, err := findTransitGatewayPeeringAttachments(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, - func(v *awstypes.TransitGatewayPeeringAttachment) bool { return v.AccepterTgwInfo != nil }, - func(v *awstypes.TransitGatewayPeeringAttachment) bool { return v.RequesterTgwInfo != nil }, - ) -} - -func findTransitGatewayPeeringAttachments(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPeeringAttachmentsInput) ([]awstypes.TransitGatewayPeeringAttachment, error) { - var output []awstypes.TransitGatewayPeeringAttachment - - pages := ec2.NewDescribeTransitGatewayPeeringAttachmentsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayPeeringAttachments...) - } - - return output, nil -} - -func findTransitGatewayPeeringAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPeeringAttachment, error) { - input := &ec2.DescribeTransitGatewayPeeringAttachmentsInput{ - TransitGatewayAttachmentIds: []string{id}, - } - - output, err := findTransitGatewayPeeringAttachment(ctx, conn, input) - - if err != nil { - return nil, err - } - - // See https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#vpc-attachment-lifecycle. - switch state := output.State; state { - case awstypes.TransitGatewayAttachmentStateDeleted, - awstypes.TransitGatewayAttachmentStateFailed, - awstypes.TransitGatewayAttachmentStateRejected: - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayPrefixListReference(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPrefixListReferencesInput) (*awstypes.TransitGatewayPrefixListReference, error) { - output, err := findTransitGatewayPrefixListReferences(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayPrefixListReferences(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPrefixListReferencesInput) ([]awstypes.TransitGatewayPrefixListReference, error) { - var output []awstypes.TransitGatewayPrefixListReference - - pages := ec2.NewGetTransitGatewayPrefixListReferencesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayPrefixListReferences...) - } - - return output, nil -} - -func findTransitGatewayPrefixListReferenceByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { - input := &ec2.GetTransitGatewayPrefixListReferencesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "prefix-list-id": prefixListID, - }), - TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), - } - - output, err := findTransitGatewayPrefixListReference(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.PrefixListId) != prefixListID || aws.ToString(output.TransitGatewayRouteTableId) != transitGatewayRouteTableID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayStaticRoute(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) (*awstypes.TransitGatewayRoute, error) { - input := &ec2.SearchTransitGatewayRoutesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - names.AttrType: string(awstypes.TransitGatewayRouteTypeStatic), - "route-search.exact-match": destination, - }), - TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), - } - - output, err := findTransitGatewayRoutes(ctx, conn, input) - - if err != nil { - return nil, err - } - - for _, route := range output { - if v := aws.ToString(route.DestinationCidrBlock); types.CIDRBlocksEqual(v, destination) { - if state := route.State; state == awstypes.TransitGatewayRouteStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - route.DestinationCidrBlock = aws.String(types.CanonicalCIDRBlock(v)) - - return &route, nil - } - } - - return nil, &retry.NotFoundError{} -} - -func findTransitGatewayRoutes(ctx context.Context, conn *ec2.Client, input *ec2.SearchTransitGatewayRoutesInput) ([]awstypes.TransitGatewayRoute, error) { - output, err := conn.SearchTransitGatewayRoutes(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.Routes, err -} - -func findTransitGatewayPolicyTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPolicyTablesInput) (*awstypes.TransitGatewayPolicyTable, error) { - output, err := findTransitGatewayPolicyTables(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayRouteTable(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayRouteTablesInput) (*awstypes.TransitGatewayRouteTable, error) { - output, err := findTransitGatewayRouteTables(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayPolicyTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayPolicyTablesInput) ([]awstypes.TransitGatewayPolicyTable, error) { - var output []awstypes.TransitGatewayPolicyTable - - pages := ec2.NewDescribeTransitGatewayPolicyTablesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayPolicyTableIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayPolicyTables...) - } - - return output, nil -} - -func findTransitGatewayRouteTables(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayRouteTablesInput) ([]awstypes.TransitGatewayRouteTable, error) { - var output []awstypes.TransitGatewayRouteTable - - pages := ec2.NewDescribeTransitGatewayRouteTablesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayRouteTables...) - } - - return output, nil -} - -func findTransitGatewayPolicyTableByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPolicyTable, error) { - input := &ec2.DescribeTransitGatewayPolicyTablesInput{ - TransitGatewayPolicyTableIds: []string{id}, - } - - output, err := findTransitGatewayPolicyTable(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayPolicyTableId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayRouteTableByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayRouteTable, error) { - input := &ec2.DescribeTransitGatewayRouteTablesInput{ - TransitGatewayRouteTableIds: []string{id}, - } - - output, err := findTransitGatewayRouteTable(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayRouteTableStateDeleted { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayRouteTableId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTransitGatewayPolicyTableAssociationByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayPolicyTableAssociation, error) { - input := &ec2.GetTransitGatewayPolicyTableAssociationsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "transit-gateway-attachment-id": transitGatewayAttachmentID, - }), - TransitGatewayPolicyTableId: aws.String(transitGatewayPolicyTableID), - } - - output, err := findTransitGatewayPolicyTableAssociation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayAssociationStateDisassociated { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != transitGatewayAttachmentID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, err -} - -func findTransitGatewayRouteTableAssociationByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayRouteTableAssociation, error) { - input := &ec2.GetTransitGatewayRouteTableAssociationsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "transit-gateway-attachment-id": transitGatewayAttachmentID, - }), - TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), - } - - output, err := findTransitGatewayRouteTableAssociation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayAssociationStateDisassociated { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != transitGatewayAttachmentID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, err -} - -func findTransitGatewayRouteTableAssociation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTableAssociationsInput) (*awstypes.TransitGatewayRouteTableAssociation, error) { - output, err := findTransitGatewayRouteTableAssociations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayPolicyTableAssociations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPolicyTableAssociationsInput) ([]awstypes.TransitGatewayPolicyTableAssociation, error) { - var output []awstypes.TransitGatewayPolicyTableAssociation - - pages := ec2.NewGetTransitGatewayPolicyTableAssociationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayPolicyTableIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Associations...) - } - - return output, nil -} - -func findTransitGatewayPolicyTableAssociation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayPolicyTableAssociationsInput) (*awstypes.TransitGatewayPolicyTableAssociation, error) { - output, err := findTransitGatewayPolicyTableAssociations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayRouteTableAssociations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTableAssociationsInput) ([]awstypes.TransitGatewayRouteTableAssociation, error) { - var output []awstypes.TransitGatewayRouteTableAssociation - - pages := ec2.NewGetTransitGatewayRouteTableAssociationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.Associations...) - } - - return output, nil -} - -func findTransitGatewayRouteTablePropagationByTwoPartKey(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) (*awstypes.TransitGatewayRouteTablePropagation, error) { - input := &ec2.GetTransitGatewayRouteTablePropagationsInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "transit-gateway-attachment-id": transitGatewayAttachmentID, - }), - TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), - } - - output, err := findTransitGatewayRouteTablePropagation(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.TransitGatewayPropagationStateDisabled { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != transitGatewayAttachmentID { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, err -} - -func findTransitGatewayRouteTablePropagation(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTablePropagationsInput) (*awstypes.TransitGatewayRouteTablePropagation, error) { - output, err := findTransitGatewayRouteTablePropagations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTransitGatewayRouteTablePropagations(ctx context.Context, conn *ec2.Client, input *ec2.GetTransitGatewayRouteTablePropagationsInput) ([]awstypes.TransitGatewayRouteTablePropagation, error) { - var output []awstypes.TransitGatewayRouteTablePropagation - - pages := ec2.NewGetTransitGatewayRouteTablePropagationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayRouteTablePropagations...) - } - - return output, nil -} - -func findTransitGatewayVPCAttachment(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayVpcAttachmentsInput) (*awstypes.TransitGatewayVpcAttachment, error) { - output, err := findTransitGatewayVPCAttachments(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.TransitGatewayVpcAttachment) bool { return v.Options != nil }) -} - -func findTransitGatewayVPCAttachments(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTransitGatewayVpcAttachmentsInput) ([]awstypes.TransitGatewayVpcAttachment, error) { - var output []awstypes.TransitGatewayVpcAttachment - - pages := ec2.NewDescribeTransitGatewayVpcAttachmentsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTransitGatewayAttachmentIDNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TransitGatewayVpcAttachments...) - } - - return output, nil -} - -func findTransitGatewayVPCAttachmentByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { - input := &ec2.DescribeTransitGatewayVpcAttachmentsInput{ - TransitGatewayAttachmentIds: []string{id}, - } - - output, err := findTransitGatewayVPCAttachment(ctx, conn, input) - - if err != nil { - return nil, err - } - - // See https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#vpc-attachment-lifecycle. - switch state := output.State; state { - case awstypes.TransitGatewayAttachmentStateDeleted, - awstypes.TransitGatewayAttachmentStateFailed, - awstypes.TransitGatewayAttachmentStateRejected: - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.TransitGatewayAttachmentId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findEIPs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesInput) ([]awstypes.Address, error) { - output, err := conn.DescribeAddresses(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidAddressNotFound, errCodeInvalidAllocationIDNotFound) || - tfawserr.ErrMessageContains(err, errCodeAuthFailure, "does not belong to you") { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output.Addresses, nil -} - -func findEIP(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesInput) (*awstypes.Address, error) { - output, err := findEIPs(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findEIPByAllocationID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Address, error) { - input := &ec2.DescribeAddressesInput{ - AllocationIds: []string{id}, - } - - output, err := findEIP(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.AllocationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findEIPByAssociationID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Address, error) { - input := &ec2.DescribeAddressesInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "association-id": id, - }), - } - - output, err := findEIP(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.AssociationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findEIPAttributes(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesAttributeInput) ([]awstypes.AddressAttribute, error) { - var output []awstypes.AddressAttribute - - pages := ec2.NewDescribeAddressesAttributePaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.Addresses...) - } - - return output, nil -} - -func findEIPAttribute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAddressesAttributeInput) (*awstypes.AddressAttribute, error) { - output, err := findEIPAttributes(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findEIPDomainNameAttributeByAllocationID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.AddressAttribute, error) { - input := &ec2.DescribeAddressesAttributeInput{ - AllocationIds: []string{id}, - Attribute: awstypes.AddressAttributeNameDomainName, - } - - output, err := findEIPAttribute(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.AllocationId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findKeyPair(ctx context.Context, conn *ec2.Client, input *ec2.DescribeKeyPairsInput) (*awstypes.KeyPairInfo, error) { - output, err := findKeyPairs(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findKeyPairs(ctx context.Context, conn *ec2.Client, input *ec2.DescribeKeyPairsInput) ([]awstypes.KeyPairInfo, error) { - output, err := conn.DescribeKeyPairs(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidKeyPairNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - return output.KeyPairs, nil -} - -func findKeyPairByName(ctx context.Context, conn *ec2.Client, name string) (*awstypes.KeyPairInfo, error) { - input := &ec2.DescribeKeyPairsInput{ - KeyNames: []string{name}, - } - - output, err := findKeyPair(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.KeyName) != name { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findImportSnapshotTasks(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImportSnapshotTasksInput) ([]awstypes.ImportSnapshotTask, error) { - var output []awstypes.ImportSnapshotTask - - pages := ec2.NewDescribeImportSnapshotTasksPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidConversionTaskIdMalformed, "not found") { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.ImportSnapshotTasks...) - } - - return output, nil -} - -func findImportSnapshotTask(ctx context.Context, conn *ec2.Client, input *ec2.DescribeImportSnapshotTasksInput) (*awstypes.ImportSnapshotTask, error) { - output, err := findImportSnapshotTasks(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output, func(v *awstypes.ImportSnapshotTask) bool { return v.SnapshotTaskDetail != nil }) -} - -func findImportSnapshotTaskByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ImportSnapshotTask, error) { - input := &ec2.DescribeImportSnapshotTasksInput{ - ImportTaskIds: []string{id}, - } - - output, err := findImportSnapshotTask(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.ImportTaskId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findSnapshots(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotsInput) ([]awstypes.Snapshot, error) { - var output []awstypes.Snapshot - - pages := ec2.NewDescribeSnapshotsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - if tfawserr.ErrCodeEquals(err, errCodeInvalidSnapshotNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - return nil, err - } - - output = append(output, page.Snapshots...) - } - - return output, nil -} - -func findSnapshot(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotsInput) (*awstypes.Snapshot, error) { - output, err := findSnapshots(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findSnapshotByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Snapshot, error) { - input := &ec2.DescribeSnapshotsInput{ - SnapshotIds: []string{id}, - } - - output, err := findSnapshot(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.SnapshotId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findSnapshotAttribute(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotAttributeInput) (*ec2.DescribeSnapshotAttributeOutput, error) { - output, err := conn.DescribeSnapshotAttribute(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidSnapshotNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output, nil -} - -func findCreateSnapshotCreateVolumePermissionByTwoPartKey(ctx context.Context, conn *ec2.Client, snapshotID, accountID string) (awstypes.CreateVolumePermission, error) { - input := &ec2.DescribeSnapshotAttributeInput{ - Attribute: awstypes.SnapshotAttributeNameCreateVolumePermission, - SnapshotId: aws.String(snapshotID), - } - - output, err := findSnapshotAttribute(ctx, conn, input) - - if err != nil { - return awstypes.CreateVolumePermission{}, err - } - - for _, v := range output.CreateVolumePermissions { - if aws.ToString(v.UserId) == accountID { - return v, nil - } - } - - return awstypes.CreateVolumePermission{}, &retry.NotFoundError{LastRequest: input} -} - -func findFindSnapshotTierStatuses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotTierStatusInput) ([]awstypes.SnapshotTierStatus, error) { - var output []awstypes.SnapshotTierStatus - - pages := ec2.NewDescribeSnapshotTierStatusPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.SnapshotTierStatuses...) - } - - return output, nil -} - -func findFindSnapshotTierStatus(ctx context.Context, conn *ec2.Client, input *ec2.DescribeSnapshotTierStatusInput) (*awstypes.SnapshotTierStatus, error) { - output, err := findFindSnapshotTierStatuses(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findSnapshotTierStatusBySnapshotID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SnapshotTierStatus, error) { - input := &ec2.DescribeSnapshotTierStatusInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "snapshot-id": id, - }), - } - - output, err := findFindSnapshotTierStatus(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.SnapshotId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findNetworkPerformanceMetricSubscriptions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeAwsNetworkPerformanceMetricSubscriptionsInput) ([]awstypes.Subscription, error) { - var output []awstypes.Subscription - - pages := ec2.NewDescribeAwsNetworkPerformanceMetricSubscriptionsPaginator(conn, input, func(o *ec2.DescribeAwsNetworkPerformanceMetricSubscriptionsPaginatorOptions) { - o.Limit = 100 - }) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.Subscriptions...) - } - - return output, nil -} - -func findNetworkPerformanceMetricSubscriptionByFourPartKey(ctx context.Context, conn *ec2.Client, source, destination, metric, statistic string) (*awstypes.Subscription, error) { - input := &ec2.DescribeAwsNetworkPerformanceMetricSubscriptionsInput{} - - output, err := findNetworkPerformanceMetricSubscriptions(ctx, conn, input) - - if err != nil { - return nil, err - } - - for _, v := range output { - if aws.ToString(v.Source) == source && aws.ToString(v.Destination) == destination && string(v.Metric) == metric && string(v.Statistic) == statistic { - return &v, nil - } - } - - return nil, &retry.NotFoundError{} -} - -func findInstanceConnectEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceConnectEndpointsInput) (*awstypes.Ec2InstanceConnectEndpoint, error) { - output, err := findInstanceConnectEndpoints(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findInstanceConnectEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeInstanceConnectEndpointsInput) ([]awstypes.Ec2InstanceConnectEndpoint, error) { - var output []awstypes.Ec2InstanceConnectEndpoint - - pages := ec2.NewDescribeInstanceConnectEndpointsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidInstanceConnectEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.InstanceConnectEndpoints...) - } - - return output, nil -} - -func findInstanceConnectEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Ec2InstanceConnectEndpoint, error) { - input := &ec2.DescribeInstanceConnectEndpointsInput{ - InstanceConnectEndpointIds: []string{id}, - } - output, err := findInstanceConnectEndpoint(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.Ec2InstanceConnectEndpointStateDeleteComplete { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.InstanceConnectEndpointId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVerifiedAccessGroupPolicyByID(ctx context.Context, conn *ec2.Client, id string) (*ec2.GetVerifiedAccessGroupPolicyOutput, error) { - input := &ec2.GetVerifiedAccessGroupPolicyInput{ - VerifiedAccessGroupId: &id, - } - output, err := conn.GetVerifiedAccessGroupPolicy(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessGroupIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output, nil -} - -func findVerifiedAccessEndpointPolicyByID(ctx context.Context, conn *ec2.Client, id string) (*ec2.GetVerifiedAccessEndpointPolicyOutput, error) { - input := &ec2.GetVerifiedAccessEndpointPolicyInput{ - VerifiedAccessEndpointId: &id, - } - output, err := conn.GetVerifiedAccessEndpointPolicy(ctx, input) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - if output == nil { - return nil, tfresource.NewEmptyResultError(input) - } - - return output, nil -} - -func findVerifiedAccessGroup(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessGroupsInput) (*awstypes.VerifiedAccessGroup, error) { - output, err := findVerifiedAccessGroups(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVerifiedAccessGroups(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessGroupsInput) ([]awstypes.VerifiedAccessGroup, error) { - var output []awstypes.VerifiedAccessGroup - - pages := ec2.NewDescribeVerifiedAccessGroupsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessGroupIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.VerifiedAccessGroups...) - } - - return output, nil -} - -func findVerifiedAccessGroupByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessGroup, error) { - input := &ec2.DescribeVerifiedAccessGroupsInput{ - VerifiedAccessGroupIds: []string{id}, - } - output, err := findVerifiedAccessGroup(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.VerifiedAccessGroupId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVerifiedAccessInstance(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstancesInput) (*awstypes.VerifiedAccessInstance, error) { - output, err := findVerifiedAccessInstances(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVerifiedAccessInstances(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstancesInput) ([]awstypes.VerifiedAccessInstance, error) { - var output []awstypes.VerifiedAccessInstance - - pages := ec2.NewDescribeVerifiedAccessInstancesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessInstanceIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.VerifiedAccessInstances...) - } - - return output, nil -} - -func findVerifiedAccessInstanceByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessInstance, error) { - input := &ec2.DescribeVerifiedAccessInstancesInput{ - VerifiedAccessInstanceIds: []string{id}, - } - output, err := findVerifiedAccessInstance(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.VerifiedAccessInstanceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVerifiedAccessInstanceLoggingConfiguration(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstanceLoggingConfigurationsInput) (*awstypes.VerifiedAccessInstanceLoggingConfiguration, error) { - output, err := findVerifiedAccessInstanceLoggingConfigurations(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVerifiedAccessInstanceLoggingConfigurations(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessInstanceLoggingConfigurationsInput) ([]awstypes.VerifiedAccessInstanceLoggingConfiguration, error) { - var output []awstypes.VerifiedAccessInstanceLoggingConfiguration - - pages := ec2.NewDescribeVerifiedAccessInstanceLoggingConfigurationsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessInstanceIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.LoggingConfigurations...) - } - - return output, nil -} - -func findVerifiedAccessInstanceLoggingConfigurationByInstanceID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessInstanceLoggingConfiguration, error) { - input := &ec2.DescribeVerifiedAccessInstanceLoggingConfigurationsInput{ - VerifiedAccessInstanceIds: []string{id}, - } - output, err := findVerifiedAccessInstanceLoggingConfiguration(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.VerifiedAccessInstanceId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVerifiedAccessInstanceTrustProviderAttachmentExists(ctx context.Context, conn *ec2.Client, vaiID, vatpID string) error { - output, err := findVerifiedAccessInstanceByID(ctx, conn, vaiID) - - if err != nil { - return err - } - - for _, v := range output.VerifiedAccessTrustProviders { - if aws.ToString(v.VerifiedAccessTrustProviderId) == vatpID { - return nil - } - } - - return &retry.NotFoundError{ - LastError: fmt.Errorf("Verified Access Instance (%s) Trust Provider (%s) Attachment not found", vaiID, vatpID), - } -} - -func findVerifiedAccessTrustProvider(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessTrustProvidersInput) (*awstypes.VerifiedAccessTrustProvider, error) { - output, err := findVerifiedAccessTrustProviders(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVerifiedAccessTrustProviders(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessTrustProvidersInput) ([]awstypes.VerifiedAccessTrustProvider, error) { - var output []awstypes.VerifiedAccessTrustProvider - - pages := ec2.NewDescribeVerifiedAccessTrustProvidersPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessTrustProviderIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.VerifiedAccessTrustProviders...) - } - - return output, nil -} - -func findVerifiedAccessTrustProviderByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessTrustProvider, error) { - input := &ec2.DescribeVerifiedAccessTrustProvidersInput{ - VerifiedAccessTrustProviderIds: []string{id}, - } - output, err := findVerifiedAccessTrustProvider(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.VerifiedAccessTrustProviderId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findVerifiedAccessEndpoint(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessEndpointsInput) (*awstypes.VerifiedAccessEndpoint, error) { - output, err := findVerifiedAccessEndpoints(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findVerifiedAccessEndpoints(ctx context.Context, conn *ec2.Client, input *ec2.DescribeVerifiedAccessEndpointsInput) ([]awstypes.VerifiedAccessEndpoint, error) { - var output []awstypes.VerifiedAccessEndpoint - - pages := ec2.NewDescribeVerifiedAccessEndpointsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidVerifiedAccessEndpointIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.VerifiedAccessEndpoints...) - } - - return output, nil -} - -func findVerifiedAccessEndpointByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VerifiedAccessEndpoint, error) { - input := &ec2.DescribeVerifiedAccessEndpointsInput{ - VerifiedAccessEndpointIds: []string{id}, - } - output, err := findVerifiedAccessEndpoint(ctx, conn, input) - - if err != nil { - return nil, err - } - - if status := output.Status; status != nil && status.Code == awstypes.VerifiedAccessEndpointStatusCodeDeleted { - return nil, &retry.NotFoundError{ - Message: string(status.Code), - LastRequest: input, - } - } - - // Eventual consistency check. - if aws.ToString(output.VerifiedAccessEndpointId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findFastSnapshotRestore(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFastSnapshotRestoresInput) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { - output, err := findFastSnapshotRestores(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findFastSnapshotRestores(ctx context.Context, conn *ec2.Client, input *ec2.DescribeFastSnapshotRestoresInput) ([]awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { - var output []awstypes.DescribeFastSnapshotRestoreSuccessItem - - pages := ec2.NewDescribeFastSnapshotRestoresPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if err != nil { - return nil, err - } - - output = append(output, page.FastSnapshotRestores...) - } - - return output, nil -} - -func findFastSnapshotRestoreByTwoPartKey(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { - input := &ec2.DescribeFastSnapshotRestoresInput{ - Filters: newAttributeFilterListV2(map[string]string{ - "availability-zone": availabilityZone, - "snapshot-id": snapshotID, - }), - } - - output, err := findFastSnapshotRestore(ctx, conn, input) - - if err != nil { - return nil, err - } - - if state := output.State; state == awstypes.FastSnapshotRestoreStateCodeDisabled { - return nil, &retry.NotFoundError{ - Message: string(state), - LastRequest: input, - } - } - - return output, nil -} - -func findTrafficMirrorFilter(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorFiltersInput) (*awstypes.TrafficMirrorFilter, error) { - output, err := findTrafficMirrorFilters(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTrafficMirrorFilters(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorFiltersInput) ([]awstypes.TrafficMirrorFilter, error) { - var output []awstypes.TrafficMirrorFilter - - pages := ec2.NewDescribeTrafficMirrorFiltersPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTrafficMirrorFilterIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TrafficMirrorFilters...) - } - - return output, nil -} - -func findTrafficMirrorFilterByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TrafficMirrorFilter, error) { - input := &ec2.DescribeTrafficMirrorFiltersInput{ - TrafficMirrorFilterIds: []string{id}, - } - - output, err := findTrafficMirrorFilter(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.TrafficMirrorFilterId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTrafficMirrorFilterRuleByTwoPartKey(ctx context.Context, conn *ec2.Client, filterID, ruleID string) (*awstypes.TrafficMirrorFilterRule, error) { - output, err := findTrafficMirrorFilterByID(ctx, conn, filterID) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(tfslices.Filter(slices.Concat(output.IngressFilterRules, output.EgressFilterRules), func(v awstypes.TrafficMirrorFilterRule) bool { - return aws.ToString(v.TrafficMirrorFilterRuleId) == ruleID - })) -} - -func findTrafficMirrorSession(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorSessionsInput) (*awstypes.TrafficMirrorSession, error) { - output, err := findTrafficMirrorSessions(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTrafficMirrorSessions(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorSessionsInput) ([]awstypes.TrafficMirrorSession, error) { - var output []awstypes.TrafficMirrorSession - - pages := ec2.NewDescribeTrafficMirrorSessionsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTrafficMirrorSessionIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TrafficMirrorSessions...) - } - - return output, nil -} - -func findTrafficMirrorSessionByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TrafficMirrorSession, error) { - input := &ec2.DescribeTrafficMirrorSessionsInput{ - TrafficMirrorSessionIds: []string{id}, - } - - output, err := findTrafficMirrorSession(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.TrafficMirrorSessionId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findTrafficMirrorTarget(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorTargetsInput) (*awstypes.TrafficMirrorTarget, error) { - output, err := findTrafficMirrorTargets(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findTrafficMirrorTargets(ctx context.Context, conn *ec2.Client, input *ec2.DescribeTrafficMirrorTargetsInput) ([]awstypes.TrafficMirrorTarget, error) { - var output []awstypes.TrafficMirrorTarget - - pages := ec2.NewDescribeTrafficMirrorTargetsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidTrafficMirrorTargetIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.TrafficMirrorTargets...) - } - - return output, nil -} - -func findTrafficMirrorTargetByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TrafficMirrorTarget, error) { - input := &ec2.DescribeTrafficMirrorTargetsInput{ - TrafficMirrorTargetIds: []string{id}, - } - - output, err := findTrafficMirrorTarget(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.TrafficMirrorTargetId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findNetworkInsightsPath(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsPathsInput) (*awstypes.NetworkInsightsPath, error) { - output, err := findNetworkInsightsPaths(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findNetworkInsightsAnalysis(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsAnalysesInput) (*awstypes.NetworkInsightsAnalysis, error) { - output, err := findNetworkInsightsAnalyses(ctx, conn, input) - - if err != nil { - return nil, err - } - - return tfresource.AssertSingleValueResult(output) -} - -func findNetworkInsightsAnalyses(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsAnalysesInput) ([]awstypes.NetworkInsightsAnalysis, error) { - var output []awstypes.NetworkInsightsAnalysis - - pages := ec2.NewDescribeNetworkInsightsAnalysesPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInsightsAnalysisIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.NetworkInsightsAnalyses...) - } - - return output, nil -} - -func findNetworkInsightsAnalysisByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInsightsAnalysis, error) { - input := &ec2.DescribeNetworkInsightsAnalysesInput{ - NetworkInsightsAnalysisIds: []string{id}, - } - - output, err := findNetworkInsightsAnalysis(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.NetworkInsightsAnalysisId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} - -func findNetworkInsightsPaths(ctx context.Context, conn *ec2.Client, input *ec2.DescribeNetworkInsightsPathsInput) ([]awstypes.NetworkInsightsPath, error) { - var output []awstypes.NetworkInsightsPath - - pages := ec2.NewDescribeNetworkInsightsPathsPaginator(conn, input) - for pages.HasMorePages() { - page, err := pages.NextPage(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInsightsPathIdNotFound) { - return nil, &retry.NotFoundError{ - LastError: err, - LastRequest: input, - } - } - - if err != nil { - return nil, err - } - - output = append(output, page.NetworkInsightsPaths...) - } - - return output, nil -} - -func findNetworkInsightsPathByID(ctx context.Context, conn *ec2.Client, id string) (*awstypes.NetworkInsightsPath, error) { - input := &ec2.DescribeNetworkInsightsPathsInput{ - NetworkInsightsPathIds: []string{id}, - } - - output, err := findNetworkInsightsPath(ctx, conn, input) - - if err != nil { - return nil, err - } - - // Eventual consistency check. - if aws.ToString(output.NetworkInsightsPathId) != id { - return nil, &retry.NotFoundError{ - LastRequest: input, - } - } - - return output, nil -} diff --git a/internal/service/ec2/generate.go b/internal/service/ec2/generate.go index afe46e2e75a..d680cd11280 100644 --- a/internal/service/ec2/generate.go +++ b/internal/service/ec2/generate.go @@ -1,10 +1,9 @@ // Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 -//go:generate go run ../../generate/tagresource/main.go -IDAttribName=resource_id -UpdateTagsFunc=updateTagsV2 -//go:generate go run ../../generate/tags/main.go -ListTags -ListTagsOp=DescribeTags -ListTagsOpPaginated -ListTagsInFiltIDName=resource-id -ListTagsInIDElem=Resources -ServiceTagsSlice -TagOp=CreateTags -TagInIDElem=Resources -TagInIDNeedSlice=yes -TagType2=TagDescription -UntagOp=DeleteTags -UntagInNeedTagType -UntagInTagsElem=Tags -UpdateTags -//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -GetTag -ListTagsOp=DescribeTags -ListTagsOpPaginated -ListTagsInFiltIDName=resource-id -ServiceTagsSlice -TagsFunc=TagsV2 -KeyValueTagsFunc=keyValueTagsV2 -GetTagsInFunc=getTagsInV2 -SetTagsOutFunc=setTagsOutV2 -TagOp=CreateTags -TagInIDElem=Resources -TagInIDNeedValueSlice=yes -TagType2=TagDescription -UntagOp=DeleteTags -UpdateTagsFunc=updateTagsV2 -UntagInNeedTagType -UntagInTagsElem=Tags -UpdateTags -- tagsv2_gen.go -//go:generate go run ../../generate/listpages/main.go -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory,DescribeVpcEndpointServices -AWSSDKVersion=2 +//go:generate go run ../../generate/tagresource/main.go -IDAttribName=resource_id +//go:generate go run ../../generate/tags/main.go -AWSSDKVersion=2 -GetTag -ListTags -ListTagsOp=DescribeTags -ListTagsOpPaginated -ListTagsInFiltIDName=resource-id -ServiceTagsSlice -KeyValueTagsFunc=keyValueTags -TagOp=CreateTags -TagInIDElem=Resources -TagInIDNeedValueSlice=yes -TagType2=TagDescription -UntagOp=DeleteTags -UntagInNeedTagType -UntagInTagsElem=Tags -UpdateTags +//go:generate go run ../../generate/listpages/main.go -AWSSDKVersion=2 -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory,DescribeVpcEndpointServices //go:generate go run ../../generate/servicepackage/main.go //go:generate go run ../../generate/tagstests/main.go // ONLY generate directives and package declaration! Do not add anything else to this file. diff --git a/internal/service/ec2/id.go b/internal/service/ec2/id.go index 270ebb08259..f5e32f4c56a 100644 --- a/internal/service/ec2/id.go +++ b/internal/service/ec2/id.go @@ -10,36 +10,36 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/create" ) -// RouteCreateID returns a route resource ID. -func RouteCreateID(routeTableID, destination string) string { +// routeCreateID returns a route resource ID. +func routeCreateID(routeTableID, destination string) string { return fmt.Sprintf("r-%s%d", routeTableID, create.StringHashcode(destination)) } -func VPCEndpointRouteTableAssociationCreateID(vpcEndpointID, routeTableID string) string { +func vpcEndpointRouteTableAssociationCreateID(vpcEndpointID, routeTableID string) string { return fmt.Sprintf("a-%s%d", vpcEndpointID, create.StringHashcode(routeTableID)) } -func VPCEndpointSecurityGroupAssociationCreateID(vpcEndpointID, securityGroupID string) string { +func vpcEndpointSecurityGroupAssociationCreateID(vpcEndpointID, securityGroupID string) string { return fmt.Sprintf("a-%s%d", vpcEndpointID, create.StringHashcode(securityGroupID)) } -func VPCEndpointSubnetAssociationCreateID(vpcEndpointID, subnetID string) string { +func vpcEndpointSubnetAssociationCreateID(vpcEndpointID, subnetID string) string { return fmt.Sprintf("a-%s%d", vpcEndpointID, create.StringHashcode(subnetID)) } -func VPNGatewayVPCAttachmentCreateID(vpnGatewayID, vpcID string) string { +func vpnGatewayVPCAttachmentCreateID(vpnGatewayID, vpcID string) string { return fmt.Sprintf("vpn-attachment-%x", create.StringHashcode(fmt.Sprintf("%s-%s", vpcID, vpnGatewayID))) } const vpnGatewayRoutePropagationIDSeparator = "_" -func VPNGatewayRoutePropagationCreateID(routeTableID, gatewayID string) string { +func vpnGatewayRoutePropagationCreateID(routeTableID, gatewayID string) string { parts := []string{gatewayID, routeTableID} id := strings.Join(parts, vpnGatewayRoutePropagationIDSeparator) return id } -func VPNGatewayRoutePropagationParseID(id string) (string, string, error) { +func vpnGatewayRoutePropagationParseID(id string) (string, string, error) { parts := strings.Split(id, vpnGatewayRoutePropagationIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { return parts[1], parts[0], nil diff --git a/internal/service/ec2/ipam_.go b/internal/service/ec2/ipam_.go index cb4d2092af7..3bb1ea5aeb7 100644 --- a/internal/service/ec2/ipam_.go +++ b/internal/service/ec2/ipam_.go @@ -130,7 +130,7 @@ func resourceIPAMCreate(ctx context.Context, d *schema.ResourceData, meta interf input := &ec2.CreateIpamInput{ ClientToken: aws.String(id.UniqueId()), OperatingRegions: expandIPAMOperatingRegions(d.Get("operating_regions").(*schema.Set).List()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeIpam), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeIpam), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -184,7 +184,7 @@ func resourceIPAMRead(ctx context.Context, d *schema.ResourceData, meta interfac d.Set("scope_count", ipam.ScopeCount) d.Set("tier", ipam.Tier) - setTagsOutV2(ctx, ipam.Tags) + setTagsOut(ctx, ipam.Tags) return diags } @@ -240,7 +240,7 @@ func resourceIPAMUpdate(ctx context.Context, d *schema.ResourceData, meta interf } } - return diags + return append(diags, resourceIPAMRead(ctx, d, meta)...) } func resourceIPAMDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { diff --git a/internal/service/ec2/ipam_byoip_test.go b/internal/service/ec2/ipam_byoip_test.go index 6e288687b8d..905cc8285c8 100644 --- a/internal/service/ec2/ipam_byoip_test.go +++ b/internal/service/ec2/ipam_byoip_test.go @@ -61,7 +61,7 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { { Config: testAccIPAMBYOIPConfig_ipv4IPv6DefaultNetmask(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), acctest.MatchResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", regexache.MustCompile(`vpc/vpc-.+`)), resource.TestCheckNoResourceAttr(resourceName, "ipv6_netmask_length"), resource.TestMatchResourceAttr(resourceName, "ipv6_association_id", regexache.MustCompile(`^vpc-cidr-assoc-.+`)), @@ -72,13 +72,13 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { Config: testAccIPAMBYOIPConfig_ipv6ExplicitNetmask(p, m, s, netmaskLength), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), acctest.MatchResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", regexache.MustCompile(`vpc/vpc-.+`)), resource.TestCheckResourceAttr(resourceName, "ipv6_netmask_length", strconv.Itoa(netmaskLength)), resource.TestMatchResourceAttr(resourceName, "ipv6_association_id", regexache.MustCompile(`^vpc-cidr-assoc-.+`)), @@ -89,14 +89,14 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { Config: testAccIPAMBYOIPConfig_ipv6ExplicitCIDR(p, m, s, ipv6CidrVPC), SkipFunc: testAccIPAMConfig_ipv6BYOIPSkipExplicitCIDR(t, ipv6CidrVPC), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), acctest.MatchResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", regexache.MustCompile(`vpc/vpc-.+`)), resource.TestMatchResourceAttr(resourceName, "ipv6_association_id", regexache.MustCompile(`^vpc-cidr-assoc-.+`)), resource.TestCheckResourceAttr(resourceName, "ipv6_cidr_block", ipv6CidrVPC), @@ -107,14 +107,14 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), SkipFunc: testAccIPAMConfig_ipv6BYOIPSkipExplicitCIDR(t, ipv6CidrVPC), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, // aws_vpc_ipv6_cidr_block_association { Config: testAccIPAMBYOIPConfig_ipv6CIDRBlockAssociationDefaultNetmask(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), testAccCheckVPCIPv6CIDRBlockAssociationExists(ctx, assocName, &associationIPv6), testAccCheckVPCAssociationIPv6CIDRPrefix(&associationIPv6, strconv.Itoa(netmaskLength)), ), @@ -123,13 +123,13 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc)), + acctest.CheckVPCExists(ctx, resourceName, &vpc)), // vpc will still have association id because its based on the aws_vpc_ipv6_cidr_block_association resource }, { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { @@ -143,13 +143,13 @@ func TestAccIPAM_byoipIPv6(t *testing.T) { { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc)), + acctest.CheckVPCExists(ctx, resourceName, &vpc)), // vpc will still have association id because its based on the aws_vpc_ipv6_cidr_block_association resource }, { Config: testAccIPAMBYOIPConfig_ipv6CIDRBase(p, m, s), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", "")), }, { diff --git a/internal/service/ec2/ipam_pool.go b/internal/service/ec2/ipam_pool.go index a39a1101342..3266ea2fc83 100644 --- a/internal/service/ec2/ipam_pool.go +++ b/internal/service/ec2/ipam_pool.go @@ -158,7 +158,7 @@ func resourceIPAMPoolCreate(ctx context.Context, d *schema.ResourceData, meta in AddressFamily: addressFamily, ClientToken: aws.String(id.UniqueId()), IpamScopeId: aws.String(d.Get("ipam_scope_id").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeIpamPool), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeIpamPool), } if v, ok := d.GetOk("allocation_default_netmask_length"); ok { @@ -241,7 +241,7 @@ func resourceIPAMPoolRead(ctx context.Context, d *schema.ResourceData, meta inte } d.Set("address_family", pool.AddressFamily) - d.Set("allocation_resource_tags", keyValueTagsV2(ctx, tagsFromIPAMAllocationTags(pool.AllocationResourceTags)).Map()) + d.Set("allocation_resource_tags", keyValueTags(ctx, tagsFromIPAMAllocationTags(pool.AllocationResourceTags)).Map()) d.Set(names.AttrARN, pool.IpamPoolArn) d.Set("auto_import", pool.AutoImport) d.Set("aws_service", pool.AwsService) @@ -256,7 +256,7 @@ func resourceIPAMPoolRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set("source_ipam_pool_id", pool.SourceIpamPoolId) d.Set(names.AttrState, pool.State) - setTagsOutV2(ctx, pool.Tags) + setTagsOut(ctx, pool.Tags) return diags } diff --git a/internal/service/ec2/ipam_pool_cidr.go b/internal/service/ec2/ipam_pool_cidr.go index fc5fdfd9202..9454465679f 100644 --- a/internal/service/ec2/ipam_pool_cidr.go +++ b/internal/service/ec2/ipam_pool_cidr.go @@ -119,14 +119,14 @@ func resourceIPAMPoolCIDRCreate(ctx context.Context, d *schema.ResourceData, met input.Cidr = aws.String(v.(string)) } - if v, ok := d.GetOk("netmask_length"); ok { - input.NetmaskLength = aws.Int32(int32(v.(int))) - } - if v, ok := d.GetOk("cidr_authorization_context"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { input.CidrAuthorizationContext = expandIPAMCIDRAuthorizationContext(v.([]interface{})[0].(map[string]interface{})) } + if v, ok := d.GetOk("netmask_length"); ok { + input.NetmaskLength = aws.Int32(int32(v.(int))) + } + output, err := conn.ProvisionIpamPoolCidr(ctx, input) if err != nil { @@ -145,7 +145,7 @@ func resourceIPAMPoolCIDRCreate(ctx context.Context, d *schema.ResourceData, met // This resource's ID is a concatenated id of `_` // ipam_pool_cidr_id was not part of the initial feature release - d.SetId(IPAMPoolCIDRCreateResourceID(aws.ToString(ipamPoolCidr.Cidr), poolID)) + d.SetId(ipamPoolCIDRCreateResourceID(aws.ToString(ipamPoolCidr.Cidr), poolID)) return append(diags, resourceIPAMPoolCIDRRead(ctx, d, meta)...) } @@ -154,8 +154,7 @@ func resourceIPAMPoolCIDRRead(ctx context.Context, d *schema.ResourceData, meta var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - cidrBlock, poolID, err := IPAMPoolCIDRParseResourceID(d.Id()) - + cidrBlock, poolID, err := ipamPoolCIDRParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -183,8 +182,7 @@ func resourceIPAMPoolCIDRDelete(ctx context.Context, d *schema.ResourceData, met var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - cidrBlock, poolID, err := IPAMPoolCIDRParseResourceID(d.Id()) - + cidrBlock, poolID, err := ipamPoolCIDRParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -213,14 +211,14 @@ func resourceIPAMPoolCIDRDelete(ctx context.Context, d *schema.ResourceData, met const ipamPoolCIDRIDSeparator = "_" -func IPAMPoolCIDRCreateResourceID(cidrBlock, poolID string) string { +func ipamPoolCIDRCreateResourceID(cidrBlock, poolID string) string { parts := []string{cidrBlock, poolID} id := strings.Join(parts, ipamPoolCIDRIDSeparator) return id } -func IPAMPoolCIDRParseResourceID(id string) (string, string, error) { +func ipamPoolCIDRParseResourceID(id string) (string, string, error) { parts := strings.Split(id, ipamPoolCIDRIDSeparator) if len(parts) != 2 || parts[0] == "" || parts[1] == "" { diff --git a/internal/service/ec2/ipam_pool_cidr_allocation.go b/internal/service/ec2/ipam_pool_cidr_allocation.go index cd7a718d2c0..207df9925a6 100644 --- a/internal/service/ec2/ipam_pool_cidr_allocation.go +++ b/internal/service/ec2/ipam_pool_cidr_allocation.go @@ -130,7 +130,7 @@ func resourceIPAMPoolCIDRAllocationCreate(ctx context.Context, d *schema.Resourc } allocationID := aws.ToString(output.IpamPoolAllocation.IpamPoolAllocationId) - d.SetId(IPAMPoolCIDRAllocationCreateResourceID(allocationID, ipamPoolID)) + d.SetId(ipamPoolCIDRAllocationCreateResourceID(allocationID, ipamPoolID)) _, err = tfresource.RetryWhenNotFound(ctx, d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { return findIPAMPoolAllocationByTwoPartKey(ctx, conn, allocationID, ipamPoolID) @@ -147,8 +147,7 @@ func resourceIPAMPoolCIDRAllocationRead(ctx context.Context, d *schema.ResourceD var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - allocationID, poolID, err := IPAMPoolCIDRAllocationParseResourceID(d.Id()) - + allocationID, poolID, err := ipamPoolCIDRAllocationParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -179,8 +178,7 @@ func resourceIPAMPoolCIDRAllocationDelete(ctx context.Context, d *schema.Resourc var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - allocationID, poolID, err := IPAMPoolCIDRAllocationParseResourceID(d.Id()) - + allocationID, poolID, err := ipamPoolCIDRAllocationParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -205,14 +203,14 @@ func resourceIPAMPoolCIDRAllocationDelete(ctx context.Context, d *schema.Resourc const ipamPoolCIDRAllocationIDSeparator = "_" -func IPAMPoolCIDRAllocationCreateResourceID(allocationID, poolID string) string { +func ipamPoolCIDRAllocationCreateResourceID(allocationID, poolID string) string { parts := []string{allocationID, poolID} id := strings.Join(parts, ipamPoolCIDRAllocationIDSeparator) return id } -func IPAMPoolCIDRAllocationParseResourceID(id string) (string, string, error) { +func ipamPoolCIDRAllocationParseResourceID(id string) (string, string, error) { parts := strings.Split(id, ipamPoolCIDRAllocationIDSeparator) if len(parts) != 2 || parts[0] == "" || parts[1] == "" { diff --git a/internal/service/ec2/ipam_pool_cidr_allocation_test.go b/internal/service/ec2/ipam_pool_cidr_allocation_test.go index 86d303e0f6a..7f5ebdbf46c 100644 --- a/internal/service/ec2/ipam_pool_cidr_allocation_test.go +++ b/internal/service/ec2/ipam_pool_cidr_allocation_test.go @@ -231,19 +231,9 @@ func testAccCheckIPAMPoolCIDRAllocationExists(ctx context.Context, n string, v * return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No IPAM Pool CIDR Allocation ID is set") - } - - allocationID, poolID, err := tfec2.IPAMPoolCIDRAllocationParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindIPAMPoolAllocationByTwoPartKey(ctx, conn, allocationID, poolID) + output, err := tfec2.FindIPAMPoolAllocationByTwoPartKey(ctx, conn, rs.Primary.Attributes["ipam_pool_allocation_id"], rs.Primary.Attributes["ipam_pool_id"]) if err != nil { return err @@ -262,19 +252,9 @@ func testAccCheckIPAMPoolCIDRAllocationExistsWithProvider(ctx context.Context, n return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No IPAM Pool CIDR Allocation ID is set") - } - - allocationID, poolID, err := tfec2.IPAMPoolCIDRAllocationParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := providerF().Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindIPAMPoolAllocationByTwoPartKey(ctx, conn, allocationID, poolID) + output, err := tfec2.FindIPAMPoolAllocationByTwoPartKey(ctx, conn, rs.Primary.Attributes["ipam_pool_allocation_id"], rs.Primary.Attributes["ipam_pool_id"]) if err != nil { return err @@ -295,13 +275,7 @@ func testAccCheckIPAMPoolAllocationDestroy(ctx context.Context) resource.TestChe continue } - allocationID, poolID, err := tfec2.IPAMPoolCIDRAllocationParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindIPAMPoolAllocationByTwoPartKey(ctx, conn, allocationID, poolID) + _, err := tfec2.FindIPAMPoolAllocationByTwoPartKey(ctx, conn, rs.Primary.Attributes["ipam_pool_allocation_id"], rs.Primary.Attributes["ipam_pool_id"]) if tfresource.NotFound(err) { continue diff --git a/internal/service/ec2/ipam_pool_cidr_test.go b/internal/service/ec2/ipam_pool_cidr_test.go index 603406b2cb7..0b671cc262c 100644 --- a/internal/service/ec2/ipam_pool_cidr_test.go +++ b/internal/service/ec2/ipam_pool_cidr_test.go @@ -141,19 +141,9 @@ func testAccCheckIPAMPoolCIDRExists(ctx context.Context, n string, v *awstypes.I return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No IPAM Pool CIDR ID is set") - } - - cidrBlock, poolID, err := tfec2.IPAMPoolCIDRParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindIPAMPoolCIDRByTwoPartKey(ctx, conn, cidrBlock, poolID) + output, err := tfec2.FindIPAMPoolCIDRByTwoPartKey(ctx, conn, rs.Primary.Attributes["cidr"], rs.Primary.Attributes["ipam_pool_id"]) if err != nil { return err @@ -174,13 +164,7 @@ func testAccCheckIPAMPoolCIDRDestroy(ctx context.Context) resource.TestCheckFunc continue } - cidrBlock, poolID, err := tfec2.IPAMPoolCIDRParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindIPAMPoolCIDRByTwoPartKey(ctx, conn, cidrBlock, poolID) + _, err := tfec2.FindIPAMPoolCIDRByTwoPartKey(ctx, conn, rs.Primary.Attributes["cidr"], rs.Primary.Attributes["ipam_pool_id"]) if tfresource.NotFound(err) { continue diff --git a/internal/service/ec2/ipam_pool_cidrs_data_source.go b/internal/service/ec2/ipam_pool_cidrs_data_source.go index b88fce4475e..81b62466ef7 100644 --- a/internal/service/ec2/ipam_pool_cidrs_data_source.go +++ b/internal/service/ec2/ipam_pool_cidrs_data_source.go @@ -61,7 +61,7 @@ func dataSourceIPAMPoolCIDRsRead(ctx context.Context, d *schema.ResourceData, me IpamPoolId: aws.String(poolID), } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/ipam_pool_data_source.go b/internal/service/ec2/ipam_pool_data_source.go index 6b58c29da43..d8e89144569 100644 --- a/internal/service/ec2/ipam_pool_data_source.go +++ b/internal/service/ec2/ipam_pool_data_source.go @@ -116,7 +116,7 @@ func dataSourceIPAMPoolRead(ctx context.Context, d *schema.ResourceData, meta in input.IpamPoolIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -135,7 +135,7 @@ func dataSourceIPAMPoolRead(ctx context.Context, d *schema.ResourceData, meta in d.Set("allocation_default_netmask_length", pool.AllocationDefaultNetmaskLength) d.Set("allocation_max_netmask_length", pool.AllocationMaxNetmaskLength) d.Set("allocation_min_netmask_length", pool.AllocationMinNetmaskLength) - d.Set("allocation_resource_tags", keyValueTagsV2(ctx, tagsFromIPAMAllocationTags(pool.AllocationResourceTags)).Map()) + d.Set("allocation_resource_tags", keyValueTags(ctx, tagsFromIPAMAllocationTags(pool.AllocationResourceTags)).Map()) d.Set(names.AttrARN, pool.IpamPoolArn) d.Set("auto_import", pool.AutoImport) d.Set("aws_service", pool.AwsService) @@ -149,7 +149,7 @@ func dataSourceIPAMPoolRead(ctx context.Context, d *schema.ResourceData, meta in d.Set("source_ipam_pool_id", pool.SourceIpamPoolId) d.Set(names.AttrState, pool.State) - setTagsOutV2(ctx, pool.Tags) + setTagsOut(ctx, pool.Tags) return diags } diff --git a/internal/service/ec2/ipam_pools_data_source.go b/internal/service/ec2/ipam_pools_data_source.go index 9af03fb65fd..649fb7121f3 100644 --- a/internal/service/ec2/ipam_pools_data_source.go +++ b/internal/service/ec2/ipam_pools_data_source.go @@ -110,7 +110,7 @@ func dataSourceIPAMPoolsRead(ctx context.Context, d *schema.ResourceData, meta i input := &ec2.DescribeIpamPoolsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -145,7 +145,7 @@ func flattenIPAMPool(ctx context.Context, p awstypes.IpamPool, ignoreTagsConfig pool["allocation_default_netmask_length"] = aws.ToInt32(p.AllocationDefaultNetmaskLength) pool["allocation_max_netmask_length"] = aws.ToInt32(p.AllocationMaxNetmaskLength) pool["allocation_min_netmask_length"] = aws.ToInt32(p.AllocationMinNetmaskLength) - pool["allocation_resource_tags"] = keyValueTagsV2(ctx, tagsFromIPAMAllocationTags(p.AllocationResourceTags)).Map() + pool["allocation_resource_tags"] = keyValueTags(ctx, tagsFromIPAMAllocationTags(p.AllocationResourceTags)).Map() pool[names.AttrARN] = aws.ToString(p.IpamPoolArn) pool["auto_import"] = aws.ToBool(p.AutoImport) pool["aws_service"] = p.AwsService @@ -159,7 +159,7 @@ func flattenIPAMPool(ctx context.Context, p awstypes.IpamPool, ignoreTagsConfig pool["source_ipam_pool_id"] = aws.ToString(p.SourceIpamPoolId) pool[names.AttrState] = p.State if v := p.Tags; v != nil { - pool[names.AttrTags] = keyValueTagsV2(ctx, v).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map() + pool[names.AttrTags] = keyValueTags(ctx, v).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map() } return pool diff --git a/internal/service/ec2/ipam_resource_discovery.go b/internal/service/ec2/ipam_resource_discovery.go index f277c731d85..14e773c13ef 100644 --- a/internal/service/ec2/ipam_resource_discovery.go +++ b/internal/service/ec2/ipam_resource_discovery.go @@ -110,7 +110,7 @@ func resourceIPAMResourceDiscoveryCreate(ctx context.Context, d *schema.Resource input := &ec2.CreateIpamResourceDiscoveryInput{ ClientToken: aws.String(id.UniqueId()), OperatingRegions: expandIPAMOperatingRegions(d.Get("operating_regions").(*schema.Set).List()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeIpamResourceDiscovery), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeIpamResourceDiscovery), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -157,7 +157,7 @@ func resourceIPAMResourceDiscoveryRead(ctx context.Context, d *schema.ResourceDa } d.Set(names.AttrOwnerID, rd.OwnerId) - setTagsOutV2(ctx, rd.Tags) + setTagsOut(ctx, rd.Tags) return diags } @@ -209,7 +209,7 @@ func resourceIPAMResourceDiscoveryUpdate(ctx context.Context, d *schema.Resource } } - return diags + return append(diags, resourceIPAMResourceDiscoveryRead(ctx, d, meta)...) } func resourceIPAMResourceDiscoveryDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { diff --git a/internal/service/ec2/ipam_resource_discovery_association.go b/internal/service/ec2/ipam_resource_discovery_association.go index cfb6f8cf214..26059543654 100644 --- a/internal/service/ec2/ipam_resource_discovery_association.go +++ b/internal/service/ec2/ipam_resource_discovery_association.go @@ -95,7 +95,7 @@ func resourceIPAMResourceDiscoveryAssociationCreate(ctx context.Context, d *sche ClientToken: aws.String(id.UniqueId()), IpamId: aws.String(ipamID), IpamResourceDiscoveryId: aws.String(ipamResourceDiscoveryID), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeIpamResourceDiscoveryAssociation), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeIpamResourceDiscoveryAssociation), } output, err := conn.AssociateIpamResourceDiscovery(ctx, input) @@ -138,7 +138,7 @@ func resourceIPAMResourceDiscoveryAssociationRead(ctx context.Context, d *schema d.Set(names.AttrOwnerID, rda.OwnerId) d.Set(names.AttrState, rda.State) - setTagsOutV2(ctx, rda.Tags) + setTagsOut(ctx, rda.Tags) return diags } diff --git a/internal/service/ec2/ipam_scope.go b/internal/service/ec2/ipam_scope.go index 50cad91ee51..42d6ab6895c 100644 --- a/internal/service/ec2/ipam_scope.go +++ b/internal/service/ec2/ipam_scope.go @@ -88,7 +88,7 @@ func resourceIPAMScopeCreate(ctx context.Context, d *schema.ResourceData, meta i input := &ec2.CreateIpamScopeInput{ ClientToken: aws.String(id.UniqueId()), IpamId: aws.String(d.Get("ipam_id").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeIpamScope), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeIpamScope), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -135,7 +135,7 @@ func resourceIPAMScopeRead(ctx context.Context, d *schema.ResourceData, meta int d.Set("is_default", scope.IsDefault) d.Set("pool_count", scope.PoolCount) - setTagsOutV2(ctx, scope.Tags) + setTagsOut(ctx, scope.Tags) return diags } diff --git a/internal/service/ec2/list_pages_gen.go b/internal/service/ec2/list_pages_gen.go index 5e3dc6e82ef..b70f11ab0fb 100644 --- a/internal/service/ec2/list_pages_gen.go +++ b/internal/service/ec2/list_pages_gen.go @@ -1,4 +1,4 @@ -// Code generated by "internal/generate/listpages/main.go -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory,DescribeVpcEndpointServices -AWSSDKVersion=2"; DO NOT EDIT. +// Code generated by "internal/generate/listpages/main.go -AWSSDKVersion=2 -ListOps=DescribeSpotFleetInstances,DescribeSpotFleetRequestHistory,DescribeVpcEndpointServices"; DO NOT EDIT. package ec2 diff --git a/internal/service/ec2/outposts_coip_pool_data_source.go b/internal/service/ec2/outposts_coip_pool_data_source.go index 25bbaf16149..59cbc22ff1f 100644 --- a/internal/service/ec2/outposts_coip_pool_data_source.go +++ b/internal/service/ec2/outposts_coip_pool_data_source.go @@ -66,18 +66,18 @@ func dataSourceCoIPPoolRead(ctx context.Context, d *schema.ResourceData, meta in } if v, ok := d.GetOk("local_gateway_route_table_id"); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2(map[string]string{ + input.Filters = append(input.Filters, newAttributeFilterList(map[string]string{ "coip-pool.local-gateway-route-table-id": v.(string), })...) } if tags, tagsOk := d.GetOk(names.AttrTags); tagsOk { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, tags.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, tags.(map[string]interface{}))), )...) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -98,7 +98,7 @@ func dataSourceCoIPPoolRead(ctx context.Context, d *schema.ResourceData, meta in d.Set("pool_cidrs", coip.PoolCidrs) d.Set("pool_id", coip.PoolId) - setTagsOutV2(ctx, coip.Tags) + setTagsOut(ctx, coip.Tags) return diags } diff --git a/internal/service/ec2/outposts_coip_pools_data_source.go b/internal/service/ec2/outposts_coip_pools_data_source.go index 8d5b871091a..3239831b646 100644 --- a/internal/service/ec2/outposts_coip_pools_data_source.go +++ b/internal/service/ec2/outposts_coip_pools_data_source.go @@ -46,11 +46,11 @@ func dataSourceCoIPPoolsRead(ctx context.Context, d *schema.ResourceData, meta i input := &ec2.DescribeCoipPoolsInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/outposts_local_gateway_data_source.go b/internal/service/ec2/outposts_local_gateway_data_source.go index 6cb705c2501..5d22f8f46a1 100644 --- a/internal/service/ec2/outposts_local_gateway_data_source.go +++ b/internal/service/ec2/outposts_local_gateway_data_source.go @@ -64,19 +64,19 @@ func dataSourceLocalGatewayRead(ctx context.Context, d *schema.ResourceData, met input.LocalGatewayIds = []string{v.(string)} } - input.Filters = newAttributeFilterListV2( + input.Filters = newAttributeFilterList( map[string]string{ names.AttrState: d.Get(names.AttrState).(string), }, ) if tags, tagsOk := d.GetOk(names.AttrTags); tagsOk { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, tags.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, tags.(map[string]interface{}))), )...) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -96,7 +96,7 @@ func dataSourceLocalGatewayRead(ctx context.Context, d *schema.ResourceData, met d.Set(names.AttrOwnerID, localGateway.OwnerId) d.Set(names.AttrState, localGateway.State) - setTagsOutV2(ctx, localGateway.Tags) + setTagsOut(ctx, localGateway.Tags) return diags } diff --git a/internal/service/ec2/outposts_local_gateway_route_table_data_source.go b/internal/service/ec2/outposts_local_gateway_route_table_data_source.go index 3ce74a8c09c..217c35195e0 100644 --- a/internal/service/ec2/outposts_local_gateway_route_table_data_source.go +++ b/internal/service/ec2/outposts_local_gateway_route_table_data_source.go @@ -66,7 +66,7 @@ func dataSourceLocalGatewayRouteTableRead(ctx context.Context, d *schema.Resourc input.LocalGatewayRouteTableIds = []string{v.(string)} } - input.Filters = newAttributeFilterListV2( + input.Filters = newAttributeFilterList( map[string]string{ "local-gateway-id": d.Get("local_gateway_id").(string), "outpost-arn": d.Get("outpost_arn").(string), @@ -74,11 +74,11 @@ func dataSourceLocalGatewayRouteTableRead(ctx context.Context, d *schema.Resourc }, ) - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -99,7 +99,7 @@ func dataSourceLocalGatewayRouteTableRead(ctx context.Context, d *schema.Resourc d.Set("outpost_arn", localGatewayRouteTable.OutpostArn) d.Set(names.AttrState, localGatewayRouteTable.State) - setTagsOutV2(ctx, localGatewayRouteTable.Tags) + setTagsOut(ctx, localGatewayRouteTable.Tags) return diags } diff --git a/internal/service/ec2/outposts_local_gateway_route_table_vpc_association.go b/internal/service/ec2/outposts_local_gateway_route_table_vpc_association.go index 13b59d5e8f8..e91a19e225b 100644 --- a/internal/service/ec2/outposts_local_gateway_route_table_vpc_association.go +++ b/internal/service/ec2/outposts_local_gateway_route_table_vpc_association.go @@ -64,7 +64,7 @@ func resourceLocalGatewayRouteTableVPCAssociationCreate(ctx context.Context, d * input := &ec2.CreateLocalGatewayRouteTableVpcAssociationInput{ LocalGatewayRouteTableId: aws.String(d.Get("local_gateway_route_table_id").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeLocalGatewayRouteTableVpcAssociation), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeLocalGatewayRouteTableVpcAssociation), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -103,7 +103,7 @@ func resourceLocalGatewayRouteTableVPCAssociationRead(ctx context.Context, d *sc d.Set("local_gateway_route_table_id", association.LocalGatewayRouteTableId) d.Set(names.AttrVPCID, association.VpcId) - setTagsOutV2(ctx, association.Tags) + setTagsOut(ctx, association.Tags) return diags } diff --git a/internal/service/ec2/outposts_local_gateway_route_tables_data_source.go b/internal/service/ec2/outposts_local_gateway_route_tables_data_source.go index 2857fab2869..1f9687143de 100644 --- a/internal/service/ec2/outposts_local_gateway_route_tables_data_source.go +++ b/internal/service/ec2/outposts_local_gateway_route_tables_data_source.go @@ -46,11 +46,11 @@ func dataSourceLocalGatewayRouteTablesRead(ctx context.Context, d *schema.Resour input := &ec2.DescribeLocalGatewayRouteTablesInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source.go b/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source.go index 2c35a38d32b..8113d17413a 100644 --- a/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source.go +++ b/internal/service/ec2/outposts_local_gateway_virtual_interface_data_source.go @@ -80,11 +80,11 @@ func dataSourceLocalGatewayVirtualInterfaceRead(ctx context.Context, d *schema.R input.LocalGatewayVirtualInterfaceIds = []string{v.(string)} } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -107,7 +107,7 @@ func dataSourceLocalGatewayVirtualInterfaceRead(ctx context.Context, d *schema.R d.Set("peer_bgp_asn", localGatewayVirtualInterface.PeerBgpAsn) d.Set("vlan", localGatewayVirtualInterface.Vlan) - setTagsOutV2(ctx, localGatewayVirtualInterface.Tags) + setTagsOut(ctx, localGatewayVirtualInterface.Tags) return diags } diff --git a/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source.go b/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source.go index 92cf4f43df0..56b2179b0f0 100644 --- a/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source.go +++ b/internal/service/ec2/outposts_local_gateway_virtual_interface_group_data_source.go @@ -61,17 +61,17 @@ func dataSourceLocalGatewayVirtualInterfaceGroupRead(ctx context.Context, d *sch input.LocalGatewayVirtualInterfaceGroupIds = []string{v.(string)} } - input.Filters = newAttributeFilterListV2( + input.Filters = newAttributeFilterList( map[string]string{ "local-gateway-id": d.Get("local_gateway_id").(string), }, ) - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -91,7 +91,7 @@ func dataSourceLocalGatewayVirtualInterfaceGroupRead(ctx context.Context, d *sch d.Set("local_gateway_virtual_interface_group_id", localGatewayVirtualInterfaceGroup.LocalGatewayVirtualInterfaceGroupId) d.Set("local_gateway_virtual_interface_ids", localGatewayVirtualInterfaceGroup.LocalGatewayVirtualInterfaceIds) - setTagsOutV2(ctx, localGatewayVirtualInterfaceGroup.Tags) + setTagsOut(ctx, localGatewayVirtualInterfaceGroup.Tags) return diags } diff --git a/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source.go b/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source.go index 562fb6ad5ab..2de038f2f7a 100644 --- a/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source.go +++ b/internal/service/ec2/outposts_local_gateway_virtual_interface_groups_data_source.go @@ -49,11 +49,11 @@ func dataSourceLocalGatewayVirtualInterfaceGroupsRead(ctx context.Context, d *sc input := &ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/outposts_local_gateways_data_source.go b/internal/service/ec2/outposts_local_gateways_data_source.go index bd05d2b533d..179d4d40fed 100644 --- a/internal/service/ec2/outposts_local_gateways_data_source.go +++ b/internal/service/ec2/outposts_local_gateways_data_source.go @@ -46,11 +46,11 @@ func dataSourceLocalGatewaysRead(ctx context.Context, d *schema.ResourceData, me input := &ec2.DescribeLocalGatewaysInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/service_endpoint_resolver_gen.go b/internal/service/ec2/service_endpoint_resolver_gen.go index 0b1b24d201c..05755fb2a09 100644 --- a/internal/service/ec2/service_endpoint_resolver_gen.go +++ b/internal/service/ec2/service_endpoint_resolver_gen.go @@ -6,78 +6,14 @@ import ( "context" "fmt" "net" - "net/url" aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" ec2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ec2" - endpoints_sdkv1 "github.com/aws/aws-sdk-go/aws/endpoints" smithyendpoints "github.com/aws/smithy-go/endpoints" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/errs" ) -var _ endpoints_sdkv1.Resolver = resolverSDKv1{} - -type resolverSDKv1 struct { - ctx context.Context -} - -func newEndpointResolverSDKv1(ctx context.Context) resolverSDKv1 { - return resolverSDKv1{ - ctx: ctx, - } -} - -func (r resolverSDKv1) EndpointFor(service, region string, opts ...func(*endpoints_sdkv1.Options)) (endpoint endpoints_sdkv1.ResolvedEndpoint, err error) { - ctx := r.ctx - - var opt endpoints_sdkv1.Options - opt.Set(opts...) - - useFIPS := opt.UseFIPSEndpoint == endpoints_sdkv1.FIPSEndpointStateEnabled - - defaultResolver := endpoints_sdkv1.DefaultResolver() - - if useFIPS { - ctx = tflog.SetField(ctx, "tf_aws.use_fips", useFIPS) - - endpoint, err = defaultResolver.EndpointFor(service, region, opts...) - if err != nil { - return endpoint, err - } - - tflog.Debug(ctx, "endpoint resolved", map[string]any{ - "tf_aws.endpoint": endpoint.URL, - }) - - var endpointURL *url.URL - endpointURL, err = url.Parse(endpoint.URL) - if err != nil { - return endpoint, err - } - - hostname := endpointURL.Hostname() - _, err = net.LookupHost(hostname) - if err != nil { - if dnsErr, ok := errs.As[*net.DNSError](err); ok && dnsErr.IsNotFound { - tflog.Debug(ctx, "default endpoint host not found, disabling FIPS", map[string]any{ - "tf_aws.hostname": hostname, - }) - opts = append(opts, func(o *endpoints_sdkv1.Options) { - o.UseFIPSEndpoint = endpoints_sdkv1.FIPSEndpointStateDisabled - }) - } else { - err = fmt.Errorf("looking up accessanalyzer endpoint %q: %s", hostname, err) - return - } - } else { - return endpoint, err - } - } - - return defaultResolver.EndpointFor(service, region, opts...) -} - var _ ec2_sdkv2.EndpointResolverV2 = resolverSDKv2{} type resolverSDKv2 struct { diff --git a/internal/service/ec2/service_endpoints_gen_test.go b/internal/service/ec2/service_endpoints_gen_test.go index 6eab3c485f4..ca6ebe68a3e 100644 --- a/internal/service/ec2/service_endpoints_gen_test.go +++ b/internal/service/ec2/service_endpoints_gen_test.go @@ -18,8 +18,6 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" ec2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ec2" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - ec2_sdkv1 "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/google/go-cmp/cmp" @@ -236,25 +234,13 @@ func TestEndpointConfiguration(t *testing.T) { //nolint:paralleltest // uses t.S }, } - t.Run("v1", func(t *testing.T) { - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase + for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv + testcase := testcase - t.Run(name, func(t *testing.T) { - testEndpointCase(t, providerRegion, testcase, callServiceV1) - }) - } - }) - - t.Run("v2", func(t *testing.T) { - for name, testcase := range testcases { //nolint:paralleltest // uses t.Setenv - testcase := testcase - - t.Run(name, func(t *testing.T) { - testEndpointCase(t, providerRegion, testcase, callServiceV2) - }) - } - }) + t.Run(name, func(t *testing.T) { + testEndpointCase(t, providerRegion, testcase, callService) + }) + } } func defaultEndpoint(region string) (url.URL, error) { @@ -292,7 +278,7 @@ func defaultFIPSEndpoint(region string) (url.URL, error) { return ep.URI, nil } -func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { +func callService(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { t.Helper() client := meta.EC2Client(ctx) @@ -317,21 +303,6 @@ func callServiceV2(ctx context.Context, t *testing.T, meta *conns.AWSClient) api return result } -func callServiceV1(ctx context.Context, t *testing.T, meta *conns.AWSClient) apiCallParams { - t.Helper() - - client := meta.EC2Conn(ctx) - - req, _ := client.DescribeVpcsRequest(&ec2_sdkv1.DescribeVpcsInput{}) - - req.HTTPRequest.URL.Path = "/" - - return apiCallParams{ - endpoint: req.HTTPRequest.URL.String(), - region: aws_sdkv1.StringValue(client.Config.Region), - } -} - func withNoConfig(_ *caseSetup) { // no-op } diff --git a/internal/service/ec2/service_package.go b/internal/service/ec2/service_package.go index 2fc47c981f2..a83c137dc10 100644 --- a/internal/service/ec2/service_package.go +++ b/internal/service/ec2/service_package.go @@ -9,33 +9,11 @@ import ( aws_sdkv2 "github.com/aws/aws-sdk-go-v2/aws" retry_sdkv2 "github.com/aws/aws-sdk-go-v2/aws/retry" ec2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ec2" - aws_sdkv1 "github.com/aws/aws-sdk-go/aws" - session_sdkv1 "github.com/aws/aws-sdk-go/aws/session" - ec2_sdkv1 "github.com/aws/aws-sdk-go/service/ec2" tfawserr_sdkv2 "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/names" ) -// 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) (*ec2_sdkv1.EC2, error) { - sess := config[names.AttrSession].(*session_sdkv1.Session) - - cfg := aws_sdkv1.Config{} - - if endpoint := config[names.AttrEndpoint].(string); endpoint != "" { - tflog.Debug(ctx, "setting endpoint", map[string]any{ - "tf_aws.endpoint": endpoint, - }) - cfg.Endpoint = aws_sdkv1.String(endpoint) - } else { - cfg.EndpointResolver = newEndpointResolverSDKv1(ctx) - } - - return ec2_sdkv1.New(sess.Copy(&cfg)), nil -} - // NewClient returns a new AWS SDK for Go v2 client for this service package's AWS API. func (p *servicePackage) NewClient(ctx context.Context, config map[string]any) (*ec2_sdkv2.Client, error) { cfg := *(config["aws_sdkv2_config"].(*aws_sdkv2.Config)) diff --git a/internal/service/ec2/service_package_gen.go b/internal/service/ec2/service_package_gen.go index 3bc46b33c5d..04d5d5977c8 100644 --- a/internal/service/ec2/service_package_gen.go +++ b/internal/service/ec2/service_package_gen.go @@ -15,7 +15,7 @@ type servicePackage struct{} func (p *servicePackage) FrameworkDataSources(ctx context.Context) []*types.ServicePackageFrameworkDataSource { return []*types.ServicePackageFrameworkDataSource{ { - Factory: newDataSourceCapacityBlockOffering, + Factory: newCapacityBlockOfferingDataSource, Name: "Capacity Block Offering", }, { @@ -31,6 +31,13 @@ func (p *servicePackage) FrameworkDataSources(ctx context.Context) []*types.Serv func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.ServicePackageFrameworkResource { return []*types.ServicePackageFrameworkResource{ + { + Factory: newCapacityBlockReservationResource, + Name: "Capacity Block Reservation", + Tags: &types.ServicePackageResourceTags{ + IdentifierAttribute: names.AttrID, + }, + }, { Factory: newEBSFastSnapshotRestoreResource, Name: "EBS Fast Snapshot Restore", @@ -50,21 +57,6 @@ func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.Servic Factory: newInstanceMetadataDefaultsResource, Name: "Instance Metadata Defaults", }, - { - Factory: newResourceCapacityBlockReservation, - Name: "Capacity Block Reservation", - Tags: &types.ServicePackageResourceTags{ - IdentifierAttribute: names.AttrID, - }, - }, - { - Factory: newResourceEndpointPrivateDNS, - Name: "Endpoint Private DNS", - }, - { - Factory: newResourceEndpointServicePrivateDNSVerification, - Name: "Endpoint Service Private DNS Verification", - }, { Factory: newSecurityGroupEgressRuleResource, Name: "Security Group Egress Rule", @@ -79,6 +71,14 @@ func (p *servicePackage) FrameworkResources(ctx context.Context) []*types.Servic IdentifierAttribute: names.AttrID, }, }, + { + Factory: newVPCEndpointPrivateDNSResource, + Name: "VPC Endpoint Private DNS", + }, + { + Factory: newVPCEndpointServicePrivateDNSVerificationResource, + Name: "VPC Endpoint Service Private DNS Verification", + }, } } @@ -226,12 +226,14 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Local Gateways", }, { - Factory: DataSourceManagedPrefixList, + Factory: dataSourceManagedPrefixList, TypeName: "aws_ec2_managed_prefix_list", + Name: "Managed Prefix List", }, { - Factory: DataSourceManagedPrefixLists, + Factory: dataSourceManagedPrefixLists, TypeName: "aws_ec2_managed_prefix_lists", + Name: "Managed Prefix Lists", }, { Factory: dataSourceNetworkInsightsAnalysis, @@ -383,8 +385,9 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "Instances", }, { - Factory: DataSourceInternetGateway, + Factory: dataSourceInternetGateway, TypeName: "aws_internet_gateway", + Name: "Internet Gateway", }, { Factory: dataSourceKeyPair, @@ -399,16 +402,19 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceNATGateway, + Factory: dataSourceNATGateway, TypeName: "aws_nat_gateway", + Name: "NAT Gateway", }, { - Factory: DataSourceNATGateways, + Factory: dataSourceNATGateways, TypeName: "aws_nat_gateways", + Name: "NAT Gateways", }, { - Factory: DataSourceNetworkACLs, + Factory: dataSourceNetworkACLs, TypeName: "aws_network_acls", + Name: "Network ACLs", }, { Factory: dataSourceNetworkInterface, @@ -417,59 +423,67 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceNetworkInterfaces, + Factory: dataSourceNetworkInterfaces, TypeName: "aws_network_interfaces", + Name: "Network Interfaces", }, { - Factory: DataSourcePrefixList, + Factory: dataSourcePrefixList, TypeName: "aws_prefix_list", + Name: "Prefix List", }, { - Factory: DataSourceRoute, + Factory: dataSourceRoute, TypeName: "aws_route", + Name: "Route", }, { - Factory: DataSourceRouteTable, + Factory: dataSourceRouteTable, TypeName: "aws_route_table", + Name: "Route Table", }, { - Factory: DataSourceRouteTables, + Factory: dataSourceRouteTables, TypeName: "aws_route_tables", + Name: "Route Tables", }, { - Factory: DataSourceSecurityGroup, + Factory: dataSourceSecurityGroup, TypeName: "aws_security_group", Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceSecurityGroups, + Factory: dataSourceSecurityGroups, TypeName: "aws_security_groups", + Name: "Security Groups", }, { - Factory: DataSourceSubnet, + Factory: dataSourceSubnet, TypeName: "aws_subnet", }, { - Factory: DataSourceSubnets, + Factory: dataSourceSubnets, TypeName: "aws_subnets", }, { - Factory: DataSourceVPC, + Factory: dataSourceVPC, TypeName: "aws_vpc", Name: "VPC", Tags: &types.ServicePackageResourceTags{}, }, { - Factory: DataSourceVPCDHCPOptions, + Factory: dataSourceVPCDHCPOptions, TypeName: "aws_vpc_dhcp_options", }, { - Factory: DataSourceVPCEndpoint, + Factory: dataSourceVPCEndpoint, TypeName: "aws_vpc_endpoint", + Name: "Endpoint", }, { - Factory: DataSourceVPCEndpointService, + Factory: dataSourceVPCEndpointService, TypeName: "aws_vpc_endpoint_service", + Name: "Endpoint Service", }, { Factory: dataSourceIPAMPool, @@ -493,16 +507,19 @@ func (p *servicePackage) SDKDataSources(ctx context.Context) []*types.ServicePac Name: "IPAM Preview Next CIDR", }, { - Factory: DataSourceVPCPeeringConnection, + Factory: dataSourceVPCPeeringConnection, TypeName: "aws_vpc_peering_connection", + Name: "VPC Peering Connection", }, { - Factory: DataSourceVPCPeeringConnections, + Factory: dataSourceVPCPeeringConnections, TypeName: "aws_vpc_peering_connections", + Name: "VPC Peering Connections", }, { - Factory: DataSourceVPCs, + Factory: dataSourceVPCs, TypeName: "aws_vpcs", + Name: "VPCs", }, { Factory: dataSourceVPNGateway, @@ -569,7 +586,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceDefaultSecurityGroup, + Factory: resourceDefaultSecurityGroup, TypeName: "aws_default_security_group", Name: "Security Group", Tags: &types.ServicePackageResourceTags{ @@ -577,7 +594,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceDefaultSubnet, + Factory: resourceDefaultSubnet, TypeName: "aws_default_subnet", Name: "Subnet", Tags: &types.ServicePackageResourceTags{ @@ -585,15 +602,15 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceDefaultVPC, + Factory: resourceDefaultVPC, TypeName: "aws_default_vpc", - Name: "VPC", + Name: "Default VPC", Tags: &types.ServicePackageResourceTags{ IdentifierAttribute: names.AttrID, }, }, { - Factory: ResourceDefaultVPCDHCPOptions, + Factory: resourceDefaultVPCDHCPOptions, TypeName: "aws_default_vpc_dhcp_options", Name: "DHCP Options", Tags: &types.ServicePackageResourceTags{ @@ -725,7 +742,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceManagedPrefixList, + Factory: resourceManagedPrefixList, TypeName: "aws_ec2_managed_prefix_list", Name: "Managed Prefix List", Tags: &types.ServicePackageResourceTags{ @@ -733,8 +750,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceManagedPrefixListEntry, + Factory: resourceManagedPrefixListEntry, TypeName: "aws_ec2_managed_prefix_list_entry", + Name: "Managed Prefix List Entry", }, { Factory: resourceNetworkInsightsAnalysis, @@ -758,8 +776,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka Name: "Serial Console Access", }, { - Factory: ResourceSubnetCIDRReservation, + Factory: resourceSubnetCIDRReservation, TypeName: "aws_ec2_subnet_cidr_reservation", + Name: "Subnet CIDR Reservation", }, { Factory: resourceTag, @@ -916,7 +935,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceEgressOnlyInternetGateway, + Factory: resourceEgressOnlyInternetGateway, TypeName: "aws_egress_only_internet_gateway", Name: "Egress-Only Internet Gateway", Tags: &types.ServicePackageResourceTags{ @@ -937,7 +956,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka Name: "EIP Association", }, { - Factory: ResourceFlowLog, + Factory: resourceFlowLog, TypeName: "aws_flow_log", Name: "Flow Log", Tags: &types.ServicePackageResourceTags{ @@ -953,7 +972,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceInternetGateway, + Factory: resourceInternetGateway, TypeName: "aws_internet_gateway", Name: "Internet Gateway", Tags: &types.ServicePackageResourceTags{ @@ -961,8 +980,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceInternetGatewayAttachment, + Factory: resourceInternetGatewayAttachment, TypeName: "aws_internet_gateway_attachment", + Name: "Internet Gateway Attachment", }, { Factory: resourceKeyPair, @@ -986,7 +1006,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka Name: "Main Route Table Association", }, { - Factory: ResourceNATGateway, + Factory: resourceNATGateway, TypeName: "aws_nat_gateway", Name: "NAT Gateway", Tags: &types.ServicePackageResourceTags{ @@ -1002,8 +1022,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceNetworkACLAssociation, + Factory: resourceNetworkACLAssociation, TypeName: "aws_network_acl_association", + Name: "Network ACL Association", }, { Factory: resourceNetworkACLRule, @@ -1019,12 +1040,14 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceNetworkInterfaceAttachment, + Factory: resourceNetworkInterfaceAttachment, TypeName: "aws_network_interface_attachment", + Name: "Network Interface Attachment", }, { - Factory: ResourceNetworkInterfaceSGAttachment, + Factory: resourceNetworkInterfaceSGAttachment, TypeName: "aws_network_interface_sg_attachment", + Name: "Network Interface SG Attachement", }, { Factory: resourcePlacementGroup, @@ -1048,8 +1071,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceRouteTableAssociation, + Factory: resourceRouteTableAssociation, TypeName: "aws_route_table_association", + Name: "Route Table Association", }, { Factory: resourceSecurityGroup, @@ -1060,8 +1084,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceSecurityGroupRule, + Factory: resourceSecurityGroupRule, TypeName: "aws_security_group_rule", + Name: "Security Group Rule", }, { Factory: resourceSnapshotCreateVolumePermission, @@ -1090,7 +1115,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceSubnet, + Factory: resourceSubnet, TypeName: "aws_subnet", Name: "Subnet", Tags: &types.ServicePackageResourceTags{ @@ -1098,7 +1123,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVerifiedAccessEndpoint, + Factory: resourceVerifiedAccessEndpoint, TypeName: "aws_verifiedaccess_endpoint", Name: "Verified Access Endpoint", Tags: &types.ServicePackageResourceTags{ @@ -1106,7 +1131,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVerifiedAccessGroup, + Factory: resourceVerifiedAccessGroup, TypeName: "aws_verifiedaccess_group", Name: "Verified Access Group", Tags: &types.ServicePackageResourceTags{ @@ -1114,7 +1139,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVerifiedAccessInstance, + Factory: resourceVerifiedAccessInstance, TypeName: "aws_verifiedaccess_instance", Name: "Verified Access Instance", Tags: &types.ServicePackageResourceTags{ @@ -1122,17 +1147,17 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVerifiedAccessInstanceLoggingConfiguration, + Factory: resourceVerifiedAccessInstanceLoggingConfiguration, TypeName: "aws_verifiedaccess_instance_logging_configuration", Name: "Verified Access Instance Logging Configuration", }, { - Factory: ResourceVerifiedAccessInstanceTrustProviderAttachment, + Factory: resourceVerifiedAccessInstanceTrustProviderAttachment, TypeName: "aws_verifiedaccess_instance_trust_provider_attachment", Name: "Verified Access Instance Trust Provider Attachment", }, { - Factory: ResourceVerifiedAccessTrustProvider, + Factory: resourceVerifiedAccessTrustProvider, TypeName: "aws_verifiedaccess_trust_provider", Name: "Verified Access Trust Provider", Tags: &types.ServicePackageResourceTags{ @@ -1145,7 +1170,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka Name: "EBS Volume Attachment", }, { - Factory: ResourceVPC, + Factory: resourceVPC, TypeName: "aws_vpc", Name: "VPC", Tags: &types.ServicePackageResourceTags{ @@ -1153,7 +1178,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCDHCPOptions, + Factory: resourceVPCDHCPOptions, TypeName: "aws_vpc_dhcp_options", Name: "DHCP Options", Tags: &types.ServicePackageResourceTags{ @@ -1161,8 +1186,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCDHCPOptionsAssociation, + Factory: resourceVPCDHCPOptionsAssociation, TypeName: "aws_vpc_dhcp_options_association", + Name: "VPC DHCP Options Association", }, { Factory: resourceVPCEndpoint, @@ -1173,28 +1199,31 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCEndpointConnectionAccepter, + Factory: resourceVPCEndpointConnectionAccepter, TypeName: "aws_vpc_endpoint_connection_accepter", + Name: "VPC Endpoint Connection Accepter", }, { - Factory: ResourceVPCEndpointConnectionNotification, + Factory: resourceVPCEndpointConnectionNotification, TypeName: "aws_vpc_endpoint_connection_notification", Name: "VPC Endpoint Connection Notification", }, { - Factory: ResourceVPCEndpointPolicy, + Factory: resourceVPCEndpointPolicy, TypeName: "aws_vpc_endpoint_policy", }, { - Factory: ResourceVPCEndpointRouteTableAssociation, + Factory: resourceVPCEndpointRouteTableAssociation, TypeName: "aws_vpc_endpoint_route_table_association", + Name: "VPC Endpoint Route Table Association", }, { - Factory: ResourceVPCEndpointSecurityGroupAssociation, + Factory: resourceVPCEndpointSecurityGroupAssociation, TypeName: "aws_vpc_endpoint_security_group_association", + Name: "VPC Endpoint Security Group Association", }, { - Factory: ResourceVPCEndpointService, + Factory: resourceVPCEndpointService, TypeName: "aws_vpc_endpoint_service", Name: "VPC Endpoint Service", Tags: &types.ServicePackageResourceTags{ @@ -1202,12 +1231,14 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCEndpointServiceAllowedPrincipal, + Factory: resourceVPCEndpointServiceAllowedPrincipal, TypeName: "aws_vpc_endpoint_service_allowed_principal", + Name: "Endpoint Service Allowed Principal", }, { - Factory: ResourceVPCEndpointSubnetAssociation, + Factory: resourceVPCEndpointSubnetAssociation, TypeName: "aws_vpc_endpoint_subnet_association", + Name: "VPC Endpoint Subnet Association", }, { Factory: resourceIPAM, @@ -1270,19 +1301,22 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCIPv4CIDRBlockAssociation, + Factory: resourceVPCIPv4CIDRBlockAssociation, TypeName: "aws_vpc_ipv4_cidr_block_association", + Name: "VPC IPV4 CIDR Block Association", }, { - Factory: ResourceVPCIPv6CIDRBlockAssociation, + Factory: resourceVPCIPv6CIDRBlockAssociation, TypeName: "aws_vpc_ipv6_cidr_block_association", + Name: "VPC IPV6 CIDR Block Association", }, { - Factory: ResourceNetworkPerformanceMetricSubscription, + Factory: resourceNetworkPerformanceMetricSubscription, TypeName: "aws_vpc_network_performance_metric_subscription", + Name: "VPC Network Performance Metric Subscription", }, { - Factory: ResourceVPCPeeringConnection, + Factory: resourceVPCPeeringConnection, TypeName: "aws_vpc_peering_connection", Name: "VPC Peering Connection", Tags: &types.ServicePackageResourceTags{ @@ -1290,7 +1324,7 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCPeeringConnectionAccepter, + Factory: resourceVPCPeeringConnectionAccepter, TypeName: "aws_vpc_peering_connection_accepter", Name: "VPC Peering Connection", Tags: &types.ServicePackageResourceTags{ @@ -1298,8 +1332,9 @@ func (p *servicePackage) SDKResources(ctx context.Context) []*types.ServicePacka }, }, { - Factory: ResourceVPCPeeringConnectionOptions, + Factory: resourceVPCPeeringConnectionOptions, TypeName: "aws_vpc_peering_connection_options", + Name: "VPC Peering Connection Options", }, { Factory: resourceVPNConnection, diff --git a/internal/service/ec2/status.go b/internal/service/ec2/status.go index ae16810ca6c..8b13352bb69 100644 --- a/internal/service/ec2/status.go +++ b/internal/service/ec2/status.go @@ -7,19 +7,238 @@ import ( "context" "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// -// Move functions to statusv2.go as they are migrated to AWS SDK for Go v2. -// +func statusAvailabilityZoneGroupOptInStatus(ctx context.Context, conn *ec2.Client, name string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findAvailabilityZoneGroupByName(ctx, conn, name) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.OptInStatus), nil + } +} + +func statusCapacityReservation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findCapacityReservationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusCarrierGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findCarrierGatewayByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusFleet(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call FindFleetByID as it maps useful status codes to NotFoundError. + output, err := findFleet(ctx, conn, &ec2.DescribeFleetsInput{ + FleetIds: []string{id}, + }) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.FleetState), nil + } +} + +func statusHost(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findHostByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusInstance(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call findInstanceByID as it maps useful status codes to NotFoundError. + output, err := findInstance(ctx, conn, &ec2.DescribeInstancesInput{ + InstanceIds: []string{id}, + }) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State.Name), nil + } +} + +func statusInstanceIAMInstanceProfile(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + instance, err := findInstanceByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + if instance.IamInstanceProfile == nil || instance.IamInstanceProfile.Arn == nil { + return instance, "", nil + } + + name, err := instanceProfileARNToName(aws.ToString(instance.IamInstanceProfile.Arn)) + + if err != nil { + return instance, "", err + } + + return instance, name, nil + } +} + +func statusInstanceCapacityReservationSpecificationEquals(ctx context.Context, conn *ec2.Client, id string, expectedValue *awstypes.CapacityReservationSpecification) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findInstanceByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output.CapacityReservationSpecification, strconv.FormatBool(capacityReservationSpecificationResponsesEqual(output.CapacityReservationSpecification, expectedValue)), nil + } +} + +func statusInstanceMaintenanceOptionsAutoRecovery(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findInstanceByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + if v := output.MaintenanceOptions; v != nil { + return v, string(v.AutoRecovery), nil + } + + return nil, "", nil + } +} + +func statusInstanceMetadataOptions(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findInstanceByID(ctx, conn, id) -func StatusNATGatewayState(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + if output.MetadataOptions == nil { + return nil, "", nil + } + + return output.MetadataOptions, string(output.MetadataOptions.State), nil + } +} + +func statusInstanceRootBlockDeviceDeleteOnTermination(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findInstanceByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + for _, v := range output.BlockDeviceMappings { + if aws.ToString(v.DeviceName) == aws.ToString(output.RootDeviceName) && v.Ebs != nil { + return v.Ebs, strconv.FormatBool(aws.ToBool(v.Ebs.DeleteOnTermination)), nil + } + } + + return nil, "", nil + } +} + +func statusLocalGatewayRoute(ctx context.Context, conn *ec2.Client, localGatewayRouteTableID, destinationCIDRBlock string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findLocalGatewayRouteByTwoPartKey(ctx, conn, localGatewayRouteTableID, destinationCIDRBlock) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusLocalGatewayRouteTableVPCAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindNATGatewayByID(ctx, conn, id) + output, err := findLocalGatewayRouteTableVPCAssociationByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -29,13 +248,13 @@ func StatusNATGatewayState(ctx context.Context, conn *ec2.EC2, id string) retry. return nil, "", err } - return output, aws.StringValue(output.State), nil + return output, aws.ToString(output.State), nil } } -func StatusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx context.Context, conn *ec2.EC2, natGatewayID, allocationID string) retry.StateRefreshFunc { +func statusManagedPrefixListState(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindNATGatewayAddressByNATGatewayIDAndAllocationID(ctx, conn, natGatewayID, allocationID) + output, err := findManagedPrefixListByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -45,13 +264,13 @@ func StatusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx context.Context, c return nil, "", err } - return output, aws.StringValue(output.Status), nil + return output, string(output.State), nil } } -func StatusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx context.Context, conn *ec2.EC2, natGatewayID, privateIP string) retry.StateRefreshFunc { +func statusPlacementGroup(ctx context.Context, conn *ec2.Client, name string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx, conn, natGatewayID, privateIP) + output, err := findPlacementGroupByName(ctx, conn, name) if tfresource.NotFound(err) { return nil, "", nil @@ -61,17 +280,17 @@ func StatusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx context.Context, conn return nil, "", err } - return output, aws.StringValue(output.Status), nil + return output, string(output.State), nil } } const ( - SecurityGroupStatusCreated = "Created" + securityGroupStatusCreated = "Created" ) -func StatusSecurityGroup(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSecurityGroup(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSecurityGroupByID(ctx, conn, id) + output, err := findSecurityGroupByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -81,13 +300,13 @@ func StatusSecurityGroup(ctx context.Context, conn *ec2.EC2, id string) retry.St return nil, "", err } - return output, SecurityGroupStatusCreated, nil + return output, securityGroupStatusCreated, nil } } -func StatusSubnetState(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSpotFleetActivityStatus(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSpotFleetRequestByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -97,13 +316,16 @@ func StatusSubnetState(ctx context.Context, conn *ec2.EC2, id string) retry.Stat return nil, "", err } - return output, aws.StringValue(output.State), nil + return output, string(output.ActivityStatus), nil } } -func StatusSubnetIPv6CIDRBlockAssociationState(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSpotFleetRequest(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetIPv6CIDRBlockAssociationByID(ctx, conn, id) + // Don't call FindSpotFleetRequestByID as it maps useful status codes to NotFoundError. + output, err := findSpotFleetRequest(ctx, conn, &ec2.DescribeSpotFleetRequestsInput{ + SpotFleetRequestIds: []string{id}, + }) if tfresource.NotFound(err) { return nil, "", nil @@ -113,13 +335,13 @@ func StatusSubnetIPv6CIDRBlockAssociationState(ctx context.Context, conn *ec2.EC return nil, "", err } - return output.Ipv6CidrBlockState, aws.StringValue(output.Ipv6CidrBlockState.State), nil + return output, string(output.SpotFleetRequestState), nil } } -func StatusSubnetAssignIPv6AddressOnCreation(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSpotInstanceRequest(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSpotInstanceRequestByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -129,13 +351,13 @@ func StatusSubnetAssignIPv6AddressOnCreation(ctx context.Context, conn *ec2.EC2, return nil, "", err } - return output, strconv.FormatBool(aws.BoolValue(output.AssignIpv6AddressOnCreation)), nil + return output, aws.ToString(output.Status.Code), nil } } -func StatusSubnetEnableDNS64(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetState(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -145,13 +367,13 @@ func StatusSubnetEnableDNS64(ctx context.Context, conn *ec2.EC2, id string) retr return nil, "", err } - return output, strconv.FormatBool(aws.BoolValue(output.EnableDns64)), nil + return output, string(output.State), nil } } -func StatusSubnetEnableLniAtDeviceIndex(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetIPv6CIDRBlockAssociationState(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetIPv6CIDRBlockAssociationByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -161,13 +383,13 @@ func StatusSubnetEnableLniAtDeviceIndex(ctx context.Context, conn *ec2.EC2, id s return nil, "", err } - return output, strconv.FormatInt(aws.Int64Value(output.EnableLniAtDeviceIndex), 10), nil + return output.Ipv6CidrBlockState, string(output.Ipv6CidrBlockState.State), nil } } -func StatusSubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetAssignIPv6AddressOnCreation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -177,13 +399,13 @@ func StatusSubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx context.Context, co return nil, "", err } - return output, strconv.FormatBool(aws.BoolValue(output.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsAAAARecord)), nil + return output, strconv.FormatBool(aws.ToBool(output.AssignIpv6AddressOnCreation)), nil } } -func StatusSubnetEnableResourceNameDNSARecordOnLaunch(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetEnableDNS64(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -193,13 +415,13 @@ func StatusSubnetEnableResourceNameDNSARecordOnLaunch(ctx context.Context, conn return nil, "", err } - return output, strconv.FormatBool(aws.BoolValue(output.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsARecord)), nil + return output, strconv.FormatBool(aws.ToBool(output.EnableDns64)), nil } } -func StatusSubnetMapCustomerOwnedIPOnLaunch(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetEnableLniAtDeviceIndex(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -209,13 +431,13 @@ func StatusSubnetMapCustomerOwnedIPOnLaunch(ctx context.Context, conn *ec2.EC2, return nil, "", err } - return output, strconv.FormatBool(aws.BoolValue(output.MapCustomerOwnedIpOnLaunch)), nil + return output, strconv.FormatInt(int64(aws.ToInt32(output.EnableLniAtDeviceIndex)), 10), nil } } -func StatusSubnetMapPublicIPOnLaunch(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -225,13 +447,13 @@ func StatusSubnetMapPublicIPOnLaunch(ctx context.Context, conn *ec2.EC2, id stri return nil, "", err } - return output, strconv.FormatBool(aws.BoolValue(output.MapPublicIpOnLaunch)), nil + return output, strconv.FormatBool(aws.ToBool(output.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsAAAARecord)), nil } } -func StatusSubnetPrivateDNSHostnameTypeOnLaunch(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetEnableResourceNameDNSARecordOnLaunch(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindSubnetByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -241,13 +463,13 @@ func StatusSubnetPrivateDNSHostnameTypeOnLaunch(ctx context.Context, conn *ec2.E return nil, "", err } - return output, aws.StringValue(output.PrivateDnsNameOptionsOnLaunch.HostnameType), nil + return output, strconv.FormatBool(aws.ToBool(output.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsARecord)), nil } } -func StatusVPCCIDRBlockAssociationState(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetMapCustomerOwnedIPOnLaunch(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, _, err := FindVPCCIDRBlockAssociationByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -257,13 +479,13 @@ func StatusVPCCIDRBlockAssociationState(ctx context.Context, conn *ec2.EC2, id s return nil, "", err } - return output.CidrBlockState, aws.StringValue(output.CidrBlockState.State), nil + return output, strconv.FormatBool(aws.ToBool(output.MapCustomerOwnedIpOnLaunch)), nil } } -func StatusVPCIPv6CIDRBlockAssociationState(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetMapPublicIPOnLaunch(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, _, err := FindVPCIPv6CIDRBlockAssociationByID(ctx, conn, id) + output, err := findSubnetByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -273,16 +495,991 @@ func StatusVPCIPv6CIDRBlockAssociationState(ctx context.Context, conn *ec2.EC2, return nil, "", err } - return output.Ipv6CidrBlockState, aws.StringValue(output.Ipv6CidrBlockState.State), nil + return output, strconv.FormatBool(aws.ToBool(output.MapPublicIpOnLaunch)), nil } } -func StatusVPCPeeringConnectionActive(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusSubnetPrivateDNSHostnameTypeOnLaunch(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - // Don't call FindVPCPeeringConnectionByID as it maps useful status codes to NotFoundError. - output, err := FindVPCPeeringConnection(ctx, conn, &ec2.DescribeVpcPeeringConnectionsInput{ - VpcPeeringConnectionIds: aws.StringSlice([]string{id}), - }) + output, err := findSubnetByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.PrivateDnsNameOptionsOnLaunch.HostnameType), nil + } +} + +func statusVolume(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findEBSVolumeByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVolumeAttachment(ctx context.Context, conn *ec2.Client, volumeID, instanceID, deviceName string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVolumeAttachment(ctx, conn, volumeID, instanceID, deviceName) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVolumeModification(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVolumeModificationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.ModificationState), nil + } +} + +func statusVPC(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPCByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVPCCIDRBlockAssociationState(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, _, err := findVPCCIDRBlockAssociationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output.CidrBlockState, string(output.CidrBlockState.State), nil + } +} + +func statusVPCIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, _, err := findVPCIPv6CIDRBlockAssociationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output.Ipv6CidrBlockState, string(output.Ipv6CidrBlockState.State), nil + } +} + +func statusVPCAttributeValue(ctx context.Context, conn *ec2.Client, id string, attribute awstypes.VpcAttributeName) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + attributeValue, err := findVPCAttribute(ctx, conn, id, attribute) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return attributeValue, strconv.FormatBool(attributeValue), nil + } +} + +func statusNetworkInterface(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findNetworkInterfaceByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status), nil + } +} + +func statusNetworkInterfaceAttachment(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findNetworkInterfaceAttachmentByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status), nil + } +} + +func statusVPCEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPCEndpointByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +const ( + routeStatusReady = "ready" +) + +func statusRoute(ctx context.Context, conn *ec2.Client, routeFinder routeFinder, routeTableID, destination string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := routeFinder(ctx, conn, routeTableID, destination) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, routeStatusReady, nil + } +} + +const ( + routeTableStatusReady = "ready" +) + +func statusRouteTable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findRouteTableByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, routeTableStatusReady, nil + } +} + +func statusRouteTableAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findRouteTableAssociationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + if output.AssociationState == nil { + // In ISO partitions AssociationState can be nil. + // If the association has been found then we assume it's associated. + state := awstypes.RouteTableAssociationStateCodeAssociated + + return &awstypes.RouteTableAssociationState{State: state}, string(state), nil + } + + return output.AssociationState, string(output.AssociationState.State), nil + } +} + +func statusVPCEndpointServiceAvailable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call FindVPCEndpointServiceConfigurationByID as it maps useful status codes to NotFoundError. + output, err := findVPCEndpointServiceConfiguration(ctx, conn, &ec2.DescribeVpcEndpointServiceConfigurationsInput{ + ServiceIds: []string{id}, + }) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.ServiceState), nil + } +} + +func fetchVPCEndpointServiceDeletionStatus(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPCEndpointServiceConfigurationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.ServiceState), nil + } +} + +const ( + vpcEndpointRouteTableAssociationStatusReady = "ready" +) + +func statusVPCEndpointRouteTableAssociation(ctx context.Context, conn *ec2.Client, vpcEndpointID, routeTableID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + err := findVPCEndpointRouteTableAssociationExists(ctx, conn, vpcEndpointID, routeTableID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return "", vpcEndpointRouteTableAssociationStatusReady, nil + } +} + +func statusVPCEndpointConnectionVPCEndpoint(ctx context.Context, conn *ec2.Client, serviceID, vpcEndpointID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx, conn, serviceID, vpcEndpointID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.VpcEndpointState), nil + } +} + +func statusVPCEndpointServicePrivateDNSNameConfiguration(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPCEndpointServicePrivateDNSNameConfigurationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVPCPeeringConnectionActive(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call findVPCPeeringConnectionByID as it maps useful status codes to NotFoundError. + output, err := findVPCPeeringConnection(ctx, conn, &ec2.DescribeVpcPeeringConnectionsInput{ + VpcPeeringConnectionIds: []string{id}, + }) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusVPCPeeringConnectionDeleted(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPCPeeringConnectionByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusClientVPNEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findClientVPNEndpointByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusClientVPNEndpointClientConnectResponseOptions(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findClientVPNEndpointClientConnectResponseOptionsByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusClientVPNAuthorizationRule(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findClientVPNAuthorizationRuleByThreePartKey(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusClientVPNNetworkAssociation(ctx context.Context, conn *ec2.Client, associationID, endpointID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findClientVPNNetworkAssociationByTwoPartKey(ctx, conn, associationID, endpointID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusClientVPNRoute(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findClientVPNRouteByThreePartKey(ctx, conn, endpointID, targetSubnetID, destinationCIDR) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusVPNConnection(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPNConnectionByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVPNConnectionRoute(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPNConnectionRouteByTwoPartKey(ctx, conn, vpnConnectionID, cidrBlock) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVPNGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPNGatewayByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVPNGatewayVPCAttachment(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVPNGatewayVPCAttachmentByTwoPartKey(ctx, conn, vpnGatewayID, vpcID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusCustomerGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findCustomerGatewayByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.ToString(output.State), nil + } +} + +func statusInternetGatewayAttachmentState(ctx context.Context, conn *ec2.Client, internetGatewayID, vpcID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findInternetGatewayAttachment(ctx, conn, internetGatewayID, vpcID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusIPAM(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findIPAMByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusIPAMPool(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findIPAMPoolByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusIPAMPoolCIDR(ctx context.Context, conn *ec2.Client, cidrBlock, poolID, poolCIDRID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + if cidrBlock == "" { + output, err := findIPAMPoolCIDRByPoolCIDRIDAndPoolID(ctx, conn, poolCIDRID, poolID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + cidrBlock = aws.ToString(output.Cidr) + } + + output, err := findIPAMPoolCIDRByTwoPartKey(ctx, conn, cidrBlock, poolID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusIPAMResourceDiscovery(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findIPAMResourceDiscoveryByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusIPAMResourceDiscoveryAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findIPAMResourceDiscoveryAssociationByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusIPAMScope(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findIPAMScopeByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusImage(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findImageByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusImageBlockPublicAccess(ctx context.Context, conn *ec2.Client) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findImageBlockPublicAccessState(ctx, conn) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, aws.ToString(output), nil + } +} + +func statusTransitGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayConnect(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayConnectByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayConnectPeer(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayConnectPeerByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayMulticastDomain(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayMulticastDomainByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayMulticastDomainAssociation(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayMulticastDomainAssociationByThreePartKey(ctx, conn, multicastDomainID, attachmentID, subnetID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Subnet.State), nil + } +} + +func statusTransitGatewayPeeringAttachment(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call findTransitGatewayPeeringAttachmentByID as it maps useful status codes to NotFoundError. + output, err := findTransitGatewayPeeringAttachment(ctx, conn, &ec2.DescribeTransitGatewayPeeringAttachmentsInput{ + TransitGatewayAttachmentIds: []string{id}, + }) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayPrefixListReference(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayPrefixListReferenceByTwoPartKey(ctx, conn, transitGatewayRouteTableID, prefixListID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayStaticRoute(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayRouteTable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayRouteTableByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayPolicyTable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayPolicyTableByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayPolicyTableAssociation(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayPolicyTableAssociationByTwoPartKey(ctx, conn, transitGatewayPolicyTableID, transitGatewayAttachmentID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayRouteTableAssociation(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayRouteTableAssociationByTwoPartKey(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayRouteTablePropagation(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findTransitGatewayRouteTablePropagationByTwoPartKey(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusTransitGatewayVPCAttachment(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + // Don't call findTransitGatewayVPCAttachmentByID as it maps useful status codes to NotFoundError. + output, err := findTransitGatewayVPCAttachment(ctx, conn, &ec2.DescribeTransitGatewayVpcAttachmentsInput{ + TransitGatewayAttachmentIds: []string{id}, + }) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusEIPDomainNameAttribute(ctx context.Context, conn *ec2.Client, allocationID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findEIPDomainNameAttributeByAllocationID(ctx, conn, allocationID) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + if output.PtrRecordUpdate == nil { + return output, "", nil + } + + return output, aws.ToString(output.PtrRecordUpdate.Status), nil + } +} + +func statusSnapshotStorageTier(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findSnapshotTierStatusBySnapshotID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.StorageTier), nil + } +} + +func statusInstanceConnectEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findInstanceConnectEndpointByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.State), nil + } +} + +func statusVerifiedAccessEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findVerifiedAccessEndpointByID(ctx, conn, id) + + if tfresource.NotFound(err) { + return nil, "", nil + } + + if err != nil { + return nil, "", err + } + + return output, string(output.Status.Code), nil + } +} + +func statusFastSnapshotRestore(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string) retry.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := findFastSnapshotRestoreByTwoPartKey(ctx, conn, availabilityZone, snapshotID) if tfresource.NotFound(err) { return nil, "", nil @@ -292,13 +1489,13 @@ func StatusVPCPeeringConnectionActive(ctx context.Context, conn *ec2.EC2, id str return nil, "", err } - return output, aws.StringValue(output.Status.Code), nil + return output, string(output.State), nil } } -func StatusVPCPeeringConnectionDeleted(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusEBSSnapshotImport(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindVPCPeeringConnectionByID(ctx, conn, id) + output, err := findImportSnapshotTaskByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -308,13 +1505,13 @@ func StatusVPCPeeringConnectionDeleted(ctx context.Context, conn *ec2.EC2, id st return nil, "", err } - return output, aws.StringValue(output.Status.Code), nil + return output.SnapshotTaskDetail, aws.ToString(output.SnapshotTaskDetail.Status), nil } } -func StatusInternetGatewayAttachmentState(ctx context.Context, conn *ec2.EC2, internetGatewayID, vpcID string) retry.StateRefreshFunc { +func statusNATGatewayState(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindInternetGatewayAttachment(ctx, conn, internetGatewayID, vpcID) + output, err := findNATGatewayByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -324,13 +1521,13 @@ func StatusInternetGatewayAttachmentState(ctx context.Context, conn *ec2.EC2, in return nil, "", err } - return output, aws.StringValue(output.State), nil + return output, string(output.State), nil } } -func StatusManagedPrefixListState(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx context.Context, conn *ec2.Client, natGatewayID, allocationID string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindManagedPrefixListByID(ctx, conn, id) + output, err := findNATGatewayAddressByNATGatewayIDAndAllocationID(ctx, conn, natGatewayID, allocationID) if tfresource.NotFound(err) { return nil, "", nil @@ -340,13 +1537,13 @@ func StatusManagedPrefixListState(ctx context.Context, conn *ec2.EC2, id string) return nil, "", err } - return output, aws.StringValue(output.State), nil + return output, string(output.Status), nil } } -func StatusNetworkInterfaceStatus(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx context.Context, conn *ec2.Client, natGatewayID, privateIP string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindNetworkInterfaceByID(ctx, conn, id) + output, err := findNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx, conn, natGatewayID, privateIP) if tfresource.NotFound(err) { return nil, "", nil @@ -356,13 +1553,13 @@ func StatusNetworkInterfaceStatus(ctx context.Context, conn *ec2.EC2, id string) return nil, "", err } - return output, aws.StringValue(output.Status), nil + return output, string(output.Status), nil } } -func StatusNetworkInterfaceAttachmentStatus(ctx context.Context, conn *ec2.EC2, id string) retry.StateRefreshFunc { +func statusNetworkInsightsAnalysis(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { return func() (interface{}, string, error) { - output, err := FindNetworkInterfaceAttachmentByID(ctx, conn, id) + output, err := findNetworkInsightsAnalysisByID(ctx, conn, id) if tfresource.NotFound(err) { return nil, "", nil @@ -372,6 +1569,6 @@ func StatusNetworkInterfaceAttachmentStatus(ctx context.Context, conn *ec2.EC2, return nil, "", err } - return output, aws.StringValue(output.Status), nil + return output, string(output.Status), nil } } diff --git a/internal/service/ec2/statusv2.go b/internal/service/ec2/statusv2.go deleted file mode 100644 index a9131d8892c..00000000000 --- a/internal/service/ec2/statusv2.go +++ /dev/null @@ -1,1263 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package ec2 - -import ( - "context" - "strconv" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/ec2" - awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" -) - -func statusAvailabilityZoneGroupOptInStatus(ctx context.Context, conn *ec2.Client, name string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findAvailabilityZoneGroupByName(ctx, conn, name) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.OptInStatus), nil - } -} - -func statusCapacityReservation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findCapacityReservationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusCarrierGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findCarrierGatewayByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusFleet(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - // Don't call FindFleetByID as it maps useful status codes to NotFoundError. - output, err := findFleet(ctx, conn, &ec2.DescribeFleetsInput{ - FleetIds: []string{id}, - }) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.FleetState), nil - } -} - -func statusHost(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findHostByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusInstance(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - // Don't call findInstanceByID as it maps useful status codes to NotFoundError. - output, err := findInstance(ctx, conn, &ec2.DescribeInstancesInput{ - InstanceIds: []string{id}, - }) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State.Name), nil - } -} - -func statusInstanceIAMInstanceProfile(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - instance, err := findInstanceByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - if instance.IamInstanceProfile == nil || instance.IamInstanceProfile.Arn == nil { - return instance, "", nil - } - - name, err := instanceProfileARNToName(aws.ToString(instance.IamInstanceProfile.Arn)) - - if err != nil { - return instance, "", err - } - - return instance, name, nil - } -} - -func statusInstanceCapacityReservationSpecificationEquals(ctx context.Context, conn *ec2.Client, id string, expectedValue *awstypes.CapacityReservationSpecification) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findInstanceByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output.CapacityReservationSpecification, strconv.FormatBool(capacityReservationSpecificationResponsesEqual(output.CapacityReservationSpecification, expectedValue)), nil - } -} - -func statusInstanceMaintenanceOptionsAutoRecovery(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findInstanceByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - if v := output.MaintenanceOptions; v != nil { - return v, string(v.AutoRecovery), nil - } - - return nil, "", nil - } -} - -func statusInstanceMetadataOptions(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findInstanceByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - if output.MetadataOptions == nil { - return nil, "", nil - } - - return output.MetadataOptions, string(output.MetadataOptions.State), nil - } -} - -func statusInstanceRootBlockDeviceDeleteOnTermination(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findInstanceByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - for _, v := range output.BlockDeviceMappings { - if aws.ToString(v.DeviceName) == aws.ToString(output.RootDeviceName) && v.Ebs != nil { - return v.Ebs, strconv.FormatBool(aws.ToBool(v.Ebs.DeleteOnTermination)), nil - } - } - - return nil, "", nil - } -} - -func statusLocalGatewayRoute(ctx context.Context, conn *ec2.Client, localGatewayRouteTableID, destinationCIDRBlock string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findLocalGatewayRouteByTwoPartKey(ctx, conn, localGatewayRouteTableID, destinationCIDRBlock) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusLocalGatewayRouteTableVPCAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findLocalGatewayRouteTableVPCAssociationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output.State), nil - } -} - -func statusPlacementGroup(ctx context.Context, conn *ec2.Client, name string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findPlacementGroupByName(ctx, conn, name) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusSpotFleetActivityStatus(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findSpotFleetRequestByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.ActivityStatus), nil - } -} - -func statusSpotFleetRequest(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - // Don't call FindSpotFleetRequestByID as it maps useful status codes to NotFoundError. - output, err := findSpotFleetRequest(ctx, conn, &ec2.DescribeSpotFleetRequestsInput{ - SpotFleetRequestIds: []string{id}, - }) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.SpotFleetRequestState), nil - } -} - -func statusSpotInstanceRequest(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findSpotInstanceRequestByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output.Status.Code), nil - } -} - -func statusVolume(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findEBSVolumeByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVolumeAttachment(ctx context.Context, conn *ec2.Client, volumeID, instanceID, deviceName string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVolumeAttachment(ctx, conn, volumeID, instanceID, deviceName) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVolumeModification(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVolumeModificationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.ModificationState), nil - } -} - -func statusVPC(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPCByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVPCIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, _, err := findVPCIPv6CIDRBlockAssociationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output.Ipv6CidrBlockState, string(output.Ipv6CidrBlockState.State), nil - } -} - -func statusVPCAttributeValue(ctx context.Context, conn *ec2.Client, id string, attribute awstypes.VpcAttributeName) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - attributeValue, err := findVPCAttribute(ctx, conn, id, attribute) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return attributeValue, strconv.FormatBool(attributeValue), nil - } -} - -func statusNetworkInterface(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findNetworkInterfaceByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status), nil - } -} - -func statusNetworkInterfaceAttachment(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findNetworkInterfaceAttachmentByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status), nil - } -} - -func statusVPCEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPCEndpointByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -const ( - routeStatusReady = "ready" -) - -func statusRoute(ctx context.Context, conn *ec2.Client, routeFinder routeFinder, routeTableID, destination string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := routeFinder(ctx, conn, routeTableID, destination) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, routeStatusReady, nil - } -} - -const ( - routeTableStatusReady = "ready" -) - -func statusRouteTable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findRouteTableByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, routeTableStatusReady, nil - } -} - -func statusRouteTableAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findRouteTableAssociationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - if output.AssociationState == nil { - // In ISO partitions AssociationState can be nil. - // If the association has been found then we assume it's associated. - state := awstypes.RouteTableAssociationStateCodeAssociated - - return &awstypes.RouteTableAssociationState{State: state}, string(state), nil - } - - return output.AssociationState, string(output.AssociationState.State), nil - } -} - -func statusVPCEndpointServiceAvailable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - // Don't call FindVPCEndpointServiceConfigurationByID as it maps useful status codes to NotFoundError. - output, err := findVPCEndpointServiceConfiguration(ctx, conn, &ec2.DescribeVpcEndpointServiceConfigurationsInput{ - ServiceIds: []string{id}, - }) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.ServiceState), nil - } -} - -func fetchVPCEndpointServiceDeletionStatus(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPCEndpointServiceConfigurationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.ServiceState), nil - } -} - -const ( - VPCEndpointRouteTableAssociationStatusReady = "ready" -) - -func statusVPCEndpointRouteTableAssociation(ctx context.Context, conn *ec2.Client, vpcEndpointID, routeTableID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - err := findVPCEndpointRouteTableAssociationExists(ctx, conn, vpcEndpointID, routeTableID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return "", VPCEndpointRouteTableAssociationStatusReady, nil - } -} - -func statusVPCEndpointConnectionVPCEndpoint(ctx context.Context, conn *ec2.Client, serviceID, vpcEndpointID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx, conn, serviceID, vpcEndpointID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.VpcEndpointState), nil - } -} - -func statusVPCEndpointServicePrivateDNSNameConfiguration(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPCEndpointServicePrivateDNSNameConfigurationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusClientVPNEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findClientVPNEndpointByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status.Code), nil - } -} - -func statusClientVPNEndpointClientConnectResponseOptions(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findClientVPNEndpointClientConnectResponseOptionsByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status.Code), nil - } -} - -func statusClientVPNAuthorizationRule(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findClientVPNAuthorizationRuleByThreePartKey(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status.Code), nil - } -} - -func statusClientVPNNetworkAssociation(ctx context.Context, conn *ec2.Client, associationID, endpointID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findClientVPNNetworkAssociationByTwoPartKey(ctx, conn, associationID, endpointID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status.Code), nil - } -} - -func statusClientVPNRoute(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findClientVPNRouteByThreePartKey(ctx, conn, endpointID, targetSubnetID, destinationCIDR) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status.Code), nil - } -} - -func statusVPNConnection(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPNConnectionByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVPNConnectionRoute(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPNConnectionRouteByTwoPartKey(ctx, conn, vpnConnectionID, cidrBlock) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVPNGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPNGatewayByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVPNGatewayVPCAttachment(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVPNGatewayVPCAttachmentByTwoPartKey(ctx, conn, vpnGatewayID, vpcID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusCustomerGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findCustomerGatewayByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output.State), nil - } -} - -func statusIPAM(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findIPAMByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusIPAMPool(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findIPAMPoolByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusIPAMPoolCIDR(ctx context.Context, conn *ec2.Client, cidrBlock, poolID, poolCIDRID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - if cidrBlock == "" { - output, err := findIPAMPoolCIDRByPoolCIDRIDAndPoolID(ctx, conn, poolCIDRID, poolID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - cidrBlock = aws.ToString(output.Cidr) - } - - output, err := findIPAMPoolCIDRByTwoPartKey(ctx, conn, cidrBlock, poolID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusIPAMResourceDiscovery(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findIPAMResourceDiscoveryByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusIPAMResourceDiscoveryAssociation(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findIPAMResourceDiscoveryAssociationByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusIPAMScope(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findIPAMScopeByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusImage(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findImageByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusImageBlockPublicAccess(ctx context.Context, conn *ec2.Client) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findImageBlockPublicAccessState(ctx, conn) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, aws.ToString(output), nil - } -} - -func statusTransitGateway(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayConnect(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayConnectByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayConnectPeer(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayConnectPeerByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayMulticastDomain(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayMulticastDomainByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayMulticastDomainAssociation(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayMulticastDomainAssociationByThreePartKey(ctx, conn, multicastDomainID, attachmentID, subnetID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Subnet.State), nil - } -} - -func statusTransitGatewayPeeringAttachment(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - // Don't call findTransitGatewayPeeringAttachmentByID as it maps useful status codes to NotFoundError. - output, err := findTransitGatewayPeeringAttachment(ctx, conn, &ec2.DescribeTransitGatewayPeeringAttachmentsInput{ - TransitGatewayAttachmentIds: []string{id}, - }) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayPrefixListReference(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayPrefixListReferenceByTwoPartKey(ctx, conn, transitGatewayRouteTableID, prefixListID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayStaticRoute(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayRouteTable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayRouteTableByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayPolicyTable(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayPolicyTableByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayPolicyTableAssociation(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayPolicyTableAssociationByTwoPartKey(ctx, conn, transitGatewayPolicyTableID, transitGatewayAttachmentID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayRouteTableAssociation(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayRouteTableAssociationByTwoPartKey(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayRouteTablePropagation(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findTransitGatewayRouteTablePropagationByTwoPartKey(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusTransitGatewayVPCAttachment(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - // Don't call findTransitGatewayVPCAttachmentByID as it maps useful status codes to NotFoundError. - output, err := findTransitGatewayVPCAttachment(ctx, conn, &ec2.DescribeTransitGatewayVpcAttachmentsInput{ - TransitGatewayAttachmentIds: []string{id}, - }) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusEIPDomainNameAttribute(ctx context.Context, conn *ec2.Client, allocationID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findEIPDomainNameAttributeByAllocationID(ctx, conn, allocationID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - if output.PtrRecordUpdate == nil { - return output, "", nil - } - - return output, aws.ToString(output.PtrRecordUpdate.Status), nil - } -} - -func statusSnapshotStorageTier(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findSnapshotTierStatusBySnapshotID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.StorageTier), nil - } -} - -func statusInstanceConnectEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findInstanceConnectEndpointByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusVerifiedAccessEndpoint(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findVerifiedAccessEndpointByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status.Code), nil - } -} - -func statusFastSnapshotRestore(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findFastSnapshotRestoreByTwoPartKey(ctx, conn, availabilityZone, snapshotID) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.State), nil - } -} - -func statusEBSSnapshotImport(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findImportSnapshotTaskByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output.SnapshotTaskDetail, aws.ToString(output.SnapshotTaskDetail.Status), nil - } -} - -func statusNetworkInsightsAnalysis(ctx context.Context, conn *ec2.Client, id string) retry.StateRefreshFunc { - return func() (interface{}, string, error) { - output, err := findNetworkInsightsAnalysisByID(ctx, conn, id) - - if tfresource.NotFound(err) { - return nil, "", nil - } - - if err != nil { - return nil, "", err - } - - return output, string(output.Status), nil - } -} diff --git a/internal/service/ec2/sweep.go b/internal/service/ec2/sweep.go index 56172128e7e..03ba5092a46 100644 --- a/internal/service/ec2/sweep.go +++ b/internal/service/ec2/sweep.go @@ -820,7 +820,7 @@ func sweepEgressOnlyInternetGateways(region string) error { } for _, v := range page.EgressOnlyInternetGateways { - r := ResourceEgressOnlyInternetGateway() + r := resourceEgressOnlyInternetGateway() d := r.Data(nil) d.SetId(aws.ToString(v.EgressOnlyInternetGatewayId)) @@ -952,7 +952,7 @@ func sweepFlowLogs(region string) error { } for _, flowLog := range page.FlowLogs { - r := ResourceFlowLog() + r := resourceFlowLog() d := r.Data(nil) d.SetId(aws.ToString(flowLog.FlowLogId)) @@ -1124,7 +1124,7 @@ func sweepInternetGateways(region string) error { continue } - r := ResourceInternetGateway() + r := resourceInternetGateway() d := r.Data(nil) d.SetId(internetGatewayID) if len(internetGateway.Attachments) > 0 { @@ -1247,7 +1247,7 @@ func sweepNATGateways(region string) error { } for _, v := range page.NatGateways { - r := ResourceNATGateway() + r := resourceNATGateway() d := r.Data(nil) d.SetId(aws.ToString(v.NatGatewayId)) @@ -1393,7 +1393,7 @@ func sweepManagedPrefixLists(region string) error { continue } - r := ResourceManagedPrefixList() + r := resourceManagedPrefixList() d := r.Data(nil) d.SetId(aws.ToString(v.PrefixListId)) @@ -1819,7 +1819,7 @@ func sweepSubnets(region string) error { continue } - r := ResourceSubnet() + r := resourceSubnet() d := r.Data(nil) d.SetId(aws.ToString(v.SubnetId)) @@ -2282,7 +2282,7 @@ func sweepVPCDHCPOptions(region string) error { continue } - r := ResourceVPCDHCPOptions() + r := resourceVPCDHCPOptions() d := r.Data(nil) d.SetId(aws.ToString(v.DhcpOptionsId)) @@ -2380,9 +2380,9 @@ func sweepVPCEndpointConnectionAccepters(region string) error { } for _, v := range page.VpcEndpointConnections { - id := VPCEndpointConnectionAccepterCreateResourceID(aws.ToString(v.ServiceId), aws.ToString(v.VpcEndpointId)) + id := vpcEndpointConnectionAccepterCreateResourceID(aws.ToString(v.ServiceId), aws.ToString(v.VpcEndpointId)) - r := ResourceVPCEndpointConnectionAccepter() + r := resourceVPCEndpointConnectionAccepter() d := r.Data(nil) d.SetId(id) @@ -2432,7 +2432,7 @@ func sweepVPCEndpointServices(region string) error { continue } - r := ResourceVPCEndpointService() + r := resourceVPCEndpointService() d := r.Data(nil) d.SetId(id) @@ -2475,7 +2475,7 @@ func sweepVPCPeeringConnections(region string) error { } for _, v := range page.VpcPeeringConnections { - r := ResourceVPCPeeringConnection() + r := resourceVPCPeeringConnection() d := r.Data(nil) d.SetId(aws.ToString(v.VpcPeeringConnectionId)) @@ -2523,7 +2523,7 @@ func sweepVPCs(region string) error { continue } - r := ResourceVPC() + r := resourceVPC() d := r.Data(nil) d.SetId(aws.ToString(v.VpcId)) @@ -2656,7 +2656,7 @@ func sweepCustomerGateways(region string) error { } for _, v := range output.CustomerGateways { - if aws.ToString(v.State) == CustomerGatewayStateDeleted { + if aws.ToString(v.State) == customerGatewayStateDeleted { continue } @@ -2837,8 +2837,8 @@ func sweepNetworkPerformanceMetricSubscriptions(region string) error { } for _, v := range page.Subscriptions { - r := ResourceNetworkPerformanceMetricSubscription() - id := NetworkPerformanceMetricSubscriptionCreateResourceID(aws.ToString(v.Source), aws.ToString(v.Destination), string(v.Metric), string(v.Statistic)) + r := resourceNetworkPerformanceMetricSubscription() + id := networkPerformanceMetricSubscriptionCreateResourceID(aws.ToString(v.Source), aws.ToString(v.Destination), string(v.Metric), string(v.Statistic)) d := r.Data(nil) d.SetId(id) @@ -2924,7 +2924,7 @@ func sweepVerifiedAccessEndpoints(region string) error { } for _, v := range page.VerifiedAccessEndpoints { - r := ResourceVerifiedAccessEndpoint() + r := resourceVerifiedAccessEndpoint() d := r.Data(nil) d.SetId(aws.ToString(v.VerifiedAccessEndpointId)) @@ -2967,7 +2967,7 @@ func sweepVerifiedAccessGroups(region string) error { } for _, v := range page.VerifiedAccessGroups { - r := ResourceVerifiedAccessGroup() + r := resourceVerifiedAccessGroup() d := r.Data(nil) d.SetId(aws.ToString(v.VerifiedAccessGroupId)) @@ -3010,7 +3010,7 @@ func sweepVerifiedAccessInstances(region string) error { } for _, v := range page.VerifiedAccessInstances { - r := ResourceVerifiedAccessInstance() + r := resourceVerifiedAccessInstance() d := r.Data(nil) d.SetId(aws.ToString(v.VerifiedAccessInstanceId)) @@ -3053,7 +3053,7 @@ func sweepVerifiedAccessTrustProviders(region string) error { } for _, v := range page.VerifiedAccessTrustProviders { - r := ResourceVerifiedAccessTrustProvider() + r := resourceVerifiedAccessTrustProvider() d := r.Data(nil) d.SetId(aws.ToString(v.VerifiedAccessTrustProviderId)) @@ -3101,9 +3101,9 @@ func sweepVerifiedAccessTrustProviderAttachments(region string) error { for _, v := range v.VerifiedAccessTrustProviders { vatpID := aws.ToString(v.VerifiedAccessTrustProviderId) - r := ResourceVerifiedAccessInstanceTrustProviderAttachment() + r := resourceVerifiedAccessInstanceTrustProviderAttachment() d := r.Data(nil) - d.SetId(VerifiedAccessInstanceTrustProviderAttachmentCreateResourceID(vaiID, vatpID)) + d.SetId(verifiedAccessInstanceTrustProviderAttachmentCreateResourceID(vaiID, vatpID)) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } diff --git a/internal/service/ec2/tag_gen.go b/internal/service/ec2/tag_gen.go index b7950039771..f4bff2ab104 100644 --- a/internal/service/ec2/tag_gen.go +++ b/internal/service/ec2/tag_gen.go @@ -54,7 +54,7 @@ func resourceTagCreate(ctx context.Context, d *schema.ResourceData, meta interfa key := d.Get(names.AttrKey).(string) value := d.Get(names.AttrValue).(string) - if err := createTagsV2(ctx, conn, identifier, TagsV2(tftags.New(ctx, map[string]string{key: value}))); err != nil { + if err := createTags(ctx, conn, identifier, Tags(tftags.New(ctx, map[string]string{key: value}))); err != nil { return sdkdiag.AppendErrorf(diags, "creating %s resource (%s) tag (%s): %s", names.EC2, identifier, key, err) } @@ -100,7 +100,7 @@ func resourceTagUpdate(ctx context.Context, d *schema.ResourceData, meta interfa return sdkdiag.AppendFromErr(diags, err) } - if err := updateTagsV2(ctx, conn, identifier, nil, map[string]string{key: d.Get(names.AttrValue).(string)}); err != nil { + if err := updateTags(ctx, conn, identifier, nil, map[string]string{key: d.Get(names.AttrValue).(string)}); err != nil { return sdkdiag.AppendErrorf(diags, "updating %s resource (%s) tag (%s): %s", names.EC2, identifier, key, err) } @@ -116,7 +116,7 @@ func resourceTagDelete(ctx context.Context, d *schema.ResourceData, meta interfa return sdkdiag.AppendFromErr(diags, err) } - if err := updateTagsV2(ctx, conn, identifier, map[string]string{key: d.Get(names.AttrValue).(string)}, nil); err != nil { + if err := updateTags(ctx, conn, identifier, map[string]string{key: d.Get(names.AttrValue).(string)}, nil); err != nil { return sdkdiag.AppendErrorf(diags, "deleting %s resource (%s) tag (%s): %s", names.EC2, identifier, key, err) } diff --git a/internal/service/ec2/tags.go b/internal/service/ec2/tags.go index 1d13fbcc690..093d6d1b133 100644 --- a/internal/service/ec2/tags.go +++ b/internal/service/ec2/tags.go @@ -8,10 +8,8 @@ import ( "fmt" "time" + "github.com/aws/aws-sdk-go-v2/service/ec2" awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -19,16 +17,16 @@ import ( const eventualConsistencyTimeout = 5 * time.Minute -// createTags creates EC2 service tags for new resources. -func createTags(ctx context.Context, conn ec2iface.EC2API, identifier string, tags []*ec2.Tag) error { +// createTags creates ec2 service tags for new resources. +func createTags(ctx context.Context, conn *ec2.Client, identifier string, tags []awstypes.Tag, optFns ...func(*ec2.Options)) error { if len(tags) == 0 { return nil } - newTagsMap := KeyValueTags(ctx, tags) + newTagsMap := keyValueTags(ctx, tags) _, err := tfresource.RetryWhenAWSErrCodeContains(ctx, eventualConsistencyTimeout, func() (interface{}, error) { - return nil, updateTags(ctx, conn, identifier, nil, newTagsMap) + return nil, updateTags(ctx, conn, identifier, nil, newTagsMap, optFns...) }, ".NotFound") if err != nil { @@ -38,47 +36,47 @@ func createTags(ctx context.Context, conn ec2iface.EC2API, identifier string, ta return nil } -// tagSpecificationsFromMap returns the tag specifications for the given tag key/value map and resource type. -func tagSpecificationsFromMap(ctx context.Context, m map[string]interface{}, t awstypes.ResourceType) []awstypes.TagSpecification { - if len(m) == 0 { +// getTagSpecificationsIn returns AWS SDK for Go v2 EC2 service tags from Context. +// nil is returned if there are no input tags. +func getTagSpecificationsIn(ctx context.Context, resourceType awstypes.ResourceType) []awstypes.TagSpecification { + tags := getTagsIn(ctx) + + if len(tags) == 0 { return nil } return []awstypes.TagSpecification{ { - ResourceType: t, - Tags: TagsV2(tftags.New(ctx, m).IgnoreAWS()), + ResourceType: resourceType, + Tags: tags, }, } } -// tagSpecificationsFromKeyValue returns the tag specifications for the given tag key/value tags and resource type. -func tagSpecificationsFromKeyValue(tags tftags.KeyValueTags, resourceType string) []awstypes.TagSpecification { - if len(tags) == 0 { +// tagSpecificationsFromMap returns the tag specifications for the given tag key/value map and resource type. +func tagSpecificationsFromMap(ctx context.Context, m map[string]interface{}, t awstypes.ResourceType) []awstypes.TagSpecification { + if len(m) == 0 { return nil } return []awstypes.TagSpecification{ { - ResourceType: awstypes.ResourceType(resourceType), - Tags: TagsV2(tags.IgnoreAWS()), + ResourceType: t, + Tags: Tags(tftags.New(ctx, m).IgnoreAWS()), }, } } -// getTagSpecificationsIn returns AWS SDK for Go v1 EC2 service tags from Context. -// nil is returned if there are no input tags. -func getTagSpecificationsIn(ctx context.Context, resourceType string) []*ec2.TagSpecification { - tags := getTagsIn(ctx) - +// tagSpecificationsFromKeyValue returns the tag specifications for the given tag key/value tags and resource type. +func tagSpecificationsFromKeyValue(tags tftags.KeyValueTags, resourceType string) []awstypes.TagSpecification { if len(tags) == 0 { return nil } - return []*ec2.TagSpecification{ + return []awstypes.TagSpecification{ { - ResourceType: aws.String(resourceType), - Tags: tags, + ResourceType: awstypes.ResourceType(resourceType), + Tags: Tags(tags.IgnoreAWS()), }, } } diff --git a/internal/service/ec2/tags_gen.go b/internal/service/ec2/tags_gen.go index ed9dadef841..587312b1b58 100644 --- a/internal/service/ec2/tags_gen.go +++ b/internal/service/ec2/tags_gen.go @@ -5,56 +5,86 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/logging" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/types/option" "github.com/hashicorp/terraform-provider-aws/names" ) +// findTag fetches an individual ec2 service tag for a resource. +// Returns whether the key value and any errors. A NotFoundError is used to signal that no value was found. +// This function will optimise the handling over listTags, if possible. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func findTag(ctx context.Context, conn *ec2.Client, identifier, key string, optFns ...func(*ec2.Options)) (*string, error) { + input := &ec2.DescribeTagsInput{ + Filters: []awstypes.Filter{ + { + Name: aws.String("resource-id"), + Values: []string{identifier}, + }, + { + Name: aws.String(names.AttrKey), + Values: []string{key}, + }, + }, + } + + output, err := conn.DescribeTags(ctx, input, optFns...) + + if err != nil { + return nil, err + } + + listTags := keyValueTags(ctx, output.Tags) + + if !listTags.KeyExists(key) { + return nil, tfresource.NewEmptyResultError(nil) + } + + return listTags.KeyValue(key), nil +} + // listTags lists ec2 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 ec2iface.EC2API, identifier string) (tftags.KeyValueTags, error) { +func listTags(ctx context.Context, conn *ec2.Client, identifier string, optFns ...func(*ec2.Options)) (tftags.KeyValueTags, error) { input := &ec2.DescribeTagsInput{ - Filters: []*ec2.Filter{ + Filters: []awstypes.Filter{ { Name: aws.String("resource-id"), - Values: []*string{aws.String(identifier)}, + Values: []string{identifier}, }, }, } - var output []*ec2.TagDescription + var output []awstypes.TagDescription + + pages := ec2.NewDescribeTagsPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx, optFns...) - err := conn.DescribeTagsPagesWithContext(ctx, input, func(page *ec2.DescribeTagsOutput, lastPage bool) bool { - if page == nil { - return !lastPage + if err != nil { + return tftags.New(ctx, nil), err } for _, v := range page.Tags { - if v != nil { - output = append(output, v) - } + output = append(output, v) } - - return !lastPage - }) - - if err != nil { - return tftags.New(ctx, nil), err } - return KeyValueTags(ctx, output), nil + return keyValueTags(ctx, output), nil } // ListTags lists ec2 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).EC2Conn(ctx), identifier) + tags, err := listTags(ctx, meta.(*conns.AWSClient).EC2Client(ctx), identifier) if err != nil { return err @@ -70,11 +100,11 @@ func (p *servicePackage) ListTags(ctx context.Context, meta any, identifier stri // []*SERVICE.Tag handling // Tags returns ec2 service tags. -func Tags(tags tftags.KeyValueTags) []*ec2.Tag { - result := make([]*ec2.Tag, 0, len(tags)) +func Tags(tags tftags.KeyValueTags) []awstypes.Tag { + result := make([]awstypes.Tag, 0, len(tags)) for k, v := range tags.Map() { - tag := &ec2.Tag{ + tag := awstypes.Tag{ Key: aws.String(k), Value: aws.String(v), } @@ -85,26 +115,26 @@ func Tags(tags tftags.KeyValueTags) []*ec2.Tag { return result } -// KeyValueTags creates tftags.KeyValueTags from ec2 service tags. +// keyValueTags creates tftags.KeyValueTags from ec2 service tags. // // Accepts the following types: -// - []*ec2.Tag -// - []*ec2.TagDescription -func KeyValueTags(ctx context.Context, tags any) tftags.KeyValueTags { +// - []awstypes.Tag +// - []awstypes.TagDescription +func keyValueTags(ctx context.Context, tags any) tftags.KeyValueTags { switch tags := tags.(type) { - case []*ec2.Tag: + case []awstypes.Tag: m := make(map[string]*string, len(tags)) for _, tag := range tags { - m[aws.StringValue(tag.Key)] = tag.Value + m[aws.ToString(tag.Key)] = tag.Value } return tftags.New(ctx, m) - case []*ec2.TagDescription: + case []awstypes.TagDescription: m := make(map[string]*string, len(tags)) for _, tag := range tags { - m[aws.StringValue(tag.Key)] = tag.Value + m[aws.ToString(tag.Key)] = tag.Value } return tftags.New(ctx, m) @@ -115,7 +145,7 @@ func KeyValueTags(ctx context.Context, tags any) tftags.KeyValueTags { // getTagsIn returns ec2 service tags from Context. // nil is returned if there are no input tags. -func getTagsIn(ctx context.Context) []*ec2.Tag { +func getTagsIn(ctx context.Context) []awstypes.Tag { if inContext, ok := tftags.FromContext(ctx); ok { if tags := Tags(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { return tags @@ -128,14 +158,14 @@ func getTagsIn(ctx context.Context) []*ec2.Tag { // setTagsOut sets ec2 service tags in Context. func setTagsOut(ctx context.Context, tags any) { if inContext, ok := tftags.FromContext(ctx); ok { - inContext.TagsOut = option.Some(KeyValueTags(ctx, tags)) + inContext.TagsOut = option.Some(keyValueTags(ctx, tags)) } } // updateTags updates ec2 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 ec2iface.EC2API, identifier string, oldTagsMap, newTagsMap any) error { +func updateTags(ctx context.Context, conn *ec2.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*ec2.Options)) error { oldTags := tftags.New(ctx, oldTagsMap) newTags := tftags.New(ctx, newTagsMap) @@ -145,11 +175,11 @@ func updateTags(ctx context.Context, conn ec2iface.EC2API, identifier string, ol removedTags = removedTags.IgnoreSystem(names.EC2) if len(removedTags) > 0 { input := &ec2.DeleteTagsInput{ - Resources: aws.StringSlice([]string{identifier}), + Resources: []string{identifier}, Tags: Tags(removedTags), } - _, err := conn.DeleteTagsWithContext(ctx, input) + _, err := conn.DeleteTags(ctx, input, optFns...) if err != nil { return fmt.Errorf("untagging resource (%s): %w", identifier, err) @@ -160,11 +190,11 @@ func updateTags(ctx context.Context, conn ec2iface.EC2API, identifier string, ol updatedTags = updatedTags.IgnoreSystem(names.EC2) if len(updatedTags) > 0 { input := &ec2.CreateTagsInput{ - Resources: aws.StringSlice([]string{identifier}), + Resources: []string{identifier}, Tags: Tags(updatedTags), } - _, err := conn.CreateTagsWithContext(ctx, input) + _, err := conn.CreateTags(ctx, input, optFns...) if err != nil { return fmt.Errorf("tagging resource (%s): %w", identifier, err) @@ -177,5 +207,5 @@ func updateTags(ctx context.Context, conn ec2iface.EC2API, identifier string, ol // UpdateTags updates ec2 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).EC2Conn(ctx), identifier, oldTags, newTags) + return updateTags(ctx, meta.(*conns.AWSClient).EC2Client(ctx), identifier, oldTags, newTags) } diff --git a/internal/service/ec2/tagsv2.go b/internal/service/ec2/tagsv2.go deleted file mode 100644 index 16a464dbcd8..00000000000 --- a/internal/service/ec2/tagsv2.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package ec2 - -import ( - "context" - "fmt" - - "github.com/aws/aws-sdk-go-v2/service/ec2" - "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" -) - -// createTags creates ec2 service tags for new resources. -func createTagsV2(ctx context.Context, conn *ec2.Client, identifier string, tags []types.Tag, optFns ...func(*ec2.Options)) error { - if len(tags) == 0 { - return nil - } - - newTagsMap := keyValueTagsV2(ctx, tags) - - _, err := tfresource.RetryWhenAWSErrCodeContains(ctx, eventualConsistencyTimeout, func() (interface{}, error) { - return nil, updateTagsV2(ctx, conn, identifier, nil, newTagsMap, optFns...) - }, ".NotFound") - - if err != nil { - return fmt.Errorf("tagging resource (%s): %w", identifier, err) - } - - return nil -} - -// getTagSpecificationsInV2 returns AWS SDK for Go v2 EC2 service tags from Context. -// nil is returned if there are no input tags. -func getTagSpecificationsInV2(ctx context.Context, resourceType types.ResourceType) []types.TagSpecification { - tags := getTagsInV2(ctx) - - if len(tags) == 0 { - return nil - } - - return []types.TagSpecification{ - { - ResourceType: resourceType, - Tags: tags, - }, - } -} diff --git a/internal/service/ec2/tagsv2_gen.go b/internal/service/ec2/tagsv2_gen.go deleted file mode 100644 index 5de8449bbbc..00000000000 --- a/internal/service/ec2/tagsv2_gen.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by internal/generate/tags/main.go; DO NOT EDIT. -package ec2 - -import ( - "context" - "fmt" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/ec2" - awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/terraform-plugin-log/tflog" - "github.com/hashicorp/terraform-provider-aws/internal/logging" - tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" - "github.com/hashicorp/terraform-provider-aws/internal/types/option" - "github.com/hashicorp/terraform-provider-aws/names" -) - -// findTag fetches an individual ec2 service tag for a resource. -// Returns whether the key value and any errors. A NotFoundError is used to signal that no value was found. -// This function will optimise the handling over listTags, if possible. -// The identifier is typically the Amazon Resource Name (ARN), although -// it may also be a different identifier depending on the service. -func findTag(ctx context.Context, conn *ec2.Client, identifier, key string, optFns ...func(*ec2.Options)) (*string, error) { - input := &ec2.DescribeTagsInput{ - Filters: []awstypes.Filter{ - { - Name: aws.String("resource-id"), - Values: []string{identifier}, - }, - { - Name: aws.String(names.AttrKey), - Values: []string{key}, - }, - }, - } - - output, err := conn.DescribeTags(ctx, input, optFns...) - - if err != nil { - return nil, err - } - - listTags := keyValueTagsV2(ctx, output.Tags) - - if !listTags.KeyExists(key) { - return nil, tfresource.NewEmptyResultError(nil) - } - - return listTags.KeyValue(key), nil -} - -// []*SERVICE.Tag handling - -// TagsV2 returns ec2 service tags. -func TagsV2(tags tftags.KeyValueTags) []awstypes.Tag { - result := make([]awstypes.Tag, 0, len(tags)) - - for k, v := range tags.Map() { - tag := awstypes.Tag{ - Key: aws.String(k), - Value: aws.String(v), - } - - result = append(result, tag) - } - - return result -} - -// keyValueTagsV2 creates tftags.KeyValueTags from ec2 service tags. -// -// Accepts the following types: -// - []awstypes.Tag -// - []awstypes.TagDescription -func keyValueTagsV2(ctx context.Context, tags any) tftags.KeyValueTags { - switch tags := tags.(type) { - case []awstypes.Tag: - m := make(map[string]*string, len(tags)) - - for _, tag := range tags { - m[aws.ToString(tag.Key)] = tag.Value - } - - return tftags.New(ctx, m) - case []awstypes.TagDescription: - m := make(map[string]*string, len(tags)) - - for _, tag := range tags { - m[aws.ToString(tag.Key)] = tag.Value - } - - return tftags.New(ctx, m) - default: - return tftags.New(ctx, nil) - } -} - -// getTagsInV2 returns ec2 service tags from Context. -// nil is returned if there are no input tags. -func getTagsInV2(ctx context.Context) []awstypes.Tag { - if inContext, ok := tftags.FromContext(ctx); ok { - if tags := TagsV2(inContext.TagsIn.UnwrapOrDefault()); len(tags) > 0 { - return tags - } - } - - return nil -} - -// setTagsOutV2 sets ec2 service tags in Context. -func setTagsOutV2(ctx context.Context, tags any) { - if inContext, ok := tftags.FromContext(ctx); ok { - inContext.TagsOut = option.Some(keyValueTagsV2(ctx, tags)) - } -} - -// updateTagsV2 updates ec2 service tags. -// The identifier is typically the Amazon Resource Name (ARN), although -// it may also be a different identifier depending on the service. -func updateTagsV2(ctx context.Context, conn *ec2.Client, identifier string, oldTagsMap, newTagsMap any, optFns ...func(*ec2.Options)) error { - oldTags := tftags.New(ctx, oldTagsMap) - newTags := tftags.New(ctx, newTagsMap) - - ctx = tflog.SetField(ctx, logging.KeyResourceId, identifier) - - removedTags := oldTags.Removed(newTags) - removedTags = removedTags.IgnoreSystem(names.EC2) - if len(removedTags) > 0 { - input := &ec2.DeleteTagsInput{ - Resources: []string{identifier}, - Tags: TagsV2(removedTags), - } - - _, err := conn.DeleteTags(ctx, input, optFns...) - - if err != nil { - return fmt.Errorf("untagging resource (%s): %w", identifier, err) - } - } - - updatedTags := oldTags.Updated(newTags) - updatedTags = updatedTags.IgnoreSystem(names.EC2) - if len(updatedTags) > 0 { - input := &ec2.CreateTagsInput{ - Resources: []string{identifier}, - Tags: TagsV2(updatedTags), - } - - _, err := conn.CreateTags(ctx, input, optFns...) - - if err != nil { - return fmt.Errorf("tagging resource (%s): %w", identifier, err) - } - } - - return nil -} diff --git a/internal/service/ec2/transitgateway_.go b/internal/service/ec2/transitgateway_.go index e68649de615..1a282e8f6f3 100644 --- a/internal/service/ec2/transitgateway_.go +++ b/internal/service/ec2/transitgateway_.go @@ -156,7 +156,7 @@ func resourceTransitGatewayCreate(ctx context.Context, d *schema.ResourceData, m MulticastSupport: awstypes.MulticastSupportValue(d.Get("multicast_support").(string)), VpnEcmpSupport: awstypes.VpnEcmpSupportValue(d.Get("vpn_ecmp_support").(string)), }, - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGateway), } if v, ok := d.GetOk("amazon_side_asn"); ok { @@ -217,7 +217,7 @@ func resourceTransitGatewayRead(ctx context.Context, d *schema.ResourceData, met d.Set("transit_gateway_cidr_blocks", transitGateway.Options.TransitGatewayCidrBlocks) d.Set("vpn_ecmp_support", transitGateway.Options.VpnEcmpSupport) - setTagsOutV2(ctx, transitGateway.Tags) + setTagsOut(ctx, transitGateway.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_attachment_data_source.go b/internal/service/ec2/transitgateway_attachment_data_source.go index 7a7041e40d7..558de145622 100644 --- a/internal/service/ec2/transitgateway_attachment_data_source.go +++ b/internal/service/ec2/transitgateway_attachment_data_source.go @@ -80,7 +80,7 @@ func dataSourceTransitGatewayAttachmentRead(ctx context.Context, d *schema.Resou input := &ec2.DescribeTransitGatewayAttachmentsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -126,7 +126,7 @@ func dataSourceTransitGatewayAttachmentRead(ctx context.Context, d *schema.Resou d.Set(names.AttrTransitGatewayID, transitGatewayAttachment.TransitGatewayId) d.Set("transit_gateway_owner_id", transitGatewayAttachment.TransitGatewayOwnerId) - setTagsOutV2(ctx, transitGatewayAttachment.Tags) + setTagsOut(ctx, transitGatewayAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_attachments_data_source.go b/internal/service/ec2/transitgateway_attachments_data_source.go index 28c493cc536..c5326b1d9ea 100644 --- a/internal/service/ec2/transitgateway_attachments_data_source.go +++ b/internal/service/ec2/transitgateway_attachments_data_source.go @@ -44,13 +44,13 @@ func dataSourceTransitGatewayAttachmentsRead(ctx context.Context, d *schema.Reso input := &ec2.DescribeTransitGatewayAttachmentsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) if v, ok := d.GetOk(names.AttrTags); ok { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, v.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, v.(map[string]interface{}))), )...) } diff --git a/internal/service/ec2/transitgateway_connect.go b/internal/service/ec2/transitgateway_connect.go index e7175622e78..9f67f2a776d 100644 --- a/internal/service/ec2/transitgateway_connect.go +++ b/internal/service/ec2/transitgateway_connect.go @@ -92,7 +92,7 @@ func resourceTransitGatewayConnectCreate(ctx context.Context, d *schema.Resource Options: &awstypes.CreateTransitGatewayConnectRequestOptions{ Protocol: awstypes.ProtocolValue(d.Get(names.AttrProtocol).(string)), }, - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayAttachment), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayAttachment), TransportTransitGatewayAttachmentId: aws.String(transportAttachmentID), } @@ -202,7 +202,7 @@ func resourceTransitGatewayConnectRead(ctx context.Context, d *schema.ResourceDa d.Set(names.AttrTransitGatewayID, transitGatewayConnect.TransitGatewayId) d.Set("transport_attachment_id", transitGatewayConnect.TransportTransitGatewayAttachmentId) - setTagsOutV2(ctx, transitGatewayConnect.Tags) + setTagsOut(ctx, transitGatewayConnect.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_connect_data_source.go b/internal/service/ec2/transitgateway_connect_data_source.go index b09b2be0e0f..e794862d6ff 100644 --- a/internal/service/ec2/transitgateway_connect_data_source.go +++ b/internal/service/ec2/transitgateway_connect_data_source.go @@ -63,7 +63,7 @@ func dataSourceTransitGatewayConnectRead(ctx context.Context, d *schema.Resource input.TransitGatewayAttachmentIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -79,7 +79,7 @@ func dataSourceTransitGatewayConnectRead(ctx context.Context, d *schema.Resource d.Set(names.AttrTransitGatewayID, transitGatewayConnect.TransitGatewayId) d.Set("transport_attachment_id", transitGatewayConnect.TransportTransitGatewayAttachmentId) - setTagsOutV2(ctx, transitGatewayConnect.Tags) + setTagsOut(ctx, transitGatewayConnect.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_connect_peer.go b/internal/service/ec2/transitgateway_connect_peer.go index b58bdb339f0..5cf4900cfd8 100644 --- a/internal/service/ec2/transitgateway_connect_peer.go +++ b/internal/service/ec2/transitgateway_connect_peer.go @@ -124,7 +124,7 @@ func resourceTransitGatewayConnectPeerCreate(ctx context.Context, d *schema.Reso input := &ec2.CreateTransitGatewayConnectPeerInput{ InsideCidrBlocks: flex.ExpandStringValueSet(d.Get("inside_cidr_blocks").(*schema.Set)), PeerAddress: aws.String(d.Get("peer_address").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayConnectPeer), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayConnectPeer), TransitGatewayAttachmentId: aws.String(d.Get(names.AttrTransitGatewayAttachmentID).(string)), } @@ -196,7 +196,7 @@ func resourceTransitGatewayConnectPeerRead(ctx context.Context, d *schema.Resour d.Set("transit_gateway_address", transitGatewayConnectPeer.ConnectPeerConfiguration.TransitGatewayAddress) d.Set(names.AttrTransitGatewayAttachmentID, transitGatewayConnectPeer.TransitGatewayAttachmentId) - setTagsOutV2(ctx, transitGatewayConnectPeer.Tags) + setTagsOut(ctx, transitGatewayConnectPeer.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_connect_peer_data_source.go b/internal/service/ec2/transitgateway_connect_peer_data_source.go index ba77f79568a..30dd2017014 100644 --- a/internal/service/ec2/transitgateway_connect_peer_data_source.go +++ b/internal/service/ec2/transitgateway_connect_peer_data_source.go @@ -90,7 +90,7 @@ func dataSourceTransitGatewayConnectPeerRead(ctx context.Context, d *schema.Reso input.TransitGatewayConnectPeerIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -122,7 +122,7 @@ func dataSourceTransitGatewayConnectPeerRead(ctx context.Context, d *schema.Reso d.Set(names.AttrTransitGatewayAttachmentID, transitGatewayConnectPeer.TransitGatewayAttachmentId) d.Set("transit_gateway_connect_peer_id", transitGatewayConnectPeer.TransitGatewayConnectPeerId) - setTagsOutV2(ctx, transitGatewayConnectPeer.Tags) + setTagsOut(ctx, transitGatewayConnectPeer.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_data_source.go b/internal/service/ec2/transitgateway_data_source.go index 7f14310688f..dd38353d546 100644 --- a/internal/service/ec2/transitgateway_data_source.go +++ b/internal/service/ec2/transitgateway_data_source.go @@ -100,7 +100,7 @@ func dataSourceTransitGatewayRead(ctx context.Context, d *schema.ResourceData, m input := &ec2.DescribeTransitGatewaysInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -134,7 +134,7 @@ func dataSourceTransitGatewayRead(ctx context.Context, d *schema.ResourceData, m d.Set("transit_gateway_cidr_blocks", transitGateway.Options.TransitGatewayCidrBlocks) d.Set("vpn_ecmp_support", transitGateway.Options.VpnEcmpSupport) - setTagsOutV2(ctx, transitGateway.Tags) + setTagsOut(ctx, transitGateway.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source.go b/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source.go index f43f1cbf053..32bc59163d4 100644 --- a/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source.go +++ b/internal/service/ec2/transitgateway_dx_gateway_attachment_data_source.go @@ -50,30 +50,30 @@ func dataSourceTransitGatewayDxGatewayAttachmentRead(ctx context.Context, d *sch conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeTransitGatewayAttachmentsInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "resource-type": string(awstypes.TransitGatewayAttachmentResourceTypeDirectConnectGateway), }), } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) if v, ok := d.GetOk(names.AttrTags); ok { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, v.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, v.(map[string]interface{}))), )...) } // to preserve original functionality if v, ok := d.GetOk("dx_gateway_id"); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2(map[string]string{ + input.Filters = append(input.Filters, newAttributeFilterList(map[string]string{ "resource-id": v.(string), })...) } if v, ok := d.GetOk(names.AttrTransitGatewayID); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2(map[string]string{ + input.Filters = append(input.Filters, newAttributeFilterList(map[string]string{ "transit-gateway-id": v.(string), })...) } @@ -88,7 +88,7 @@ func dataSourceTransitGatewayDxGatewayAttachmentRead(ctx context.Context, d *sch d.Set("dx_gateway_id", transitGatewayAttachment.ResourceId) d.Set(names.AttrTransitGatewayID, transitGatewayAttachment.TransitGatewayId) - setTagsOutV2(ctx, transitGatewayAttachment.Tags) + setTagsOut(ctx, transitGatewayAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_multicast_domain.go b/internal/service/ec2/transitgateway_multicast_domain.go index fc7696ab36b..33fe186cdee 100644 --- a/internal/service/ec2/transitgateway_multicast_domain.go +++ b/internal/service/ec2/transitgateway_multicast_domain.go @@ -96,7 +96,7 @@ func resourceTransitGatewayMulticastDomainCreate(ctx context.Context, d *schema. Igmpv2Support: awstypes.Igmpv2SupportValue(d.Get("igmpv2_support").(string)), StaticSourcesSupport: awstypes.StaticSourcesSupportValue(d.Get("static_sources_support").(string)), }, - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayMulticastDomain), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayMulticastDomain), TransitGatewayId: aws.String(d.Get(names.AttrTransitGatewayID).(string)), } @@ -140,7 +140,7 @@ func resourceTransitGatewayMulticastDomainRead(ctx context.Context, d *schema.Re d.Set("static_sources_support", multicastDomain.Options.StaticSourcesSupport) d.Set(names.AttrTransitGatewayID, multicastDomain.TransitGatewayId) - setTagsOutV2(ctx, multicastDomain.Tags) + setTagsOut(ctx, multicastDomain.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_multicast_domain_data_source.go b/internal/service/ec2/transitgateway_multicast_domain_data_source.go index 8db0c5c9e99..ce8079e375f 100644 --- a/internal/service/ec2/transitgateway_multicast_domain_data_source.go +++ b/internal/service/ec2/transitgateway_multicast_domain_data_source.go @@ -132,7 +132,7 @@ func dataSourceTransitGatewayMulticastDomainRead(ctx context.Context, d *schema. input.TransitGatewayMulticastDomainIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -156,7 +156,7 @@ func dataSourceTransitGatewayMulticastDomainRead(ctx context.Context, d *schema. d.Set(names.AttrTransitGatewayID, transitGatewayMulticastDomain.TransitGatewayId) d.Set("transit_gateway_multicast_domain_id", transitGatewayMulticastDomain.TransitGatewayMulticastDomainId) - setTagsOutV2(ctx, transitGatewayMulticastDomain.Tags) + setTagsOut(ctx, transitGatewayMulticastDomain.Tags) associations, err := findTransitGatewayMulticastDomainAssociations(ctx, conn, &ec2.GetTransitGatewayMulticastDomainAssociationsInput{ TransitGatewayMulticastDomainId: aws.String(d.Id()), @@ -171,7 +171,7 @@ func dataSourceTransitGatewayMulticastDomainRead(ctx context.Context, d *schema. } members, err := findTransitGatewayMulticastGroups(ctx, conn, &ec2.SearchTransitGatewayMulticastGroupsInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "is-group-member": "true", "is-group-source": "false", }), @@ -187,7 +187,7 @@ func dataSourceTransitGatewayMulticastDomainRead(ctx context.Context, d *schema. } sources, err := findTransitGatewayMulticastGroups(ctx, conn, &ec2.SearchTransitGatewayMulticastGroupsInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "is-group-member": "false", "is-group-source": "true", }), diff --git a/internal/service/ec2/transitgateway_multicast_group_source.go b/internal/service/ec2/transitgateway_multicast_group_source.go index c82872b2f7e..2d99f2ca1e1 100644 --- a/internal/service/ec2/transitgateway_multicast_group_source.go +++ b/internal/service/ec2/transitgateway_multicast_group_source.go @@ -82,7 +82,7 @@ func resourceTransitGatewayMulticastGroupSourceRead(ctx context.Context, d *sche conn := meta.(*conns.AWSClient).EC2Client(ctx) - multicastDomainID, groupIPAddress, eniID, err := TransitGatewayMulticastGroupSourceParseResourceID(d.Id()) + multicastDomainID, groupIPAddress, eniID, err := transitGatewayMulticastGroupSourceParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -115,7 +115,7 @@ func resourceTransitGatewayMulticastGroupSourceDelete(ctx context.Context, d *sc conn := meta.(*conns.AWSClient).EC2Client(ctx) - multicastDomainID, groupIPAddress, eniID, err := TransitGatewayMulticastGroupSourceParseResourceID(d.Id()) + multicastDomainID, groupIPAddress, eniID, err := transitGatewayMulticastGroupSourceParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -171,7 +171,7 @@ func transitGatewayMulticastGroupSourceCreateResourceID(multicastDomainID, group return id } -func TransitGatewayMulticastGroupSourceParseResourceID(id string) (string, string, string, error) { +func transitGatewayMulticastGroupSourceParseResourceID(id string) (string, string, string, error) { parts := strings.Split(id, transitGatewayMulticastGroupSourceIDSeparator) if len(parts) == 3 && parts[0] != "" && parts[1] != "" && parts[2] != "" { diff --git a/internal/service/ec2/transitgateway_peering_attachment.go b/internal/service/ec2/transitgateway_peering_attachment.go index 760de81e61b..a64fa2e0241 100644 --- a/internal/service/ec2/transitgateway_peering_attachment.go +++ b/internal/service/ec2/transitgateway_peering_attachment.go @@ -99,7 +99,7 @@ func resourceTransitGatewayPeeringAttachmentCreate(ctx context.Context, d *schem PeerAccountId: aws.String(peerAccountID), PeerRegion: aws.String(d.Get("peer_region").(string)), PeerTransitGatewayId: aws.String(d.Get("peer_transit_gateway_id").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayAttachment), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayAttachment), TransitGatewayId: aws.String(d.Get(names.AttrTransitGatewayID).(string)), } @@ -148,7 +148,7 @@ func resourceTransitGatewayPeeringAttachmentRead(ctx context.Context, d *schema. return sdkdiag.AppendErrorf(diags, "setting options: %s", err) } - setTagsOutV2(ctx, transitGatewayPeeringAttachment.Tags) + setTagsOut(ctx, transitGatewayPeeringAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_peering_attachment_accepter.go b/internal/service/ec2/transitgateway_peering_attachment_accepter.go index 37b493d6455..2eef8570031 100644 --- a/internal/service/ec2/transitgateway_peering_attachment_accepter.go +++ b/internal/service/ec2/transitgateway_peering_attachment_accepter.go @@ -86,7 +86,7 @@ func resourceTransitGatewayPeeringAttachmentAccepterCreate(ctx context.Context, return sdkdiag.AppendErrorf(diags, "waiting for EC2 Transit Gateway Peering Attachment (%s) update: %s", d.Id(), err) } - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EC2 Transit Gateway Peering Attachment (%s) tags: %s", d.Id(), err) } @@ -122,7 +122,7 @@ func resourceTransitGatewayPeeringAttachmentAccepterRead(ctx context.Context, d d.Set(names.AttrTransitGatewayAttachmentID, transitGatewayPeeringAttachment.TransitGatewayAttachmentId) d.Set(names.AttrTransitGatewayID, transitGatewayPeeringAttachment.AccepterTgwInfo.TransitGatewayId) - setTagsOutV2(ctx, transitGatewayPeeringAttachment.Tags) + setTagsOut(ctx, transitGatewayPeeringAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_peering_attachment_data_source.go b/internal/service/ec2/transitgateway_peering_attachment_data_source.go index 3c37bdff20c..640f84d91bb 100644 --- a/internal/service/ec2/transitgateway_peering_attachment_data_source.go +++ b/internal/service/ec2/transitgateway_peering_attachment_data_source.go @@ -67,7 +67,7 @@ func dataSourceTransitGatewayPeeringAttachmentRead(ctx context.Context, d *schem input := &ec2.DescribeTransitGatewayPeeringAttachmentsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -76,8 +76,8 @@ func dataSourceTransitGatewayPeeringAttachmentRead(ctx context.Context, d *schem } if v, ok := d.GetOk(names.AttrTags); ok { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, v.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, v.(map[string]interface{}))), )...) } @@ -108,7 +108,7 @@ func dataSourceTransitGatewayPeeringAttachmentRead(ctx context.Context, d *schem d.Set(names.AttrState, transitGatewayPeeringAttachment.State) d.Set(names.AttrTransitGatewayID, local.TransitGatewayId) - setTagsOutV2(ctx, transitGatewayPeeringAttachment.Tags) + setTagsOut(ctx, transitGatewayPeeringAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_peering_attachments_data_source.go b/internal/service/ec2/transitgateway_peering_attachments_data_source.go index 4dc81275258..6570826aa31 100644 --- a/internal/service/ec2/transitgateway_peering_attachments_data_source.go +++ b/internal/service/ec2/transitgateway_peering_attachments_data_source.go @@ -44,7 +44,7 @@ func dataSourceTransitGatewayPeeringAttachmentsRead(ctx context.Context, d *sche input := &ec2.DescribeTransitGatewayPeeringAttachmentsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/transitgateway_policy_table.go b/internal/service/ec2/transitgateway_policy_table.go index 444de649e70..e994d22b8ed 100644 --- a/internal/service/ec2/transitgateway_policy_table.go +++ b/internal/service/ec2/transitgateway_policy_table.go @@ -67,7 +67,7 @@ func resourceTransitGatewayPolicyTableCreate(ctx context.Context, d *schema.Reso transitGatewayID := d.Get(names.AttrTransitGatewayID).(string) input := &ec2.CreateTransitGatewayPolicyTableInput{ - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayPolicyTable), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayPolicyTable), TransitGatewayId: aws.String(transitGatewayID), } @@ -114,7 +114,7 @@ func resourceTransitGatewayPolicyTableRead(ctx context.Context, d *schema.Resour d.Set(names.AttrState, transitGatewayPolicyTable.State) d.Set(names.AttrTransitGatewayID, transitGatewayPolicyTable.TransitGatewayId) - setTagsOutV2(ctx, transitGatewayPolicyTable.Tags) + setTagsOut(ctx, transitGatewayPolicyTable.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_route.go b/internal/service/ec2/transitgateway_route.go index 37f7123720f..66b22716958 100644 --- a/internal/service/ec2/transitgateway_route.go +++ b/internal/service/ec2/transitgateway_route.go @@ -70,7 +70,7 @@ func resourceTransitGatewayRouteCreate(ctx context.Context, d *schema.ResourceDa destination := d.Get("destination_cidr_block").(string) transitGatewayRouteTableID := d.Get("transit_gateway_route_table_id").(string) - id := TransitGatewayRouteCreateResourceID(transitGatewayRouteTableID, destination) + id := transitGatewayRouteCreateResourceID(transitGatewayRouteTableID, destination) input := &ec2.CreateTransitGatewayRouteInput{ Blackhole: aws.Bool(d.Get("blackhole").(bool)), DestinationCidrBlock: aws.String(destination), @@ -78,7 +78,6 @@ func resourceTransitGatewayRouteCreate(ctx context.Context, d *schema.ResourceDa TransitGatewayRouteTableId: aws.String(transitGatewayRouteTableID), } - log.Printf("[DEBUG] Creating EC2 Transit Gateway Route: %+v", input) _, err := conn.CreateTransitGatewayRoute(ctx, input) if err != nil { @@ -98,10 +97,9 @@ func resourceTransitGatewayRouteRead(ctx context.Context, d *schema.ResourceData var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - transitGatewayRouteTableID, destination, err := TransitGatewayRouteParseResourceID(d.Id()) - + transitGatewayRouteTableID, destination, err := transitGatewayRouteParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading EC2 Transit Gateway Route (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { @@ -137,10 +135,9 @@ func resourceTransitGatewayRouteDelete(ctx context.Context, d *schema.ResourceDa var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - transitGatewayRouteTableID, destination, err := TransitGatewayRouteParseResourceID(d.Id()) - + transitGatewayRouteTableID, destination, err := transitGatewayRouteParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting EC2 Transit Gateway Route (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } log.Printf("[DEBUG] Deleting EC2 Transit Gateway Route: %s", d.Id()) @@ -166,14 +163,14 @@ func resourceTransitGatewayRouteDelete(ctx context.Context, d *schema.ResourceDa const transitGatewayRouteIDSeparator = "_" -func TransitGatewayRouteCreateResourceID(transitGatewayRouteTableID, destination string) string { +func transitGatewayRouteCreateResourceID(transitGatewayRouteTableID, destination string) string { parts := []string{transitGatewayRouteTableID, destination} id := strings.Join(parts, transitGatewayRouteIDSeparator) return id } -func TransitGatewayRouteParseResourceID(id string) (string, string, error) { +func transitGatewayRouteParseResourceID(id string) (string, string, error) { parts := strings.Split(id, transitGatewayRouteIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/transitgateway_route_table.go b/internal/service/ec2/transitgateway_route_table.go index 5dbd4bd774a..703b4373e85 100644 --- a/internal/service/ec2/transitgateway_route_table.go +++ b/internal/service/ec2/transitgateway_route_table.go @@ -71,7 +71,7 @@ func resourceTransitGatewayRouteTableCreate(ctx context.Context, d *schema.Resou input := &ec2.CreateTransitGatewayRouteTableInput{ TransitGatewayId: aws.String(d.Get(names.AttrTransitGatewayID).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayRouteTable), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayRouteTable), } log.Printf("[DEBUG] Creating EC2 Transit Gateway Route Table: %+v", input) @@ -118,7 +118,7 @@ func resourceTransitGatewayRouteTableRead(ctx context.Context, d *schema.Resourc d.Set("default_propagation_route_table", transitGatewayRouteTable.DefaultPropagationRouteTable) d.Set(names.AttrTransitGatewayID, transitGatewayRouteTable.TransitGatewayId) - setTagsOutV2(ctx, transitGatewayRouteTable.Tags) + setTagsOut(ctx, transitGatewayRouteTable.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_route_table_associations_data_source.go b/internal/service/ec2/transitgateway_route_table_associations_data_source.go index 256c7231413..cc723cfb7e3 100644 --- a/internal/service/ec2/transitgateway_route_table_associations_data_source.go +++ b/internal/service/ec2/transitgateway_route_table_associations_data_source.go @@ -52,7 +52,7 @@ func dataSourceTransitGatewayRouteTableAssociationsRead(ctx context.Context, d * input.TransitGatewayRouteTableId = aws.String(v.(string)) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/transitgateway_route_table_data_source.go b/internal/service/ec2/transitgateway_route_table_data_source.go index a335746ac39..54a6b1b517a 100644 --- a/internal/service/ec2/transitgateway_route_table_data_source.go +++ b/internal/service/ec2/transitgateway_route_table_data_source.go @@ -65,7 +65,7 @@ func dataSourceTransitGatewayRouteTableRead(ctx context.Context, d *schema.Resou input := &ec2.DescribeTransitGatewayRouteTablesInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -97,7 +97,7 @@ func dataSourceTransitGatewayRouteTableRead(ctx context.Context, d *schema.Resou d.Set("default_propagation_route_table", transitGatewayRouteTable.DefaultPropagationRouteTable) d.Set(names.AttrTransitGatewayID, transitGatewayRouteTable.TransitGatewayId) - setTagsOutV2(ctx, transitGatewayRouteTable.Tags) + setTagsOut(ctx, transitGatewayRouteTable.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_route_table_propagations_data_source.go b/internal/service/ec2/transitgateway_route_table_propagations_data_source.go index f0b8340b342..b56127b05f4 100644 --- a/internal/service/ec2/transitgateway_route_table_propagations_data_source.go +++ b/internal/service/ec2/transitgateway_route_table_propagations_data_source.go @@ -52,7 +52,7 @@ func dataSourceTransitGatewayRouteTablePropagationsRead(ctx context.Context, d * input.TransitGatewayRouteTableId = aws.String(v.(string)) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/transitgateway_route_table_routes_data_source.go b/internal/service/ec2/transitgateway_route_table_routes_data_source.go index f49bf105f6d..71ab1a3ae2f 100644 --- a/internal/service/ec2/transitgateway_route_table_routes_data_source.go +++ b/internal/service/ec2/transitgateway_route_table_routes_data_source.go @@ -66,7 +66,7 @@ func dataSourceTransitGatewayRouteTableRoutesRead(ctx context.Context, d *schema tgwRouteTableID := d.Get("transit_gateway_route_table_id").(string) input := &ec2.SearchTransitGatewayRoutesInput{ - Filters: newCustomFilterListV2(d.Get(names.AttrFilter).(*schema.Set)), + Filters: newCustomFilterList(d.Get(names.AttrFilter).(*schema.Set)), TransitGatewayRouteTableId: aws.String(tgwRouteTableID), } diff --git a/internal/service/ec2/transitgateway_route_tables_data_source.go b/internal/service/ec2/transitgateway_route_tables_data_source.go index 8cbd35e94a0..c650b6c0d04 100644 --- a/internal/service/ec2/transitgateway_route_tables_data_source.go +++ b/internal/service/ec2/transitgateway_route_tables_data_source.go @@ -44,11 +44,11 @@ func dataSourceTransitGatewayRouteTablesRead(ctx context.Context, d *schema.Reso input := &ec2.DescribeTransitGatewayRouteTablesInput{} - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/transitgateway_route_test.go b/internal/service/ec2/transitgateway_route_test.go index cfbd4c7e5db..8d54cfb6876 100644 --- a/internal/service/ec2/transitgateway_route_test.go +++ b/internal/service/ec2/transitgateway_route_test.go @@ -194,19 +194,9 @@ func testAccCheckTransitGatewayRouteExists(ctx context.Context, n string, v *aws return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 Transit Gateway Route ID is set") - } - - transitGatewayRouteTableID, destination, err := tfec2.TransitGatewayRouteParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination) + output, err := tfec2.FindTransitGatewayStaticRoute(ctx, conn, rs.Primary.Attributes["transit_gateway_route_table_id"], rs.Primary.Attributes["destination_cidr_block"]) if err != nil { return err @@ -227,13 +217,7 @@ func testAccCheckTransitGatewayRouteDestroy(ctx context.Context) resource.TestCh continue } - transitGatewayRouteTableID, destination, err := tfec2.TransitGatewayRouteParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination) + _, err := tfec2.FindTransitGatewayStaticRoute(ctx, conn, rs.Primary.Attributes["transit_gateway_route_table_id"], rs.Primary.Attributes["destination_cidr_block"]) if tfresource.NotFound(err) { continue diff --git a/internal/service/ec2/transitgateway_vpc_attachment.go b/internal/service/ec2/transitgateway_vpc_attachment.go index 262e64764b3..bb280f5616d 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment.go +++ b/internal/service/ec2/transitgateway_vpc_attachment.go @@ -110,7 +110,7 @@ func resourceTransitGatewayVPCAttachmentCreate(ctx context.Context, d *schema.Re }, SubnetIds: flex.ExpandStringValueSet(d.Get(names.AttrSubnetIDs).(*schema.Set)), TransitGatewayId: aws.String(transitGatewayID), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTransitGatewayAttachment), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTransitGatewayAttachment), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -221,7 +221,7 @@ func resourceTransitGatewayVPCAttachmentRead(ctx context.Context, d *schema.Reso d.Set(names.AttrVPCID, transitGatewayVPCAttachment.VpcId) d.Set("vpc_owner_id", transitGatewayVPCAttachment.VpcOwnerId) - setTagsOutV2(ctx, transitGatewayVPCAttachment.Tags) + setTagsOut(ctx, transitGatewayVPCAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_vpc_attachment_accepter.go b/internal/service/ec2/transitgateway_vpc_attachment_accepter.go index bf60dbe3cbf..76aeeb45cf6 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment_accepter.go +++ b/internal/service/ec2/transitgateway_vpc_attachment_accepter.go @@ -110,7 +110,7 @@ func resourceTransitGatewayVPCAttachmentAccepterCreate(ctx context.Context, d *s return sdkdiag.AppendErrorf(diags, "accepting EC2 Transit Gateway VPC Attachment (%s): waiting for completion: %s", transitGatewayAttachmentID, err) } - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EC2 Transit Gateway VPC Attachment (%s) tags: %s", d.Id(), err) } @@ -192,7 +192,7 @@ func resourceTransitGatewayVPCAttachmentAccepterRead(ctx context.Context, d *sch d.Set(names.AttrVPCID, transitGatewayVPCAttachment.VpcId) d.Set("vpc_owner_id", transitGatewayVPCAttachment.VpcOwnerId) - setTagsOutV2(ctx, transitGatewayVPCAttachment.Tags) + setTagsOut(ctx, transitGatewayVPCAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_vpc_attachment_data_source.go b/internal/service/ec2/transitgateway_vpc_attachment_data_source.go index 903dfca07d2..75598f864f3 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment_data_source.go +++ b/internal/service/ec2/transitgateway_vpc_attachment_data_source.go @@ -76,7 +76,7 @@ func dataSourceTransitGatewayVPCAttachmentRead(ctx context.Context, d *schema.Re input := &ec2.DescribeTransitGatewayVpcAttachmentsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -104,7 +104,7 @@ func dataSourceTransitGatewayVPCAttachmentRead(ctx context.Context, d *schema.Re d.Set(names.AttrVPCID, transitGatewayVPCAttachment.VpcId) d.Set("vpc_owner_id", transitGatewayVPCAttachment.VpcOwnerId) - setTagsOutV2(ctx, transitGatewayVPCAttachment.Tags) + setTagsOut(ctx, transitGatewayVPCAttachment.Tags) return diags } diff --git a/internal/service/ec2/transitgateway_vpc_attachments_data_source.go b/internal/service/ec2/transitgateway_vpc_attachments_data_source.go index 4c7149e7cca..e73237fe579 100644 --- a/internal/service/ec2/transitgateway_vpc_attachments_data_source.go +++ b/internal/service/ec2/transitgateway_vpc_attachments_data_source.go @@ -43,7 +43,7 @@ func dataSourceTransitGatewayVPCAttachmentsRead(ctx context.Context, d *schema.R input := &ec2.DescribeTransitGatewayVpcAttachmentsInput{} - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/transitgateway_vpn_attachment_data_source.go b/internal/service/ec2/transitgateway_vpn_attachment_data_source.go index 3e310374a46..440a9e5f44f 100644 --- a/internal/service/ec2/transitgateway_vpn_attachment_data_source.go +++ b/internal/service/ec2/transitgateway_vpn_attachment_data_source.go @@ -50,29 +50,29 @@ func dataSourceTransitGatewayVPNAttachmentRead(ctx context.Context, d *schema.Re conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeTransitGatewayAttachmentsInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "resource-type": string(awstypes.TransitGatewayAttachmentResourceTypeVpn), }), } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) if v, ok := d.GetOk(names.AttrTags); ok { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, v.(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, v.(map[string]interface{}))), )...) } if v, ok := d.GetOk("vpn_connection_id"); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2(map[string]string{ + input.Filters = append(input.Filters, newAttributeFilterList(map[string]string{ "resource-id": v.(string), })...) } if v, ok := d.GetOk(names.AttrTransitGatewayID); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2(map[string]string{ + input.Filters = append(input.Filters, newAttributeFilterList(map[string]string{ "transit-gateway-id": v.(string), })...) } @@ -87,7 +87,7 @@ func dataSourceTransitGatewayVPNAttachmentRead(ctx context.Context, d *schema.Re d.Set(names.AttrTransitGatewayID, transitGatewayAttachment.TransitGatewayId) d.Set("vpn_connection_id", transitGatewayAttachment.ResourceId) - setTagsOutV2(ctx, transitGatewayAttachment.Tags) + setTagsOut(ctx, transitGatewayAttachment.Tags) return diags } diff --git a/internal/service/ec2/verifiedaccess_endpoint.go b/internal/service/ec2/verifiedaccess_endpoint.go index cecce44273e..2804fe77e2d 100644 --- a/internal/service/ec2/verifiedaccess_endpoint.go +++ b/internal/service/ec2/verifiedaccess_endpoint.go @@ -28,7 +28,7 @@ import ( // @SDKResource("aws_verifiedaccess_endpoint", name="Verified Access Endpoint") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVerifiedAccessEndpoint() *schema.Resource { +func resourceVerifiedAccessEndpoint() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVerifiedAccessEndpointCreate, ReadWithoutTimeout: resourceVerifiedAccessEndpointRead, @@ -197,7 +197,7 @@ func resourceVerifiedAccessEndpointCreate(ctx context.Context, d *schema.Resourc DomainCertificateArn: aws.String(d.Get("domain_certificate_arn").(string)), EndpointDomainPrefix: aws.String(d.Get("endpoint_domain_prefix").(string)), EndpointType: types.VerifiedAccessEndpointType(d.Get(names.AttrEndpointType).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVerifiedAccessEndpoint), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeVerifiedAccessEndpoint), VerifiedAccessGroupId: aws.String(d.Get("verified_access_group_id").(string)), } diff --git a/internal/service/ec2/verifiedaccess_group.go b/internal/service/ec2/verifiedaccess_group.go index 1d5ae77e7db..819b570eb82 100644 --- a/internal/service/ec2/verifiedaccess_group.go +++ b/internal/service/ec2/verifiedaccess_group.go @@ -25,7 +25,7 @@ import ( // @SDKResource("aws_verifiedaccess_group", name="Verified Access Group") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVerifiedAccessGroup() *schema.Resource { +func resourceVerifiedAccessGroup() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVerifiedAccessGroupCreate, ReadWithoutTimeout: resourceVerifiedAccessGroupRead, @@ -107,7 +107,7 @@ func resourceVerifiedAccessGroupCreate(ctx context.Context, d *schema.ResourceDa input := &ec2.CreateVerifiedAccessGroupInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVerifiedAccessGroup), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeVerifiedAccessGroup), VerifiedAccessInstanceId: aws.String(d.Get("verifiedaccess_instance_id").(string)), } @@ -166,7 +166,7 @@ func resourceVerifiedAccessGroupRead(ctx context.Context, d *schema.ResourceData d.Set("verifiedaccess_group_id", group.VerifiedAccessGroupId) d.Set("verifiedaccess_instance_id", group.VerifiedAccessInstanceId) - setTagsOutV2(ctx, group.Tags) + setTagsOut(ctx, group.Tags) output, err := findVerifiedAccessGroupPolicyByID(ctx, conn, d.Id()) diff --git a/internal/service/ec2/verifiedaccess_instance.go b/internal/service/ec2/verifiedaccess_instance.go index 17a71f02d3f..890e28ca898 100644 --- a/internal/service/ec2/verifiedaccess_instance.go +++ b/internal/service/ec2/verifiedaccess_instance.go @@ -25,7 +25,7 @@ import ( // @SDKResource("aws_verifiedaccess_instance", name="Verified Access Instance") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVerifiedAccessInstance() *schema.Resource { +func resourceVerifiedAccessInstance() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVerifiedAccessInstanceCreate, ReadWithoutTimeout: resourceVerifiedAccessInstanceRead, @@ -96,7 +96,7 @@ func resourceVerifiedAccessInstanceCreate(ctx context.Context, d *schema.Resourc input := &ec2.CreateVerifiedAccessInstanceInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVerifiedAccessInstance), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeVerifiedAccessInstance), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -147,7 +147,7 @@ func resourceVerifiedAccessInstanceRead(ctx context.Context, d *schema.ResourceD d.Set("verified_access_trust_providers", nil) } - setTagsOutV2(ctx, output.Tags) + setTagsOut(ctx, output.Tags) return diags } diff --git a/internal/service/ec2/verifiedaccess_instance_logging_configuration.go b/internal/service/ec2/verifiedaccess_instance_logging_configuration.go index 2fe051e8961..ea8774c4a8e 100644 --- a/internal/service/ec2/verifiedaccess_instance_logging_configuration.go +++ b/internal/service/ec2/verifiedaccess_instance_logging_configuration.go @@ -22,11 +22,11 @@ import ( ) const ( - DefaultLogVersionValue = "ocsf-1.0.0-rc.2" + defaultVerifiedAccessLogVersion = "ocsf-1.0.0-rc.2" ) // @SDKResource("aws_verifiedaccess_instance_logging_configuration", name="Verified Access Instance Logging Configuration") -func ResourceVerifiedAccessInstanceLoggingConfiguration() *schema.Resource { +func resourceVerifiedAccessInstanceLoggingConfiguration() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVerifiedAccessInstanceLoggingConfigurationCreate, ReadWithoutTimeout: resourceVerifiedAccessInstanceLoggingConfigurationRead, @@ -237,7 +237,7 @@ func resourceVerifiedAccessInstanceLoggingConfigurationDelete(ctx context.Contex // reset log_version because ocsf-0.1 is not compatible with enabling include_trust_context // without reset, if practitioners previously applied and destroyed with ocsf-0.1, // ocsf-0.1 will be the new "default" value, leading to errors with include_trust_context - LogVersion: aws.String(DefaultLogVersionValue), + LogVersion: aws.String(defaultVerifiedAccessLogVersion), } uuid, err := uuid.GenerateUUID() diff --git a/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment.go b/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment.go index 121c6936d4f..1effff34bd9 100644 --- a/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment.go +++ b/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment.go @@ -21,7 +21,7 @@ import ( ) // @SDKResource("aws_verifiedaccess_instance_trust_provider_attachment", name="Verified Access Instance Trust Provider Attachment") -func ResourceVerifiedAccessInstanceTrustProviderAttachment() *schema.Resource { +func resourceVerifiedAccessInstanceTrustProviderAttachment() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVerifiedAccessInstanceTrustProviderAttachmentCreate, ReadWithoutTimeout: resourceVerifiedAccessInstanceTrustProviderAttachmentRead, @@ -52,16 +52,16 @@ func resourceVerifiedAccessInstanceTrustProviderAttachmentCreate(ctx context.Con vaiID := d.Get("verifiedaccess_instance_id").(string) vatpID := d.Get("verifiedaccess_trust_provider_id").(string) - resourceID := VerifiedAccessInstanceTrustProviderAttachmentCreateResourceID(vaiID, vatpID) + resourceID := verifiedAccessInstanceTrustProviderAttachmentCreateResourceID(vaiID, vatpID) input := &ec2.AttachVerifiedAccessTrustProviderInput{ ClientToken: aws.String(id.UniqueId()), VerifiedAccessInstanceId: aws.String(vaiID), VerifiedAccessTrustProviderId: aws.String(vatpID), } - output, err := conn.AttachVerifiedAccessTrustProvider(ctx, input) + _, err := conn.AttachVerifiedAccessTrustProvider(ctx, input) - if err != nil || output == nil { + if err != nil { return sdkdiag.AppendErrorf(diags, "creating Verified Access Instance Trust Provider Attachment (%s): %s", resourceID, err) } @@ -74,7 +74,7 @@ func resourceVerifiedAccessInstanceTrustProviderAttachmentRead(ctx context.Conte var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - vaiID, vatpID, err := VerifiedAccessInstanceTrustProviderAttachmentParseResourceID(d.Id()) + vaiID, vatpID, err := verifiedAccessInstanceTrustProviderAttachmentParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -101,7 +101,7 @@ func resourceVerifiedAccessInstanceTrustProviderAttachmentDelete(ctx context.Con var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - vaiID, vatpID, err := VerifiedAccessInstanceTrustProviderAttachmentParseResourceID(d.Id()) + vaiID, vatpID, err := verifiedAccessInstanceTrustProviderAttachmentParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -127,14 +127,14 @@ func resourceVerifiedAccessInstanceTrustProviderAttachmentDelete(ctx context.Con const verifiedAccessInstanceTrustProviderAttachmentResourceIDSeparator = "/" -func VerifiedAccessInstanceTrustProviderAttachmentCreateResourceID(vaiID, vatpID string) string { +func verifiedAccessInstanceTrustProviderAttachmentCreateResourceID(vaiID, vatpID string) string { parts := []string{vaiID, vatpID} id := strings.Join(parts, verifiedAccessInstanceTrustProviderAttachmentResourceIDSeparator) return id } -func VerifiedAccessInstanceTrustProviderAttachmentParseResourceID(id string) (string, string, error) { +func verifiedAccessInstanceTrustProviderAttachmentParseResourceID(id string) (string, string, error) { parts := strings.Split(id, verifiedAccessInstanceTrustProviderAttachmentResourceIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment_test.go b/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment_test.go index 5195faf10c7..e297ab1f789 100644 --- a/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment_test.go +++ b/internal/service/ec2/verifiedaccess_instance_trust_provider_attachment_test.go @@ -86,12 +86,7 @@ func testAccCheckVerifiedAccessInstanceTrustProviderAttachmentExists(ctx context conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - vaiID, vatpID, err := tfec2.VerifiedAccessInstanceTrustProviderAttachmentParseResourceID(rs.Primary.ID) - if err != nil { - return err - } - - err = tfec2.FindVerifiedAccessInstanceTrustProviderAttachmentExists(ctx, conn, vaiID, vatpID) + err := tfec2.FindVerifiedAccessInstanceTrustProviderAttachmentExists(ctx, conn, rs.Primary.Attributes["verifiedaccess_instance_id"], rs.Primary.Attributes["verifiedaccess_trust_provider_id"]) return err } @@ -106,12 +101,7 @@ func testAccCheckVerifiedAccessInstanceTrustProviderAttachmentDestroy(ctx contex continue } - vaiID, vatpID, err := tfec2.VerifiedAccessInstanceTrustProviderAttachmentParseResourceID(rs.Primary.ID) - if err != nil { - return err - } - - err = tfec2.FindVerifiedAccessInstanceTrustProviderAttachmentExists(ctx, conn, vaiID, vatpID) + err := tfec2.FindVerifiedAccessInstanceTrustProviderAttachmentExists(ctx, conn, rs.Primary.Attributes["verifiedaccess_instance_id"], rs.Primary.Attributes["verifiedaccess_trust_provider_id"]) if tfresource.NotFound(err) { continue diff --git a/internal/service/ec2/verifiedaccess_trust_provider.go b/internal/service/ec2/verifiedaccess_trust_provider.go index b71c8a925ab..4140a401d2f 100644 --- a/internal/service/ec2/verifiedaccess_trust_provider.go +++ b/internal/service/ec2/verifiedaccess_trust_provider.go @@ -28,7 +28,7 @@ import ( // @SDKResource("aws_verifiedaccess_trust_provider", name="Verified Access Trust Provider") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVerifiedAccessTrustProvider() *schema.Resource { +func resourceVerifiedAccessTrustProvider() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVerifiedAccessTrustProviderCreate, ReadWithoutTimeout: resourceVerifiedAccessTrustProviderRead, @@ -149,7 +149,7 @@ func resourceVerifiedAccessTrustProviderCreate(ctx context.Context, d *schema.Re input := &ec2.CreateVerifiedAccessTrustProviderInput{ ClientToken: aws.String(id.UniqueId()), PolicyReferenceName: aws.String(d.Get("policy_reference_name").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVerifiedAccessTrustProvider), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeVerifiedAccessTrustProvider), TrustProviderType: types.TrustProviderType(d.Get("trust_provider_type").(string)), } @@ -220,7 +220,7 @@ func resourceVerifiedAccessTrustProviderRead(ctx context.Context, d *schema.Reso d.Set("trust_provider_type", output.TrustProviderType) d.Set("user_trust_provider_type", output.UserTrustProviderType) - setTagsOutV2(ctx, output.Tags) + setTagsOut(ctx, output.Tags) return diags } diff --git a/internal/service/ec2/vpc_.go b/internal/service/ec2/vpc_.go index 1bb9229e1d3..406ddb52e18 100644 --- a/internal/service/ec2/vpc_.go +++ b/internal/service/ec2/vpc_.go @@ -15,7 +15,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws/arn" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" - 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/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" @@ -32,15 +32,15 @@ import ( ) const ( - VPCCIDRMaxIPv4 = 28 - VPCCIDRMinIPv4 = 16 - VPCCIDRMaxIPv6 = 56 + vpcCIDRMaxIPv4Netmask = 28 + vpcCIDRMinIPv4Netmask = 16 + vpcCIDRMaxIPv6Netmask = 56 ) // @SDKResource("aws_vpc", name="VPC") // @Tags(identifierAttribute="id") // @Testing(existsType="github.com/aws/aws-sdk-go-v2/service/ec2/types;awstypes;awstypes.Vpc") -func ResourceVPC() *schema.Resource { +func resourceVPC() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceVPCCreate, @@ -58,7 +58,7 @@ func ResourceVPC() *schema.Resource { ), SchemaVersion: 1, - MigrateState: VPCMigrateState, + MigrateState: vpcMigrateState, // Keep in sync with aws_default_vpc's schema. // See notes in default_vpc.go. @@ -77,7 +77,7 @@ func ResourceVPC() *schema.Resource { Optional: true, Computed: true, ForceNew: true, - ValidateFunc: validation.IsCIDRNetwork(VPCCIDRMinIPv4, VPCCIDRMaxIPv4), + ValidateFunc: validation.IsCIDRNetwork(vpcCIDRMinIPv4Netmask, vpcCIDRMaxIPv4Netmask), ConflictsWith: []string{"ipv4_netmask_length"}, }, "default_network_acl_id": { @@ -126,7 +126,7 @@ func ResourceVPC() *schema.Resource { Type: schema.TypeInt, Optional: true, ForceNew: true, - ValidateFunc: validation.IntBetween(VPCCIDRMinIPv4, VPCCIDRMaxIPv4), + ValidateFunc: validation.IntBetween(vpcCIDRMinIPv4Netmask, vpcCIDRMaxIPv4Netmask), ConflictsWith: []string{names.AttrCIDRBlock}, RequiredWith: []string{"ipv4_ipam_pool_id"}, }, @@ -142,7 +142,7 @@ func ResourceVPC() *schema.Resource { RequiredWith: []string{"ipv6_ipam_pool_id"}, ValidateFunc: validation.All( verify.ValidIPv6CIDRNetworkAddress, - validation.IsCIDRNetwork(VPCCIDRMaxIPv6, VPCCIDRMaxIPv6)), + validation.IsCIDRNetwork(vpcCIDRMaxIPv6Netmask, vpcCIDRMaxIPv6Netmask)), }, "ipv6_cidr_block_network_border_group": { Type: schema.TypeString, @@ -158,7 +158,7 @@ func ResourceVPC() *schema.Resource { "ipv6_netmask_length": { Type: schema.TypeInt, Optional: true, - ValidateFunc: validation.IntInSlice([]int{VPCCIDRMaxIPv6}), + ValidateFunc: validation.IntInSlice([]int{vpcCIDRMaxIPv6Netmask}), ConflictsWith: []string{"ipv6_cidr_block"}, RequiredWith: []string{"ipv6_ipam_pool_id"}, }, @@ -183,7 +183,7 @@ func resourceVPCCreate(ctx context.Context, d *schema.ResourceData, meta interfa input := &ec2.CreateVpcInput{ AmazonProvidedIpv6CidrBlock: aws.Bool(d.Get("assign_generated_ipv6_cidr_block").(bool)), InstanceTenancy: types.Tenancy(d.Get("instance_tenancy").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, types.ResourceTypeVpc), + TagSpecifications: getTagSpecificationsIn(ctx, types.ResourceTypeVpc), } if v, ok := d.GetOk(names.AttrCIDRBlock); ok { @@ -374,7 +374,7 @@ func resourceVPCRead(ctx context.Context, d *schema.ResourceData, meta interface } } - setTagsOutV2(ctx, vpc.Tags) + setTagsOut(ctx, vpc.Tags) return diags } @@ -451,11 +451,11 @@ func resourceVPCDelete(ctx context.Context, d *schema.ResourceData, meta interfa } log.Printf("[INFO] Deleting EC2 VPC: %s", d.Id()) - _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, vpcDeletedTimeout, func() (interface{}, error) { + _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { return conn.DeleteVpc(ctx, input) }, errCodeDependencyViolation) - if tfawserr_sdkv2.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { + if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCIDNotFound) { return diags } @@ -463,7 +463,7 @@ func resourceVPCDelete(ctx context.Context, d *schema.ResourceData, meta interfa return sdkdiag.AppendErrorf(diags, "deleting EC2 VPC (%s): %s", d.Id(), err) } - _, err = tfresource.RetryUntilNotFound(ctx, vpcDeletedTimeout, func() (interface{}, error) { + _, err = tfresource.RetryUntilNotFound(ctx, d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { return findVPCByID(ctx, conn, d.Id()) }) @@ -659,7 +659,7 @@ func modifyVPCIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.Client, vp return "", fmt.Errorf("disassociating IPv6 CIDR block (%s): %w", associationID, err) } - if _, err := waitVPCIPv6CIDRBlockAssociationDeleted(ctx, conn, associationID, vpcIPv6CIDRBlockAssociationDeletedTimeout); err != nil { + if err := waitVPCIPv6CIDRBlockAssociationDeleted(ctx, conn, associationID, vpcIPv6CIDRBlockAssociationDeletedTimeout); err != nil { return "", fmt.Errorf("disassociating IPv6 CIDR block (%s): waiting for completion: %w", associationID, err) } } diff --git a/internal/service/ec2/vpc_data_source.go b/internal/service/ec2/vpc_data_source.go index b76d673bcf7..6685ea2915a 100644 --- a/internal/service/ec2/vpc_data_source.go +++ b/internal/service/ec2/vpc_data_source.go @@ -23,7 +23,7 @@ import ( // @SDKDataSource("aws_vpc", name="VPC") // @Tags -func DataSourceVPC() *schema.Resource { +func dataSourceVPC() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCRead, @@ -133,7 +133,7 @@ func dataSourceVPCRead(ctx context.Context, d *schema.ResourceData, meta interfa isDefaultStr = "true" } input := &ec2.DescribeVpcsInput{ - Filters: newAttributeFilterListV2( + Filters: newAttributeFilterList( map[string]string{ "cidr": d.Get(names.AttrCIDRBlock).(string), "dhcp-options-id": d.Get("dhcp_options_id").(string), @@ -147,7 +147,7 @@ func dataSourceVPCRead(ctx context.Context, d *schema.ResourceData, meta interfa input.VpcIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2(d.Get(names.AttrFilter).(*schema.Set))...) + input.Filters = append(input.Filters, newCustomFilterList(d.Get(names.AttrFilter).(*schema.Set))...) input.Filters = append(input.Filters, tagFilters(ctx)...) if len(input.Filters) == 0 { @@ -224,7 +224,7 @@ func dataSourceVPCRead(ctx context.Context, d *schema.ResourceData, meta interfa d.Set("ipv6_cidr_block", nil) } - setTagsOutV2(ctx, vpc.Tags) + setTagsOut(ctx, vpc.Tags) return diags } diff --git a/internal/service/ec2/vpc_default_network_acl.go b/internal/service/ec2/vpc_default_network_acl.go index fc67ea08da7..14da5871ce4 100644 --- a/internal/service/ec2/vpc_default_network_acl.go +++ b/internal/service/ec2/vpc_default_network_acl.go @@ -103,10 +103,10 @@ func resourceDefaultNetworkACL() *schema.Resource { func resourceDefaultNetworkACLCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { // nosemgrep:ci.semgrep.tags.calling-UpdateTags-in-resource-create var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) naclID := d.Get("default_network_acl_id").(string) - nacl, err := FindNetworkACLByID(ctx, conn, naclID) + nacl, err := findNetworkACLByID(ctx, conn, naclID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Network ACL (%s): %s", naclID, err) @@ -129,8 +129,8 @@ func resourceDefaultNetworkACLCreate(ctx context.Context, d *schema.ResourceData // Configure tags. ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - newTags := KeyValueTags(ctx, getTagsIn(ctx)) - oldTags := KeyValueTags(ctx, nacl.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) + newTags := keyValueTags(ctx, getTagsIn(ctx)) + oldTags := keyValueTags(ctx, nacl.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) if !oldTags.Equal(newTags) { if err := updateTags(ctx, conn, d.Id(), oldTags, newTags); err != nil { @@ -143,7 +143,7 @@ func resourceDefaultNetworkACLCreate(ctx context.Context, d *schema.ResourceData func resourceDefaultNetworkACLUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) // Subnets *must* belong to a Network ACL. Subnets are not "removed" from // Network ACLs, instead their association is replaced. In a normal diff --git a/internal/service/ec2/vpc_default_network_acl_test.go b/internal/service/ec2/vpc_default_network_acl_test.go index 73ee00613eb..efc48ce4f5d 100644 --- a/internal/service/ec2/vpc_default_network_acl_test.go +++ b/internal/service/ec2/vpc_default_network_acl_test.go @@ -301,7 +301,7 @@ func testAccCheckDefaultNetworkACLExists(ctx context.Context, n string, v *types conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindNetworkACLByIDV2(ctx, conn, rs.Primary.ID) + output, err := tfec2.FindNetworkACLByID(ctx, conn, rs.Primary.ID) if err != nil { return err diff --git a/internal/service/ec2/vpc_default_route_table.go b/internal/service/ec2/vpc_default_route_table.go index 2faf6a0c624..902109b29b7 100644 --- a/internal/service/ec2/vpc_default_route_table.go +++ b/internal/service/ec2/vpc_default_route_table.go @@ -238,7 +238,7 @@ func resourceDefaultRouteTableCreate(ctx context.Context, d *schema.ResourceData } } - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EC2 Default Route Table (%s) tags: %s", d.Id(), err) } diff --git a/internal/service/ec2/vpc_default_route_table_test.go b/internal/service/ec2/vpc_default_route_table_test.go index 4c10ca7c3e7..e825547cf38 100644 --- a/internal/service/ec2/vpc_default_route_table_test.go +++ b/internal/service/ec2/vpc_default_route_table_test.go @@ -85,7 +85,7 @@ func TestAccVPCDefaultRouteTable_Disappears_vpc(t *testing.T) { Config: testAccVPCDefaultRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckRouteTableExists(ctx, resourceName, &routeTable), - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceVPC(), vpcResourceName), ), ExpectNonEmptyPlan: true, diff --git a/internal/service/ec2/vpc_default_security_group.go b/internal/service/ec2/vpc_default_security_group.go index bbb73c55ac5..a70bb1012db 100644 --- a/internal/service/ec2/vpc_default_security_group.go +++ b/internal/service/ec2/vpc_default_security_group.go @@ -6,8 +6,8 @@ package ec2 import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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" @@ -20,7 +20,7 @@ import ( // @SDKResource("aws_default_security_group", name="Security Group") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceDefaultSecurityGroup() *schema.Resource { +func resourceDefaultSecurityGroup() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceDefaultSecurityGroupCreate, @@ -33,7 +33,7 @@ func ResourceDefaultSecurityGroup() *schema.Resource { }, SchemaVersion: 1, // Keep in sync with aws_security_group's schema version. - MigrateState: SecurityGroupMigrateState, + MigrateState: securityGroupMigrateState, // Keep in sync with aws_security_group's schema with the following changes: // - description is Computed-only @@ -85,12 +85,12 @@ func ResourceDefaultSecurityGroup() *schema.Resource { func resourceDefaultSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { // nosemgrep:ci.semgrep.tags.calling-UpdateTags-in-resource-create var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSecurityGroupsInput{ Filters: newAttributeFilterList( map[string]string{ - "group-name": DefaultSecurityGroupName, + "group-name": defaultSecurityGroupName, }, ), } @@ -109,17 +109,17 @@ func resourceDefaultSecurityGroupCreate(ctx context.Context, d *schema.ResourceD )...) } - sg, err := FindSecurityGroup(ctx, conn, input) + sg, err := findSecurityGroup(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Default Security Group: %s", err) } - d.SetId(aws.StringValue(sg.GroupId)) + d.SetId(aws.ToString(sg.GroupId)) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - newTags := KeyValueTags(ctx, getTagsIn(ctx)) - oldTags := KeyValueTags(ctx, sg.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) + newTags := keyValueTags(ctx, getTagsIn(ctx)) + oldTags := keyValueTags(ctx, sg.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) if !newTags.Equal(oldTags) { if err := updateTags(ctx, conn, d.Id(), oldTags, newTags); err != nil { diff --git a/internal/service/ec2/vpc_default_security_group_test.go b/internal/service/ec2/vpc_default_security_group_test.go index 978d7c85e24..c915669a642 100644 --- a/internal/service/ec2/vpc_default_security_group_test.go +++ b/internal/service/ec2/vpc_default_security_group_test.go @@ -7,8 +7,8 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -18,7 +18,7 @@ import ( func TestAccVPCDefaultSecurityGroup_basic(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_default_security_group.test" vpcResourceName := "aws_vpc.test" @@ -73,7 +73,7 @@ func TestAccVPCDefaultSecurityGroup_basic(t *testing.T) { func TestAccVPCDefaultSecurityGroup_empty(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_default_security_group.test" @@ -103,9 +103,9 @@ func TestAccVPCDefaultSecurityGroup_empty(t *testing.T) { }) } -func testAccCheckDefaultSecurityGroupARN(resourceName string, group *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckDefaultSecurityGroupARN(resourceName string, group *awstypes.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { - return acctest.CheckResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", fmt.Sprintf("security-group/%s", aws.StringValue(group.GroupId)))(s) + return acctest.CheckResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", fmt.Sprintf("security-group/%s", aws.ToString(group.GroupId)))(s) } } diff --git a/internal/service/ec2/vpc_default_subnet.go b/internal/service/ec2/vpc_default_subnet.go index 589314a8883..17fc9d6af86 100644 --- a/internal/service/ec2/vpc_default_subnet.go +++ b/internal/service/ec2/vpc_default_subnet.go @@ -8,12 +8,13 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -24,7 +25,7 @@ import ( // @SDKResource("aws_default_subnet", name="Subnet") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceDefaultSubnet() *schema.Resource { +func resourceDefaultSubnet() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceDefaultSubnetCreate, @@ -44,7 +45,7 @@ func ResourceDefaultSubnet() *schema.Resource { }, SchemaVersion: 1, - MigrateState: SubnetMigrateState, + MigrateState: subnetMigrateState, // Keep in sync with aws_subnet's schema with the following changes: // - availability_zone is Required/ForceNew @@ -149,10 +150,10 @@ func ResourceDefaultSubnet() *schema.Resource { Computed: true, }, "private_dns_hostname_type_on_launch": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice(ec2.HostnameType_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.HostnameType](), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -166,7 +167,7 @@ func ResourceDefaultSubnet() *schema.Resource { func resourceDefaultSubnetCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { // nosemgrep:ci.semgrep.tags.calling-UpdateTags-in-resource-create var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) availabilityZone := d.Get(names.AttrAvailabilityZone).(string) input := &ec2.DescribeSubnetsInput{ @@ -179,11 +180,11 @@ func resourceDefaultSubnetCreate(ctx context.Context, d *schema.ResourceData, me } var computedIPv6CIDRBlock bool - subnet, err := FindSubnet(ctx, conn, input) + subnet, err := findSubnet(ctx, conn, input) if err == nil { log.Printf("[INFO] Found existing EC2 Default Subnet (%s)", availabilityZone) - d.SetId(aws.StringValue(subnet.SubnetId)) + d.SetId(aws.ToString(subnet.SubnetId)) d.Set("existing_default_subnet", true) } else if tfresource.NotFound(err) { input := &ec2.CreateDefaultSubnetInput{ @@ -196,8 +197,8 @@ func resourceDefaultSubnetCreate(ctx context.Context, d *schema.ResourceData, me input.Ipv6Native = aws.Bool(ipv6Native) } - log.Printf("[DEBUG] Creating EC2 Default Subnet: %s", input) - output, err := conn.CreateDefaultSubnetWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 Default Subnet: %#v", input) + output, err := conn.CreateDefaultSubnet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Default Subnet (%s): %s", availabilityZone, err) @@ -205,10 +206,10 @@ func resourceDefaultSubnetCreate(ctx context.Context, d *schema.ResourceData, me subnet = output.Subnet - d.SetId(aws.StringValue(subnet.SubnetId)) + d.SetId(aws.ToString(subnet.SubnetId)) d.Set("existing_default_subnet", false) - subnet, err = WaitSubnetAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) + subnet, err = waitSubnetAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Default Subnet (%s) create: %s", d.Id(), err) @@ -216,10 +217,10 @@ func resourceDefaultSubnetCreate(ctx context.Context, d *schema.ResourceData, me // Creating an IPv6-native default subnets associates an IPv6 CIDR block. for i, v := range subnet.Ipv6CidrBlockAssociationSet { - if aws.StringValue(v.Ipv6CidrBlockState.State) == ec2.SubnetCidrBlockStateCodeAssociating { //we can only ever have 1 IPv6 block associated at once - associationID := aws.StringValue(v.AssociationId) + if v.Ipv6CidrBlockState.State == awstypes.SubnetCidrBlockStateCodeAssociating { //we can only ever have 1 IPv6 block associated at once + associationID := aws.ToString(v.AssociationId) - subnetCidrBlockState, err := WaitSubnetIPv6CIDRBlockAssociationCreated(ctx, conn, associationID) + subnetCidrBlockState, err := waitSubnetIPv6CIDRBlockAssociationCreated(ctx, conn, associationID) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Default Subnet (%s) IPv6 CIDR block (%s) to become associated: %s", d.Id(), associationID, err) @@ -242,8 +243,8 @@ func resourceDefaultSubnetCreate(ctx context.Context, d *schema.ResourceData, me // Configure tags. ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - newTags := KeyValueTags(ctx, getTagsIn(ctx)) - oldTags := KeyValueTags(ctx, subnet.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) + newTags := keyValueTags(ctx, getTagsIn(ctx)) + oldTags := keyValueTags(ctx, subnet.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) if !oldTags.Equal(newTags) { if err := updateTags(ctx, conn, d.Id(), oldTags, newTags); err != nil { diff --git a/internal/service/ec2/vpc_default_subnet_test.go b/internal/service/ec2/vpc_default_subnet_test.go index 15cccd160e9..b33d4a86226 100644 --- a/internal/service/ec2/vpc_default_subnet_test.go +++ b/internal/service/ec2/vpc_default_subnet_test.go @@ -8,10 +8,11 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -23,7 +24,7 @@ import ( ) func testAccPreCheckDefaultSubnetExists(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSubnetsInput{ Filters: tfec2.NewAttributeFilterList( @@ -45,7 +46,7 @@ func testAccPreCheckDefaultSubnetExists(ctx context.Context, t *testing.T) { } func testAccPreCheckDefaultSubnetNotFound(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSubnetsInput{ Filters: tfec2.NewAttributeFilterList( @@ -62,7 +63,7 @@ func testAccPreCheckDefaultSubnetNotFound(ctx context.Context, t *testing.T) { } for _, v := range subnets { - subnetID := aws.StringValue(v.SubnetId) + subnetID := aws.ToString(v.SubnetId) t.Logf("Deleting existing default subnet: %s", subnetID) @@ -80,13 +81,13 @@ func testAccPreCheckDefaultSubnetNotFound(ctx context.Context, t *testing.T) { func testAccDefaultSubnet_Existing_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_default_subnet.test" resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultSubnetExists(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -126,7 +127,7 @@ func testAccDefaultSubnet_Existing_basic(t *testing.T) { func testAccDefaultSubnet_Existing_forceDestroy(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_default_subnet.test" resource.Test(t, resource.TestCase{ @@ -153,7 +154,7 @@ func testAccDefaultSubnet_Existing_forceDestroy(t *testing.T) { func testAccDefaultSubnet_Existing_ipv6(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_default_subnet.test" resource.Test(t, resource.TestCase{ @@ -199,7 +200,7 @@ func testAccDefaultSubnet_Existing_ipv6(t *testing.T) { func testAccDefaultSubnet_Existing_privateDNSNameOptionsOnLaunch(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_default_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -247,7 +248,7 @@ func testAccDefaultSubnet_Existing_privateDNSNameOptionsOnLaunch(t *testing.T) { func testAccDefaultSubnet_NotFound_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_default_subnet.test" resource.Test(t, resource.TestCase{ @@ -293,7 +294,7 @@ func testAccDefaultSubnet_NotFound_basic(t *testing.T) { func testAccDefaultSubnet_NotFound_ipv6Native(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_default_subnet.test" resource.Test(t, resource.TestCase{ @@ -342,7 +343,7 @@ func testAccDefaultSubnet_NotFound_ipv6Native(t *testing.T) { // Any missing default subnets are then created. func testAccCheckDefaultSubnetDestroyExists(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_subnet" { @@ -365,7 +366,7 @@ func testAccCheckDefaultSubnetDestroyExists(ctx context.Context) resource.TestCh // Any missing default subnets are then created. func testAccCheckDefaultSubnetDestroyNotFound(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_subnet" { @@ -390,9 +391,9 @@ func testAccCheckDefaultSubnetDestroyNotFound(ctx context.Context) resource.Test } func testAccCreateMissingDefaultSubnets(ctx context.Context) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := conn.DescribeAvailabilityZonesWithContext(ctx, &ec2.DescribeAvailabilityZonesInput{ + output, err := conn.DescribeAvailabilityZones(ctx, &ec2.DescribeAvailabilityZonesInput{ Filters: tfec2.NewAttributeFilterList( map[string]string{ "opt-in-status": "opt-in-not-required", @@ -406,9 +407,9 @@ func testAccCreateMissingDefaultSubnets(ctx context.Context) error { } for _, v := range output.AvailabilityZones { - availabilityZone := aws.StringValue(v.ZoneName) + availabilityZone := aws.ToString(v.ZoneName) - _, err := conn.CreateDefaultSubnetWithContext(ctx, &ec2.CreateDefaultSubnetInput{ + _, err := conn.CreateDefaultSubnet(ctx, &ec2.CreateDefaultSubnetInput{ AvailabilityZone: aws.String(availabilityZone), }) diff --git a/internal/service/ec2/vpc_default_vpc.go b/internal/service/ec2/vpc_default_vpc.go index 38942a85d74..f3fd9727b25 100644 --- a/internal/service/ec2/vpc_default_vpc.go +++ b/internal/service/ec2/vpc_default_vpc.go @@ -21,10 +21,10 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_default_vpc", name="VPC") +// @SDKResource("aws_default_vpc", name="Default VPC") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceDefaultVPC() *schema.Resource { +func resourceDefaultVPC() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceDefaultVPCCreate, @@ -39,7 +39,7 @@ func ResourceDefaultVPC() *schema.Resource { CustomizeDiff: verify.SetTagsDiff, SchemaVersion: 1, - MigrateState: VPCMigrateState, + MigrateState: vpcMigrateState, // Keep in sync with aws_vpc's schema with the following changes: // - cidr_block is Computed-only @@ -120,7 +120,7 @@ func ResourceDefaultVPC() *schema.Resource { RequiredWith: []string{"ipv6_ipam_pool_id"}, ValidateFunc: validation.All( verify.ValidIPv6CIDRNetworkAddress, - validation.IsCIDRNetwork(VPCCIDRMaxIPv6, VPCCIDRMaxIPv6)), + validation.IsCIDRNetwork(vpcCIDRMaxIPv6Netmask, vpcCIDRMaxIPv6Netmask)), }, "ipv6_cidr_block_network_border_group": { Type: schema.TypeString, @@ -136,7 +136,7 @@ func ResourceDefaultVPC() *schema.Resource { "ipv6_netmask_length": { Type: schema.TypeInt, Optional: true, - ValidateFunc: validation.IntInSlice([]int{VPCCIDRMaxIPv6}), + ValidateFunc: validation.IntInSlice([]int{vpcCIDRMaxIPv6Netmask}), ConflictsWith: []string{"ipv6_cidr_block"}, RequiredWith: []string{"ipv6_ipam_pool_id"}, }, @@ -159,7 +159,7 @@ func resourceDefaultVPCCreate(ctx context.Context, d *schema.ResourceData, meta conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeVpcsInput{ - Filters: newAttributeFilterListV2( + Filters: newAttributeFilterList( map[string]string{ "isDefault": "true", }, @@ -272,11 +272,11 @@ func resourceDefaultVPCCreate(ctx context.Context, d *schema.ResourceData, meta // Configure tags. ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - newTags := keyValueTagsV2(ctx, getTagsInV2(ctx)) - oldTags := keyValueTagsV2(ctx, vpc.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) + newTags := keyValueTags(ctx, getTagsIn(ctx)) + oldTags := keyValueTags(ctx, vpc.Tags).IgnoreSystem(names.EC2).IgnoreConfig(ignoreTagsConfig) if !oldTags.Equal(newTags) { - if err := updateTagsV2(ctx, conn, d.Id(), oldTags, newTags); err != nil { + if err := updateTags(ctx, conn, d.Id(), oldTags, newTags); err != nil { return sdkdiag.AppendErrorf(diags, "updating EC2 Default VPC (%s) tags: %s", d.Id(), err) } } diff --git a/internal/service/ec2/vpc_default_vpc_dhcp_options.go b/internal/service/ec2/vpc_default_vpc_dhcp_options.go index 8306fe5deb5..136a32128fb 100644 --- a/internal/service/ec2/vpc_default_vpc_dhcp_options.go +++ b/internal/service/ec2/vpc_default_vpc_dhcp_options.go @@ -6,8 +6,8 @@ package ec2 import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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" @@ -20,7 +20,7 @@ import ( // @SDKResource("aws_default_vpc_dhcp_options", name="DHCP Options") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceDefaultVPCDHCPOptions() *schema.Resource { +func resourceDefaultVPCDHCPOptions() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceDefaultVPCDHCPOptionsCreate, @@ -84,7 +84,7 @@ func ResourceDefaultVPCDHCPOptions() *schema.Resource { func resourceDefaultVPCDHCPOptionsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeDhcpOptionsInput{} @@ -101,13 +101,13 @@ func resourceDefaultVPCDHCPOptionsCreate(ctx context.Context, d *schema.Resource })...) } - dhcpOptions, err := FindDHCPOptions(ctx, conn, input) + dhcpOptions, err := findDHCPOptions(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Default DHCP Options Set: %s", err) } - d.SetId(aws.StringValue(dhcpOptions.DhcpOptionsId)) + d.SetId(aws.ToString(dhcpOptions.DhcpOptionsId)) return append(diags, resourceVPCDHCPOptionsUpdate(ctx, d, meta)...) } diff --git a/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go b/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go index e5978b35871..d794245bcd6 100644 --- a/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go +++ b/internal/service/ec2/vpc_default_vpc_dhcp_options_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/names" @@ -27,7 +27,7 @@ func TestAccVPCDefaultVPCDHCPOptions_serial(t *testing.T) { func testAccDefaultVPCDHCPOptions_basic(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_default_vpc_dhcp_options.test" resource.Test(t, resource.TestCase{ @@ -54,7 +54,7 @@ func testAccDefaultVPCDHCPOptions_basic(t *testing.T) { func testAccDefaultVPCDHCPOptions_owner(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_default_vpc_dhcp_options.test" resource.Test(t, resource.TestCase{ @@ -83,7 +83,7 @@ func testAccDefaultVPCDHCPOptions_owner(t *testing.T) { // Don't forget to unset TF_CLI_CONFIG_FILE. func testAccDefaultVPCDHCPOptions_v420Regression(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_default_vpc_dhcp_options.test" resource.Test(t, resource.TestCase{ diff --git a/internal/service/ec2/vpc_default_vpc_test.go b/internal/service/ec2/vpc_default_vpc_test.go index 16f5b1a6be8..f1f420d19e0 100644 --- a/internal/service/ec2/vpc_default_vpc_test.go +++ b/internal/service/ec2/vpc_default_vpc_test.go @@ -9,10 +9,9 @@ import ( "testing" "github.com/YakDriver/regexache" - ec2_sdkv2 "github.com/aws/aws-sdk-go-v2/service/ec2" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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" @@ -79,13 +78,13 @@ func testAccPreCheckDefaultVPCNotFound(ctx context.Context, t *testing.T) { func testAccDefaultVPC_Existing_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCExists(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -125,14 +124,14 @@ func testAccDefaultVPC_Existing_basic(t *testing.T) { func testAccDefaultVPC_Existing_assignGeneratedIPv6CIDRBlock(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCExists(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -173,13 +172,13 @@ func testAccDefaultVPC_Existing_assignGeneratedIPv6CIDRBlock(t *testing.T) { func testAccDefaultVPC_Existing_forceDestroy(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCExists(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -201,13 +200,13 @@ func testAccDefaultVPC_Existing_forceDestroy(t *testing.T) { func testAccDefaultVPC_NotFound_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCNotFound(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -247,14 +246,14 @@ func testAccDefaultVPC_NotFound_basic(t *testing.T) { func testAccDefaultVPC_NotFound_assignGeneratedIPv6CIDRBlock(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCNotFound(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -295,13 +294,13 @@ func testAccDefaultVPC_NotFound_assignGeneratedIPv6CIDRBlock(t *testing.T) { func testAccDefaultVPC_NotFound_forceDestroy(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCNotFound(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -323,14 +322,14 @@ func testAccDefaultVPC_NotFound_forceDestroy(t *testing.T) { func testAccDefaultVPC_NotFound_assignGeneratedIPv6CIDRBlockAdoption(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc resourceName := "aws_default_vpc.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.Test(t, resource.TestCase{ PreCheck: func() { acctest.PreCheck(ctx, t) - acctest.PreCheckRegionNot(t, endpoints.UsWest2RegionID, endpoints.UsGovWest1RegionID) + acctest.PreCheckRegionNot(t, names.USWest2RegionID, names.USGovWest1RegionID) testAccPreCheckDefaultVPCNotFound(ctx, t) }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), @@ -422,7 +421,7 @@ func testAccCheckDefaultVPCDestroyExists(ctx context.Context) resource.TestCheck continue } - _, err := tfec2.FindVPCByIDV2(ctx, conn, rs.Primary.ID) + _, err := tfec2.FindVPCByID(ctx, conn, rs.Primary.ID) if err != nil { return err @@ -445,7 +444,7 @@ func testAccCheckDefaultVPCDestroyNotFound(ctx context.Context) resource.TestChe continue } - _, err := tfec2.FindVPCByIDV2(ctx, conn, rs.Primary.ID) + _, err := tfec2.FindVPCByID(ctx, conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -458,7 +457,7 @@ func testAccCheckDefaultVPCDestroyNotFound(ctx context.Context) resource.TestChe return fmt.Errorf("EC2 Default VPC %s still exists", rs.Primary.ID) } - _, err := conn.CreateDefaultVpc(ctx, &ec2_sdkv2.CreateDefaultVpcInput{}) + _, err := conn.CreateDefaultVpc(ctx, &ec2.CreateDefaultVpcInput{}) if err != nil { return fmt.Errorf("error creating new default VPC: %w", err) @@ -469,15 +468,15 @@ func testAccCheckDefaultVPCDestroyNotFound(ctx context.Context) resource.TestChe } // testAccCheckDefaultVPCEmpty returns a TestCheckFunc that empties the specified default VPC. -func testAccCheckDefaultVPCEmpty(ctx context.Context, v *ec2.Vpc) resource.TestCheckFunc { +func testAccCheckDefaultVPCEmpty(ctx context.Context, v *awstypes.Vpc) resource.TestCheckFunc { return func(s *terraform.State) error { - return testAccEmptyDefaultVPC(ctx, aws.StringValue(v.VpcId)) + return testAccEmptyDefaultVPC(ctx, aws.ToString(v.VpcId)) } } // testAccEmptyDefaultVPC empties a default VPC so that it can be deleted. func testAccEmptyDefaultVPC(ctx context.Context, vpcID string) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) // Delete the default IGW. igw, err := tfec2.FindInternetGateway(ctx, conn, &ec2.DescribeInternetGatewaysInput{ @@ -492,7 +491,7 @@ func testAccEmptyDefaultVPC(ctx context.Context, vpcID string) error { if err == nil { r := tfec2.ResourceInternetGateway() d := r.Data(nil) - d.SetId(aws.StringValue(igw.InternetGatewayId)) + d.SetId(aws.ToString(igw.InternetGatewayId)) d.Set(names.AttrVPCID, vpcID) err := acctest.DeleteResource(ctx, r, d, acctest.Provider.Meta()) @@ -520,7 +519,7 @@ func testAccEmptyDefaultVPC(ctx context.Context, vpcID string) error { for _, v := range subnets { r := tfec2.ResourceSubnet() d := r.Data(nil) - d.SetId(aws.StringValue(v.SubnetId)) + d.SetId(aws.ToString(v.SubnetId)) err := acctest.DeleteResource(ctx, r, d, acctest.Provider.Meta()) diff --git a/internal/service/ec2/vpc_dhcp_options.go b/internal/service/ec2/vpc_dhcp_options.go index e074aa64390..3fb2d9c9684 100644 --- a/internal/service/ec2/vpc_dhcp_options.go +++ b/internal/service/ec2/vpc_dhcp_options.go @@ -8,10 +8,11 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -25,7 +26,7 @@ import ( // @SDKResource("aws_vpc_dhcp_options", name="DHCP Options") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVPCDHCPOptions() *schema.Resource { +func resourceVPCDHCPOptions() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCDHCPOptionsCreate, ReadWithoutTimeout: resourceVPCDHCPOptionsRead, @@ -107,7 +108,7 @@ var ( func resourceVPCDHCPOptionsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) dhcpConfigurations, err := optionsMap.resourceDataToDHCPConfigurations(d) @@ -117,26 +118,26 @@ func resourceVPCDHCPOptionsCreate(ctx context.Context, d *schema.ResourceData, m input := &ec2.CreateDhcpOptionsInput{ DhcpConfigurations: dhcpConfigurations, - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeDhcpOptions), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeDhcpOptions), } - output, err := conn.CreateDhcpOptionsWithContext(ctx, input) + output, err := conn.CreateDhcpOptions(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 DHCP Options: %s", err) } - d.SetId(aws.StringValue(output.DhcpOptions.DhcpOptionsId)) + d.SetId(aws.ToString(output.DhcpOptions.DhcpOptionsId)) return append(diags, resourceVPCDHCPOptionsRead(ctx, d, meta)...) } func resourceVPCDHCPOptionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindDHCPOptionsByID(ctx, conn, d.Id()) + return findDHCPOptionsByID(ctx, conn, d.Id()) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -149,12 +150,12 @@ func resourceVPCDHCPOptionsRead(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendErrorf(diags, "reading EC2 DHCP Options (%s): %s", d.Id(), err) } - opts := outputRaw.(*ec2.DhcpOptions) + opts := outputRaw.(*awstypes.DhcpOptions) - ownerID := aws.StringValue(opts.OwnerId) + ownerID := aws.ToString(opts.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("dhcp-options/%s", d.Id()), @@ -183,9 +184,9 @@ func resourceVPCDHCPOptionsUpdate(ctx context.Context, d *schema.ResourceData, m func resourceVPCDHCPOptionsDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcs, err := FindVPCs(ctx, conn, &ec2.DescribeVpcsInput{ + vpcs, err := findVPCs(ctx, conn, &ec2.DescribeVpcsInput{ Filters: newAttributeFilterList(map[string]string{ "dhcp-options-id": d.Id(), }), @@ -196,11 +197,11 @@ func resourceVPCDHCPOptionsDelete(ctx context.Context, d *schema.ResourceData, m } for _, v := range vpcs { - vpcID := aws.StringValue(v.VpcId) + vpcID := aws.ToString(v.VpcId) log.Printf("[INFO] Disassociating EC2 DHCP Options Set (%s) from VPC (%s)", d.Id(), vpcID) - _, err := conn.AssociateDhcpOptionsWithContext(ctx, &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String(DefaultDHCPOptionsID), + _, err := conn.AssociateDhcpOptions(ctx, &ec2.AssociateDhcpOptionsInput{ + DhcpOptionsId: aws.String(defaultDHCPOptionsID), VpcId: aws.String(vpcID), }) @@ -218,8 +219,8 @@ func resourceVPCDHCPOptionsDelete(ctx context.Context, d *schema.ResourceData, m } log.Printf("[INFO] Deleting EC2 DHCP Options Set: %s", d.Id()) - _, err = tfresource.RetryWhenAWSErrCodeEquals(ctx, dhcpOptionSetDeletedTimeout, func() (interface{}, error) { - return conn.DeleteDhcpOptionsWithContext(ctx, input) + _, err = tfresource.RetryWhenAWSErrCodeEquals(ctx, d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { + return conn.DeleteDhcpOptions(ctx, input) }, errCodeDependencyViolation) if tfawserr.ErrCodeEquals(err, errCodeInvalidDHCPOptionsIDNotFound) { @@ -253,13 +254,13 @@ func newDHCPOptionsMap(tfToApi map[string]string) *dhcpOptionsMap { } // dhcpConfigurationsToResourceData sets Terraform ResourceData from a list of AWS API DHCP configurations. -func (m *dhcpOptionsMap) dhcpConfigurationsToResourceData(dhcpConfigurations []*ec2.DhcpConfiguration, d *schema.ResourceData) error { +func (m *dhcpOptionsMap) dhcpConfigurationsToResourceData(dhcpConfigurations []awstypes.DhcpConfiguration, d *schema.ResourceData) error { for v := range m.tfToApi { d.Set(v, nil) } for _, dhcpConfiguration := range dhcpConfigurations { - apiName := aws.StringValue(dhcpConfiguration.Key) + apiName := aws.ToString(dhcpConfiguration.Key) if tfName, ok := m.apiToTf[apiName]; ok { switch v := d.Get(tfName).(type) { case string: @@ -269,7 +270,7 @@ func (m *dhcpOptionsMap) dhcpConfigurationsToResourceData(dhcpConfigurations []* for _, v := range dhcpConfiguration.Values { values = append(values, v.Value) } - d.Set(tfName, aws.StringValueSlice(values)) + d.Set(tfName, values) default: return fmt.Errorf("Attribute (%s) is of unsupported type: %T", tfName, v) } @@ -282,16 +283,16 @@ func (m *dhcpOptionsMap) dhcpConfigurationsToResourceData(dhcpConfigurations []* } // resourceDataToDHCPConfigurations returns a list of AWS API DHCP configurations from Terraform ResourceData. -func (m *dhcpOptionsMap) resourceDataToDHCPConfigurations(d *schema.ResourceData) ([]*ec2.NewDhcpConfiguration, error) { - var output []*ec2.NewDhcpConfiguration +func (m *dhcpOptionsMap) resourceDataToDHCPConfigurations(d *schema.ResourceData) ([]awstypes.NewDhcpConfiguration, error) { + var output []awstypes.NewDhcpConfiguration for tfName, apiName := range m.tfToApi { switch v := d.Get(tfName).(type) { case string: if v != "" { - output = append(output, &ec2.NewDhcpConfiguration{ + output = append(output, awstypes.NewDhcpConfiguration{ Key: aws.String(apiName), - Values: aws.StringSlice([]string{v}), + Values: []string{v}, }) } case []interface{}: @@ -303,9 +304,9 @@ func (m *dhcpOptionsMap) resourceDataToDHCPConfigurations(d *schema.ResourceData } } if len(values) > 0 { - output = append(output, &ec2.NewDhcpConfiguration{ + output = append(output, awstypes.NewDhcpConfiguration{ Key: aws.String(apiName), - Values: aws.StringSlice(values), + Values: values, }) } default: diff --git a/internal/service/ec2/vpc_dhcp_options_association.go b/internal/service/ec2/vpc_dhcp_options_association.go index f3b0f6177ba..5169c10132c 100644 --- a/internal/service/ec2/vpc_dhcp_options_association.go +++ b/internal/service/ec2/vpc_dhcp_options_association.go @@ -9,9 +9,9 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + "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/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -20,8 +20,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_dhcp_options_association") -func ResourceVPCDHCPOptionsAssociation() *schema.Resource { +// @SDKResource("aws_vpc_dhcp_options_association", name="VPC DHCP Options Association") +func resourceVPCDHCPOptionsAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCDHCPOptionsAssociationPut, ReadWithoutTimeout: resourceVPCDHCPOptionsAssociationRead, @@ -48,18 +48,18 @@ func ResourceVPCDHCPOptionsAssociation() *schema.Resource { func resourceVPCDHCPOptionsAssociationPut(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) dhcpOptionsID := d.Get("dhcp_options_id").(string) vpcID := d.Get(names.AttrVPCID).(string) - id := VPCDHCPOptionsAssociationCreateResourceID(dhcpOptionsID, vpcID) + id := vpcDHCPOptionsAssociationCreateResourceID(dhcpOptionsID, vpcID) input := &ec2.AssociateDhcpOptionsInput{ DhcpOptionsId: aws.String(dhcpOptionsID), VpcId: aws.String(vpcID), } - log.Printf("[DEBUG] Creating EC2 VPC DHCP Options Set Association: %s", input) - _, err := conn.AssociateDhcpOptionsWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 VPC DHCP Options Set Association: %#v", input) + _, err := conn.AssociateDhcpOptions(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 VPC DHCP Options Set Association (%s): %s", id, err) @@ -72,16 +72,16 @@ func resourceVPCDHCPOptionsAssociationPut(ctx context.Context, d *schema.Resourc func resourceVPCDHCPOptionsAssociationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - dhcpOptionsID, vpcID, err := VPCDHCPOptionsAssociationParseResourceID(d.Id()) + dhcpOptionsID, vpcID, err := vpcDHCPOptionsAssociationParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC DHCP Options Set Association (%s): %s", d.Id(), err) } _, err = tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return nil, FindVPCDHCPOptionsAssociation(ctx, conn, vpcID, dhcpOptionsID) + return nil, findVPCDHCPOptionsAssociation(ctx, conn, vpcID, dhcpOptionsID) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -102,15 +102,15 @@ func resourceVPCDHCPOptionsAssociationRead(ctx context.Context, d *schema.Resour func resourceVPCDHCPOptionsAssociationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - dhcpOptionsID, vpcID, err := VPCDHCPOptionsAssociationParseResourceID(d.Id()) + dhcpOptionsID, vpcID, err := vpcDHCPOptionsAssociationParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } - if dhcpOptionsID == DefaultDHCPOptionsID { + if dhcpOptionsID == defaultDHCPOptionsID { return diags } @@ -118,8 +118,8 @@ func resourceVPCDHCPOptionsAssociationDelete(ctx context.Context, d *schema.Reso // So, we do this by setting the VPC to the default DHCP Options Set. log.Printf("[DEBUG] Deleting EC2 VPC DHCP Options Set Association: %s", d.Id()) - _, err = conn.AssociateDhcpOptionsWithContext(ctx, &ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: aws.String(DefaultDHCPOptionsID), + _, err = conn.AssociateDhcpOptions(ctx, &ec2.AssociateDhcpOptionsInput{ + DhcpOptionsId: aws.String(defaultDHCPOptionsID), VpcId: aws.String(vpcID), }) @@ -135,18 +135,18 @@ func resourceVPCDHCPOptionsAssociationDelete(ctx context.Context, d *schema.Reso } func resourceVPCDHCPOptionsAssociationImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpc, err := FindVPCByID(ctx, conn, d.Id()) + vpc, err := findVPCByID(ctx, conn, d.Id()) if err != nil { return nil, fmt.Errorf("reading EC2 VPC (%s): %w", d.Id(), err) } - dhcpOptionsID := aws.StringValue(vpc.DhcpOptionsId) - vpcID := aws.StringValue(vpc.VpcId) + dhcpOptionsID := aws.ToString(vpc.DhcpOptionsId) + vpcID := aws.ToString(vpc.VpcId) - d.SetId(VPCDHCPOptionsAssociationCreateResourceID(dhcpOptionsID, vpcID)) + d.SetId(vpcDHCPOptionsAssociationCreateResourceID(dhcpOptionsID, vpcID)) d.Set("dhcp_options_id", dhcpOptionsID) d.Set(names.AttrVPCID, vpcID) @@ -155,21 +155,21 @@ func resourceVPCDHCPOptionsAssociationImport(ctx context.Context, d *schema.Reso const vpcDHCPOptionsAssociationResourceIDSeparator = "-" -func VPCDHCPOptionsAssociationCreateResourceID(dhcpOptionsID, vpcID string) string { +func vpcDHCPOptionsAssociationCreateResourceID(dhcpOptionsID, vpcID string) string { parts := []string{dhcpOptionsID, vpcID} id := strings.Join(parts, vpcDHCPOptionsAssociationResourceIDSeparator) return id } -func VPCDHCPOptionsAssociationParseResourceID(id string) (string, string, error) { +func vpcDHCPOptionsAssociationParseResourceID(id string) (string, string, error) { parts := strings.Split(id, vpcDHCPOptionsAssociationResourceIDSeparator) // The DHCP Options ID either contains '-' or is the special value "default". // The VPC ID contains '-'. switch n := len(parts); n { case 3: - if parts[0] == DefaultDHCPOptionsID && parts[1] != "" && parts[2] != "" { + if parts[0] == defaultDHCPOptionsID && parts[1] != "" && parts[2] != "" { return parts[0], strings.Join([]string{parts[1], parts[2]}, vpcDHCPOptionsAssociationResourceIDSeparator), nil } case 4: diff --git a/internal/service/ec2/vpc_dhcp_options_association_test.go b/internal/service/ec2/vpc_dhcp_options_association_test.go index 473d56f91bf..3d8c169e37e 100644 --- a/internal/service/ec2/vpc_dhcp_options_association_test.go +++ b/internal/service/ec2/vpc_dhcp_options_association_test.go @@ -154,7 +154,7 @@ func testAccVPCDHCPOptionsAssociationVPCImportIdFunc(resourceName string) resour func testAccCheckVPCDHCPOptionsAssociationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_dhcp_options_association" { @@ -201,7 +201,7 @@ func testAccCheckVPCDHCPOptionsAssociationExist(ctx context.Context, n string) r return err } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) return tfec2.FindVPCDHCPOptionsAssociation(ctx, conn, vpcID, dhcpOptionsID) } diff --git a/internal/service/ec2/vpc_dhcp_options_data_source.go b/internal/service/ec2/vpc_dhcp_options_data_source.go index dabdad472f8..969bfbcf9b7 100644 --- a/internal/service/ec2/vpc_dhcp_options_data_source.go +++ b/internal/service/ec2/vpc_dhcp_options_data_source.go @@ -8,9 +8,9 @@ import ( "fmt" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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" @@ -21,7 +21,7 @@ import ( ) // @SDKDataSource("aws_vpc_dhcp_options") -func DataSourceVPCDHCPOptions() *schema.Resource { +func dataSourceVPCDHCPOptions() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCDHCPOptionsRead, @@ -78,13 +78,13 @@ func DataSourceVPCDHCPOptions() *schema.Resource { func dataSourceVPCDHCPOptionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &ec2.DescribeDhcpOptionsInput{} if v, ok := d.GetOk("dhcp_options_id"); ok { - input.DhcpOptionsIds = []*string{aws.String(v.(string))} + input.DhcpOptionsIds = []string{v.(string)} } input.Filters = append(input.Filters, newCustomFilterList( @@ -95,18 +95,18 @@ func dataSourceVPCDHCPOptionsRead(ctx context.Context, d *schema.ResourceData, m input.Filters = nil } - opts, err := FindDHCPOptions(ctx, conn, input) + opts, err := findDHCPOptions(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 DHCP Options Set", err)) } - d.SetId(aws.StringValue(opts.DhcpOptionsId)) + d.SetId(aws.ToString(opts.DhcpOptionsId)) - ownerID := aws.StringValue(opts.OwnerId) + ownerID := aws.ToString(opts.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("dhcp-options/%s", d.Id()), @@ -121,7 +121,7 @@ func dataSourceVPCDHCPOptionsRead(ctx context.Context, d *schema.ResourceData, m return sdkdiag.AppendErrorf(diags, "reading EC2 DHCP Options: %s", err) } - if err := d.Set(names.AttrTags, KeyValueTags(ctx, opts.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, opts.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_dhcp_options_test.go b/internal/service/ec2/vpc_dhcp_options_test.go index 31b8ae8cb4f..e0e829d15a4 100644 --- a/internal/service/ec2/vpc_dhcp_options_test.go +++ b/internal/service/ec2/vpc_dhcp_options_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -22,7 +22,7 @@ import ( func TestAccVPCDHCPOptions_basic(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" resource.ParallelTest(t, resource.TestCase{ @@ -57,7 +57,7 @@ func TestAccVPCDHCPOptions_basic(t *testing.T) { func TestAccVPCDHCPOptions_full(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) domainName := acctest.RandomDomainName() @@ -99,7 +99,7 @@ func TestAccVPCDHCPOptions_full(t *testing.T) { func TestAccVPCDHCPOptions_tags(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" resource.ParallelTest(t, resource.TestCase{ @@ -144,7 +144,7 @@ func TestAccVPCDHCPOptions_tags(t *testing.T) { func TestAccVPCDHCPOptions_disappears(t *testing.T) { ctx := acctest.Context(t) - var d ec2.DhcpOptions + var d awstypes.DhcpOptions resourceName := "aws_vpc_dhcp_options.test" resource.ParallelTest(t, resource.TestCase{ @@ -167,7 +167,7 @@ func TestAccVPCDHCPOptions_disappears(t *testing.T) { func testAccCheckDHCPOptionsDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_dhcp_options" { @@ -191,7 +191,7 @@ func testAccCheckDHCPOptionsDestroy(ctx context.Context) resource.TestCheckFunc } } -func testAccCheckDHCPOptionsExists(ctx context.Context, n string, v *ec2.DhcpOptions) resource.TestCheckFunc { +func testAccCheckDHCPOptionsExists(ctx context.Context, n string, v *awstypes.DhcpOptions) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -202,7 +202,7 @@ func testAccCheckDHCPOptionsExists(ctx context.Context, n string, v *ec2.DhcpOpt return fmt.Errorf("No EC2 DHCP Options Set ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindDHCPOptionsByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_egress_only_internet_gateway.go b/internal/service/ec2/vpc_egress_only_internet_gateway.go index fe65c7f1054..071dfb0a087 100644 --- a/internal/service/ec2/vpc_egress_only_internet_gateway.go +++ b/internal/service/ec2/vpc_egress_only_internet_gateway.go @@ -7,9 +7,10 @@ import ( "context" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" @@ -24,7 +25,7 @@ import ( // @SDKResource("aws_egress_only_internet_gateway", name="Egress-Only Internet Gateway") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceEgressOnlyInternetGateway() *schema.Resource { +func resourceEgressOnlyInternetGateway() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceEgressOnlyInternetGatewayCreate, ReadWithoutTimeout: resourceEgressOnlyInternetGatewayRead, @@ -51,31 +52,31 @@ func ResourceEgressOnlyInternetGateway() *schema.Resource { func resourceEgressOnlyInternetGatewayCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateEgressOnlyInternetGatewayInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeEgressOnlyInternetGateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeEgressOnlyInternetGateway), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } - output, err := conn.CreateEgressOnlyInternetGatewayWithContext(ctx, input) + output, err := conn.CreateEgressOnlyInternetGateway(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Egress-only Internet Gateway: %s", err) } - d.SetId(aws.StringValue(output.EgressOnlyInternetGateway.EgressOnlyInternetGatewayId)) + d.SetId(aws.ToString(output.EgressOnlyInternetGateway.EgressOnlyInternetGatewayId)) return append(diags, resourceEgressOnlyInternetGatewayRead(ctx, d, meta)...) } func resourceEgressOnlyInternetGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindEgressOnlyInternetGatewayByID(ctx, conn, d.Id()) + return findEgressOnlyInternetGatewayByID(ctx, conn, d.Id()) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -88,9 +89,9 @@ func resourceEgressOnlyInternetGatewayRead(ctx context.Context, d *schema.Resour return sdkdiag.AppendErrorf(diags, "reading EC2 Egress-only Internet Gateway (%s): %s", d.Id(), err) } - ig := outputRaw.(*ec2.EgressOnlyInternetGateway) + ig := outputRaw.(*awstypes.EgressOnlyInternetGateway) - if len(ig.Attachments) == 1 && aws.StringValue(ig.Attachments[0].State) == ec2.AttachmentStatusAttached { + if len(ig.Attachments) == 1 && ig.Attachments[0].State == awstypes.AttachmentStatusAttached { d.Set(names.AttrVPCID, ig.Attachments[0].VpcId) } else { d.Set(names.AttrVPCID, nil) @@ -111,10 +112,10 @@ func resourceEgressOnlyInternetGatewayUpdate(ctx context.Context, d *schema.Reso func resourceEgressOnlyInternetGatewayDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting EC2 Egress-only Internet Gateway: %s", d.Id()) - _, err := conn.DeleteEgressOnlyInternetGatewayWithContext(ctx, &ec2.DeleteEgressOnlyInternetGatewayInput{ + _, err := conn.DeleteEgressOnlyInternetGateway(ctx, &ec2.DeleteEgressOnlyInternetGatewayInput{ EgressOnlyInternetGatewayId: aws.String(d.Id()), }) diff --git a/internal/service/ec2/vpc_egress_only_internet_gateway_test.go b/internal/service/ec2/vpc_egress_only_internet_gateway_test.go index 281f3d52c07..c92e924dfb3 100644 --- a/internal/service/ec2/vpc_egress_only_internet_gateway_test.go +++ b/internal/service/ec2/vpc_egress_only_internet_gateway_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -21,7 +21,7 @@ import ( func TestAccVPCEgressOnlyInternetGateway_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.EgressOnlyInternetGateway + var v awstypes.EgressOnlyInternetGateway resourceName := "aws_egress_only_internet_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -49,7 +49,7 @@ func TestAccVPCEgressOnlyInternetGateway_basic(t *testing.T) { func TestAccVPCEgressOnlyInternetGateway_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.EgressOnlyInternetGateway + var v awstypes.EgressOnlyInternetGateway resourceName := "aws_egress_only_internet_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -95,7 +95,7 @@ func TestAccVPCEgressOnlyInternetGateway_tags(t *testing.T) { func testAccCheckEgressOnlyInternetGatewayDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_egress_only_internet_gateway" { @@ -119,7 +119,7 @@ func testAccCheckEgressOnlyInternetGatewayDestroy(ctx context.Context) resource. } } -func testAccCheckEgressOnlyInternetGatewayExists(ctx context.Context, n string, v *ec2.EgressOnlyInternetGateway) resource.TestCheckFunc { +func testAccCheckEgressOnlyInternetGatewayExists(ctx context.Context, n string, v *awstypes.EgressOnlyInternetGateway) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -130,7 +130,7 @@ func testAccCheckEgressOnlyInternetGatewayExists(ctx context.Context, n string, return fmt.Errorf("No EC2 Egress-only Internet Gateway ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindEgressOnlyInternetGatewayByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_endpoint.go b/internal/service/ec2/vpc_endpoint.go index 83d82bac2e4..c33adc75ea8 100644 --- a/internal/service/ec2/vpc_endpoint.go +++ b/internal/service/ec2/vpc_endpoint.go @@ -227,7 +227,7 @@ func resourceVPCEndpointCreate(ctx context.Context, d *schema.ResourceData, meta ClientToken: aws.String(id.UniqueId()), PrivateDnsEnabled: aws.Bool(d.Get("private_dns_enabled").(bool)), ServiceName: aws.String(serviceName), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeVpcEndpoint), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVpcEndpoint), VpcEndpointType: awstypes.VpcEndpointType(d.Get("vpc_endpoint_type").(string)), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -298,8 +298,8 @@ func resourceVPCEndpointCreate(ctx context.Context, d *schema.ResourceData, meta } // For partitions not supporting tag-on-create, attempt tag after create. - if tags := getTagsInV2(ctx); input.TagSpecifications == nil && len(tags) > 0 { - err := createTagsV2(ctx, conn, d.Id(), tags) + if tags := getTagsIn(ctx); input.TagSpecifications == nil && len(tags) > 0 { + err := createTags(ctx, conn, d.Id(), tags) // If default tags only, continue. Otherwise, error. if v, ok := d.GetOk(names.AttrTags); (!ok || len(v.(map[string]interface{})) == 0) && errs.IsUnsupportedOperationInPartitionError(partition, err) { @@ -402,7 +402,7 @@ func resourceVPCEndpointRead(ctx context.Context, d *schema.ResourceData, meta i d.Set(names.AttrPolicy, policyToSet) - setTagsOutV2(ctx, vpce.Tags) + setTagsOut(ctx, vpce.Tags) return diags } @@ -496,7 +496,7 @@ func resourceVPCEndpointDelete(ctx context.Context, d *schema.ResourceData, meta }) if err == nil && output != nil { - err = unsuccessfulItemsErrorV2(output.Unsuccessful) + err = unsuccessfulItemsError(output.Unsuccessful) } if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointNotFound) { diff --git a/internal/service/ec2/vpc_endpoint_connection_accepter.go b/internal/service/ec2/vpc_endpoint_connection_accepter.go index 0305f488c48..2594ebb6a0b 100644 --- a/internal/service/ec2/vpc_endpoint_connection_accepter.go +++ b/internal/service/ec2/vpc_endpoint_connection_accepter.go @@ -20,8 +20,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_endpoint_connection_accepter") -func ResourceVPCEndpointConnectionAccepter() *schema.Resource { +// @SDKResource("aws_vpc_endpoint_connection_accepter", name="VPC Endpoint Connection Accepter") +func resourceVPCEndpointConnectionAccepter() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointConnectionAccepterCreate, ReadWithoutTimeout: resourceVPCEndpointConnectionAccepterRead, @@ -56,13 +56,12 @@ func resourceVPCEndpointConnectionAccepterCreate(ctx context.Context, d *schema. serviceID := d.Get("vpc_endpoint_service_id").(string) vpcEndpointID := d.Get(names.AttrVPCEndpointID).(string) - id := VPCEndpointConnectionAccepterCreateResourceID(serviceID, vpcEndpointID) + id := vpcEndpointConnectionAccepterCreateResourceID(serviceID, vpcEndpointID) input := &ec2.AcceptVpcEndpointConnectionsInput{ ServiceId: aws.String(serviceID), VpcEndpointIds: []string{vpcEndpointID}, } - log.Printf("[DEBUG] Accepting VPC Endpoint Connection: %v", input) _, err := conn.AcceptVpcEndpointConnections(ctx, input) if err != nil { @@ -71,10 +70,8 @@ func resourceVPCEndpointConnectionAccepterCreate(ctx context.Context, d *schema. d.SetId(id) - _, err = waitVPCEndpointConnectionAccepted(ctx, conn, serviceID, vpcEndpointID, d.Timeout(schema.TimeoutCreate)) - - if err != nil { - return sdkdiag.AppendErrorf(diags, "waiting for VPC Endpoint Connection (%s) to be accepted: %s", d.Id(), err) + if _, err := waitVPCEndpointConnectionAccepted(ctx, conn, serviceID, vpcEndpointID, d.Timeout(schema.TimeoutCreate)); err != nil { + return sdkdiag.AppendErrorf(diags, "waiting for VPC Endpoint Connection (%s) accept: %s", d.Id(), err) } return append(diags, resourceVPCEndpointConnectionAccepterRead(ctx, d, meta)...) @@ -84,7 +81,7 @@ func resourceVPCEndpointConnectionAccepterRead(ctx context.Context, d *schema.Re var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - serviceID, vpcEndpointID, err := VPCEndpointConnectionAccepterParseResourceID(d.Id()) + serviceID, vpcEndpointID, err := vpcEndpointConnectionAccepterParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -92,7 +89,7 @@ func resourceVPCEndpointConnectionAccepterRead(ctx context.Context, d *schema.Re vpcEndpointConnection, err := findVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx, conn, serviceID, vpcEndpointID) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] VPC Endpoint Connection %s not found, removing from state", d.Id()) + log.Printf("[WARN] VPC Endpoint Connection Accepter %s not found, removing from state", d.Id()) d.SetId("") return diags } @@ -112,7 +109,7 @@ func resourceVPCEndpointConnectionAccepterDelete(ctx context.Context, d *schema. var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - serviceID, vpcEndpointID, err := VPCEndpointConnectionAccepterParseResourceID(d.Id()) + serviceID, vpcEndpointID, err := vpcEndpointConnectionAccepterParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -136,14 +133,14 @@ func resourceVPCEndpointConnectionAccepterDelete(ctx context.Context, d *schema. const vpcEndpointConnectionAccepterResourceIDSeparator = "_" -func VPCEndpointConnectionAccepterCreateResourceID(serviceID, vpcEndpointID string) string { +func vpcEndpointConnectionAccepterCreateResourceID(serviceID, vpcEndpointID string) string { parts := []string{serviceID, vpcEndpointID} id := strings.Join(parts, vpcEndpointConnectionAccepterResourceIDSeparator) return id } -func VPCEndpointConnectionAccepterParseResourceID(id string) (string, string, error) { +func vpcEndpointConnectionAccepterParseResourceID(id string) (string, string, error) { parts := strings.Split(id, vpcEndpointConnectionAccepterResourceIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/vpc_endpoint_connection_accepter_test.go b/internal/service/ec2/vpc_endpoint_connection_accepter_test.go index 5020d973d92..fe14bb1a938 100644 --- a/internal/service/ec2/vpc_endpoint_connection_accepter_test.go +++ b/internal/service/ec2/vpc_endpoint_connection_accepter_test.go @@ -57,13 +57,7 @@ func testAccCheckVPCEndpointConnectionAccepterDestroy(ctx context.Context) resou continue } - serviceID, vpcEndpointID, err := tfec2.VPCEndpointConnectionAccepterParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx, conn, serviceID, vpcEndpointID) + _, err := tfec2.FindVPCEndpointConnectionByServiceIDAndVPCEndpointID(ctx, conn, rs.Primary.Attributes["vpc_endpoint_service_id"], rs.Primary.Attributes[names.AttrVPCEndpointID]) if tfresource.NotFound(err) { continue diff --git a/internal/service/ec2/vpc_endpoint_connection_notification.go b/internal/service/ec2/vpc_endpoint_connection_notification.go index 3f31a30f912..31ee1fe466a 100644 --- a/internal/service/ec2/vpc_endpoint_connection_notification.go +++ b/internal/service/ec2/vpc_endpoint_connection_notification.go @@ -22,7 +22,7 @@ import ( ) // @SDKResource("aws_vpc_endpoint_connection_notification", name="VPC Endpoint Connection Notification") -func ResourceVPCEndpointConnectionNotification() *schema.Resource { +func resourceVPCEndpointConnectionNotification() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointConnectionNotificationCreate, ReadWithoutTimeout: resourceVPCEndpointConnectionNotificationRead, diff --git a/internal/service/ec2/vpc_endpoint_data_source.go b/internal/service/ec2/vpc_endpoint_data_source.go index 1a98f07a663..ceaf51f11f6 100644 --- a/internal/service/ec2/vpc_endpoint_data_source.go +++ b/internal/service/ec2/vpc_endpoint_data_source.go @@ -22,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_vpc_endpoint") -func DataSourceVPCEndpoint() *schema.Resource { +// @SDKDataSource("aws_vpc_endpoint", name="Endpoint") +func dataSourceVPCEndpoint() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCEndpointRead, @@ -153,7 +153,7 @@ func dataSourceVPCEndpointRead(ctx context.Context, d *schema.ResourceData, meta ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &ec2.DescribeVpcEndpointsInput{ - Filters: newAttributeFilterListV2( + Filters: newAttributeFilterList( map[string]string{ "vpc-endpoint-state": d.Get(names.AttrState).(string), "vpc-id": d.Get(names.AttrVPCID).(string), @@ -166,10 +166,10 @@ func dataSourceVPCEndpointRead(ctx context.Context, d *schema.ResourceData, meta input.VpcEndpointIds = []string{v.(string)} } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) if len(input.Filters) == 0 { @@ -242,7 +242,7 @@ func dataSourceVPCEndpointRead(ctx context.Context, d *schema.ResourceData, meta d.Set(names.AttrPolicy, policy) - if err := d.Set(names.AttrTags, keyValueTagsV2(ctx, vpce.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, vpce.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_endpoint_policy.go b/internal/service/ec2/vpc_endpoint_policy.go index 096cd90923b..8ef7eb2c2ce 100644 --- a/internal/service/ec2/vpc_endpoint_policy.go +++ b/internal/service/ec2/vpc_endpoint_policy.go @@ -22,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_endpoint_policy") -func ResourceVPCEndpointPolicy() *schema.Resource { +// @SDKResource("aws_vpc_endpoint_policy", "VPC Endpoint Policy") +func resourceVPCEndpointPolicy() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointPolicyPut, UpdateWithoutTimeout: resourceVPCEndpointPolicyPut, diff --git a/internal/service/ec2/vpc_endpoint_private_dns.go b/internal/service/ec2/vpc_endpoint_private_dns.go index f72170fd75e..1732b7ff0ce 100644 --- a/internal/service/ec2/vpc_endpoint_private_dns.go +++ b/internal/service/ec2/vpc_endpoint_private_dns.go @@ -5,9 +5,8 @@ package ec2 import ( "context" - "errors" + "fmt" - "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" @@ -15,33 +14,29 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-provider-aws/internal/create" + "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" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" ) -// @FrameworkResource("aws_vpc_endpoint_private_dns", name="Endpoint Private DNS") -func newResourceEndpointPrivateDNS(_ context.Context) (resource.ResourceWithConfigure, error) { - return &resourceEndpointPrivateDNS{}, nil +// @FrameworkResource("aws_vpc_endpoint_private_dns", name="VPC Endpoint Private DNS") +func newVPCEndpointPrivateDNSResource(_ context.Context) (resource.ResourceWithConfigure, error) { + return &vpcEndpointPrivateDNSResource{}, nil } -const ( - ResNameEndpointPrivateDNS = "Endpoint Private DNS" -) - -type resourceEndpointPrivateDNS struct { +type vpcEndpointPrivateDNSResource struct { framework.ResourceWithConfigure framework.WithNoOpDelete } -func (r *resourceEndpointPrivateDNS) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = "aws_vpc_endpoint_private_dns" +func (*vpcEndpointPrivateDNSResource) Metadata(_ context.Context, request resource.MetadataRequest, response *resource.MetadataResponse) { + response.TypeName = "aws_vpc_endpoint_private_dns" } -func (r *resourceEndpointPrivateDNS) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ +func (r *vpcEndpointPrivateDNSResource) Schema(ctx context.Context, request resource.SchemaRequest, response *resource.SchemaResponse) { + response.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ "private_dns_enabled": schema.BoolAttribute{ Required: true, @@ -56,107 +51,90 @@ func (r *resourceEndpointPrivateDNS) Schema(ctx context.Context, req resource.Sc } } -func (r *resourceEndpointPrivateDNS) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - conn := r.Meta().EC2Client(ctx) - - var plan resourceEndpointPrivateDNSData - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { +func (r *vpcEndpointPrivateDNSResource) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) { + var data vpcEndpointPrivateDNSResourceModel + response.Diagnostics.Append(request.Plan.Get(ctx, &data)...) + if response.Diagnostics.HasError() { return } - in := &ec2.ModifyVpcEndpointInput{ - VpcEndpointId: aws.String(plan.VpcEndpointID.ValueString()), - PrivateDnsEnabled: aws.Bool(plan.PrivateDNSEnabled.ValueBool()), + conn := r.Meta().EC2Client(ctx) + + input := &ec2.ModifyVpcEndpointInput{ + PrivateDnsEnabled: fwflex.BoolFromFramework(ctx, data.PrivateDNSEnabled), + VpcEndpointId: fwflex.StringFromFramework(ctx, data.VPCEndpointID), } - out, err := conn.ModifyVpcEndpoint(ctx, in) + _, err := conn.ModifyVpcEndpoint(ctx, input) + if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointPrivateDNS, plan.VpcEndpointID.String(), err), - err.Error(), - ) - return - } - if out == nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointPrivateDNS, plan.VpcEndpointID.String(), nil), - errors.New("empty output").Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("creating VPC Endpoint Private DNS (%s)", data.VPCEndpointID.ValueString()), err.Error()) + return } - resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + response.Diagnostics.Append(response.State.Set(ctx, data)...) } -func (r *resourceEndpointPrivateDNS) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - conn := r.Meta().EC2Client(ctx) - - var state resourceEndpointPrivateDNSData - resp.Diagnostics.Append(req.State.Get(ctx, &state)...) - if resp.Diagnostics.HasError() { +func (r *vpcEndpointPrivateDNSResource) Read(ctx context.Context, request resource.ReadRequest, response *resource.ReadResponse) { + var data vpcEndpointPrivateDNSResourceModel + response.Diagnostics.Append(request.State.Get(ctx, &data)...) + if response.Diagnostics.HasError() { return } - out, err := findVPCEndpointByID(ctx, conn, state.VpcEndpointID.ValueString()) + conn := r.Meta().EC2Client(ctx) + + vpce, err := findVPCEndpointByID(ctx, conn, data.VPCEndpointID.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.EC2, create.ErrActionReading, ResNameEndpointPrivateDNS, state.VpcEndpointID.String(), err), - err.Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("reading VPC Endpoint (%s)", data.VPCEndpointID.ValueString()), err.Error()) + return } - state.PrivateDNSEnabled = flex.BoolToFramework(ctx, out.PrivateDnsEnabled) + data.PrivateDNSEnabled = fwflex.BoolToFramework(ctx, vpce.PrivateDnsEnabled) - resp.Diagnostics.Append(resp.State.Set(ctx, &state)...) + response.Diagnostics.Append(response.State.Set(ctx, &data)...) } -func (r *resourceEndpointPrivateDNS) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { +func (r *vpcEndpointPrivateDNSResource) Update(ctx context.Context, request resource.UpdateRequest, response *resource.UpdateResponse) { + var data vpcEndpointPrivateDNSResourceModel + response.Diagnostics.Append(request.Plan.Get(ctx, &data)...) + if response.Diagnostics.HasError() { + return + } + conn := r.Meta().EC2Client(ctx) - var plan, state resourceEndpointPrivateDNSData - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - resp.Diagnostics.Append(req.State.Get(ctx, &state)...) - if resp.Diagnostics.HasError() { - return + input := &ec2.ModifyVpcEndpointInput{ + PrivateDnsEnabled: fwflex.BoolFromFramework(ctx, data.PrivateDNSEnabled), + VpcEndpointId: fwflex.StringFromFramework(ctx, data.VPCEndpointID), } - if !plan.PrivateDNSEnabled.Equal(state.PrivateDNSEnabled) { - in := &ec2.ModifyVpcEndpointInput{ - VpcEndpointId: aws.String(plan.VpcEndpointID.ValueString()), - PrivateDnsEnabled: aws.Bool(plan.PrivateDNSEnabled.ValueBool()), - } - - out, err := conn.ModifyVpcEndpoint(ctx, in) - if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointPrivateDNS, plan.VpcEndpointID.String(), err), - err.Error(), - ) - return - } - if out == nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointPrivateDNS, plan.VpcEndpointID.String(), nil), - errors.New("empty output").Error(), - ) - return - } + _, err := conn.ModifyVpcEndpoint(ctx, input) + + if err != nil { + response.Diagnostics.AddError(fmt.Sprintf("Updating VPC Endpoint Private DNS (%s)", data.VPCEndpointID.ValueString()), err.Error()) + + return } - resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...) + response.Diagnostics.Append(response.State.Set(ctx, &data)...) } -func (r *resourceEndpointPrivateDNS) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resource.ImportStatePassthroughID(ctx, path.Root(names.AttrVPCEndpointID), req, resp) +func (r *vpcEndpointPrivateDNSResource) ImportState(ctx context.Context, request resource.ImportStateRequest, response *resource.ImportStateResponse) { + resource.ImportStatePassthroughID(ctx, path.Root(names.AttrVPCEndpointID), request, response) } -type resourceEndpointPrivateDNSData struct { - VpcEndpointID types.String `tfsdk:"vpc_endpoint_id"` +type vpcEndpointPrivateDNSResourceModel struct { PrivateDNSEnabled types.Bool `tfsdk:"private_dns_enabled"` + VPCEndpointID types.String `tfsdk:"vpc_endpoint_id"` } diff --git a/internal/service/ec2/vpc_endpoint_private_dns_test.go b/internal/service/ec2/vpc_endpoint_private_dns_test.go index 97db0f76a24..64d98dcab81 100644 --- a/internal/service/ec2/vpc_endpoint_private_dns_test.go +++ b/internal/service/ec2/vpc_endpoint_private_dns_test.go @@ -16,7 +16,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" tfec2 "github.com/hashicorp/terraform-provider-aws/internal/service/ec2" "github.com/hashicorp/terraform-provider-aws/names" ) @@ -39,7 +38,7 @@ func TestAccVPCEndpointPrivateDNS_basic(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckVPCEndpointDestroy(ctx), + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCEndpointPrivateDNSConfig_basic(rName, true), @@ -78,7 +77,7 @@ func TestAccVPCEndpointPrivateDNS_disabled(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckVPCEndpointDestroy(ctx), + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCEndpointPrivateDNSConfig_disabled(rName), @@ -117,7 +116,7 @@ func TestAccVPCEndpointPrivateDNS_disappears_Endpoint(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckVPCEndpointDestroy(ctx), + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCEndpointPrivateDNSConfig_basic(rName, true), @@ -150,7 +149,7 @@ func TestAccVPCEndpointPrivateDNS_update(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckVPCEndpointDestroy(ctx), + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCEndpointPrivateDNSConfig_basic(rName, true), @@ -184,49 +183,47 @@ func TestAccVPCEndpointPrivateDNS_update(t *testing.T) { } // testAccCheckVPCEndpointPrivateDNSEnabled verifies private DNS is enabled for a given VPC endpoint -func testAccCheckVPCEndpointPrivateDNSEnabled(ctx context.Context, name string) resource.TestCheckFunc { +func testAccCheckVPCEndpointPrivateDNSEnabled(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.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, name, errors.New("not found")) - } - - if rs.Primary.ID == "" { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, name, errors.New("not set")) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - out, err := tfec2.FindVPCEndpointByID(ctx, conn, rs.Primary.ID) + + output, err := tfec2.FindVPCEndpointByID(ctx, conn, rs.Primary.ID) + if err != nil { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, rs.Primary.ID, err) + return err } - if out.PrivateDnsEnabled != nil && aws.ToBool(out.PrivateDnsEnabled) { + + if aws.ToBool(output.PrivateDnsEnabled) { return nil } - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, rs.Primary.ID, errors.New("private DNS not enabled")) + return errors.New("private DNS not enabled") } } // testAccCheckVPCEndpointPrivateDNSDisabled verifies private DNS is not enabled for a given VPC endpoint -func testAccCheckVPCEndpointPrivateDNSDisabled(ctx context.Context, name string) resource.TestCheckFunc { +func testAccCheckVPCEndpointPrivateDNSDisabled(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.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, name, errors.New("not found")) - } - - if rs.Primary.ID == "" { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, name, errors.New("not set")) + return fmt.Errorf("Not found: %s", n) } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - out, err := tfec2.FindVPCEndpointByID(ctx, conn, rs.Primary.ID) + + output, err := tfec2.FindVPCEndpointByID(ctx, conn, rs.Primary.ID) + if err != nil { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, rs.Primary.ID, err) + return err } - if out.PrivateDnsEnabled != nil && aws.ToBool(out.PrivateDnsEnabled) { - return create.Error(names.EC2, create.ErrActionCheckingExistence, tfec2.ResNameEndpointPrivateDNS, rs.Primary.ID, errors.New("private DNS enabled")) + + if aws.ToBool(output.PrivateDnsEnabled) { + return errors.New("private DNS enabled") } return nil diff --git a/internal/service/ec2/vpc_endpoint_route_table_association.go b/internal/service/ec2/vpc_endpoint_route_table_association.go index c4d9a38f67d..11ff0cb5300 100644 --- a/internal/service/ec2/vpc_endpoint_route_table_association.go +++ b/internal/service/ec2/vpc_endpoint_route_table_association.go @@ -20,8 +20,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_endpoint_route_table_association") -func ResourceVPCEndpointRouteTableAssociation() *schema.Resource { +// @SDKResource("aws_vpc_endpoint_route_table_association", name="VPC Endpoint Route Table Association") +func resourceVPCEndpointRouteTableAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointRouteTableAssociationCreate, ReadWithoutTimeout: resourceVPCEndpointRouteTableAssociationRead, @@ -65,7 +65,7 @@ func resourceVPCEndpointRouteTableAssociationCreate(ctx context.Context, d *sche return sdkdiag.AppendErrorf(diags, "creating VPC Endpoint Route Table Association (%s): %s", id, err) } - d.SetId(VPCEndpointRouteTableAssociationCreateID(endpointID, routeTableID)) + d.SetId(vpcEndpointRouteTableAssociationCreateID(endpointID, routeTableID)) err = waitVPCEndpointRouteTableAssociationReady(ctx, conn, endpointID, routeTableID) @@ -146,7 +146,7 @@ func resourceVPCEndpointRouteTableAssociationImport(ctx context.Context, d *sche routeTableID := parts[1] log.Printf("[DEBUG] Importing VPC Endpoint (%s) Route Table (%s) Association", endpointID, routeTableID) - d.SetId(VPCEndpointRouteTableAssociationCreateID(endpointID, routeTableID)) + d.SetId(vpcEndpointRouteTableAssociationCreateID(endpointID, routeTableID)) d.Set(names.AttrVPCEndpointID, endpointID) d.Set("route_table_id", routeTableID) diff --git a/internal/service/ec2/vpc_endpoint_security_group_association.go b/internal/service/ec2/vpc_endpoint_security_group_association.go index 71dafad79e6..74de96a8436 100644 --- a/internal/service/ec2/vpc_endpoint_security_group_association.go +++ b/internal/service/ec2/vpc_endpoint_security_group_association.go @@ -19,8 +19,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_endpoint_security_group_association") -func ResourceVPCEndpointSecurityGroupAssociation() *schema.Resource { +// @SDKResource("aws_vpc_endpoint_security_group_association", name="VPC Endpoint Security Group Association") +func resourceVPCEndpointSecurityGroupAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointSecurityGroupAssociationCreate, ReadWithoutTimeout: resourceVPCEndpointSecurityGroupAssociationRead, @@ -97,7 +97,7 @@ func resourceVPCEndpointSecurityGroupAssociationCreate(ctx context.Context, d *s return sdkdiag.AppendFromErr(diags, err) } - d.SetId(VPCEndpointSecurityGroupAssociationCreateID(vpcEndpointID, securityGroupID)) + d.SetId(vpcEndpointSecurityGroupAssociationCreateID(vpcEndpointID, securityGroupID)) if replaceDefaultAssociation { // Delete the existing VPC endpoint/default security group association. diff --git a/internal/service/ec2/vpc_endpoint_service.go b/internal/service/ec2/vpc_endpoint_service.go index 1003a2312ee..cf34c22d6ab 100644 --- a/internal/service/ec2/vpc_endpoint_service.go +++ b/internal/service/ec2/vpc_endpoint_service.go @@ -30,7 +30,7 @@ import ( // @SDKResource("aws_vpc_endpoint_service", name="VPC Endpoint Service") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVPCEndpointService() *schema.Resource { +func resourceVPCEndpointService() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointServiceCreate, ReadWithoutTimeout: resourceVPCEndpointServiceRead, @@ -159,7 +159,7 @@ func resourceVPCEndpointServiceCreate(ctx context.Context, d *schema.ResourceDat input := &ec2.CreateVpcEndpointServiceConfigurationInput{ AcceptanceRequired: aws.Bool(d.Get("acceptance_required").(bool)), ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeVpcEndpointService), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVpcEndpointService), } if v, ok := d.GetOk("gateway_load_balancer_arns"); ok && v.(*schema.Set).Len() > 0 { @@ -253,7 +253,7 @@ func resourceVPCEndpointServiceRead(ctx context.Context, d *schema.ResourceData, d.Set(names.AttrState, svcCfg.ServiceState) d.Set("supported_ip_address_types", svcCfg.SupportedIpAddressTypes) - setTagsOutV2(ctx, svcCfg.Tags) + setTagsOut(ctx, svcCfg.Tags) allowedPrincipals, err := findVPCEndpointServicePermissionsByServiceID(ctx, conn, d.Id()) @@ -325,7 +325,7 @@ func resourceVPCEndpointServiceDelete(ctx context.Context, d *schema.ResourceDat }) if err == nil && output != nil { - err = unsuccessfulItemsErrorV2(output.Unsuccessful) + err = unsuccessfulItemsError(output.Unsuccessful) } if tfawserr.ErrCodeEquals(err, errCodeInvalidVPCEndpointServiceNotFound) { diff --git a/internal/service/ec2/vpc_endpoint_service_allowed_principal.go b/internal/service/ec2/vpc_endpoint_service_allowed_principal.go index 5b684762e24..b452838b8aa 100644 --- a/internal/service/ec2/vpc_endpoint_service_allowed_principal.go +++ b/internal/service/ec2/vpc_endpoint_service_allowed_principal.go @@ -17,8 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// @SDKResource("aws_vpc_endpoint_service_allowed_principal") -func ResourceVPCEndpointServiceAllowedPrincipal() *schema.Resource { +// @SDKResource("aws_vpc_endpoint_service_allowed_principal", name="Endpoint Service Allowed Principal") +func resourceVPCEndpointServiceAllowedPrincipal() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointServiceAllowedPrincipalCreate, ReadWithoutTimeout: resourceVPCEndpointServiceAllowedPrincipalRead, diff --git a/internal/service/ec2/vpc_endpoint_service_data_source.go b/internal/service/ec2/vpc_endpoint_service_data_source.go index 3ca6aa827f9..343405cd89d 100644 --- a/internal/service/ec2/vpc_endpoint_service_data_source.go +++ b/internal/service/ec2/vpc_endpoint_service_data_source.go @@ -23,8 +23,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_vpc_endpoint_service") -func DataSourceVPCEndpointService() *schema.Resource { +// @SDKDataSource("aws_vpc_endpoint_service", name="Endpoint Service") +func dataSourceVPCEndpointService() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCEndpointServiceRead, @@ -105,7 +105,7 @@ func dataSourceVPCEndpointServiceRead(ctx context.Context, d *schema.ResourceDat ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &ec2.DescribeVpcEndpointServicesInput{ - Filters: newAttributeFilterListV2( + Filters: newAttributeFilterList( map[string]string{ "service-type": d.Get("service_type").(string), }, @@ -125,11 +125,11 @@ func dataSourceVPCEndpointServiceRead(ctx context.Context, d *schema.ResourceDat } if v, ok := d.GetOk(names.AttrTags); ok { - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, v.(map[string]interface{}))))...) + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, v.(map[string]interface{}))))...) } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set))...) if len(input.Filters) == 0 { @@ -197,7 +197,7 @@ func dataSourceVPCEndpointServiceRead(ctx context.Context, d *schema.ResourceDat d.Set("supported_ip_address_types", sd.SupportedIpAddressTypes) d.Set("vpc_endpoint_policy_supported", sd.VpcEndpointPolicySupported) - err = d.Set(names.AttrTags, keyValueTagsV2(ctx, sd.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) + err = d.Set(names.AttrTags, keyValueTags(ctx, sd.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) if err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) diff --git a/internal/service/ec2/vpc_endpoint_service_private_dns_verification.go b/internal/service/ec2/vpc_endpoint_service_private_dns_verification.go index e2d9a60e8f0..f66526c78b6 100644 --- a/internal/service/ec2/vpc_endpoint_service_private_dns_verification.go +++ b/internal/service/ec2/vpc_endpoint_service_private_dns_verification.go @@ -5,10 +5,9 @@ package ec2 import ( "context" - "errors" + "fmt" "time" - "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework/resource" @@ -16,24 +15,20 @@ import ( "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/framework" + fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" "github.com/hashicorp/terraform-provider-aws/names" ) -// @FrameworkResource("aws_vpc_endpoint_service_private_dns_verification", name="Endpoint Service Private DNS Verification") -func newResourceEndpointServicePrivateDNSVerification(_ context.Context) (resource.ResourceWithConfigure, error) { - r := &resourceEndpointServicePrivateDNSVerification{} +// @FrameworkResource("aws_vpc_endpoint_service_private_dns_verification", name="VPC Endpoint Service Private DNS Verification") +func newVPCEndpointServicePrivateDNSVerificationResource(_ context.Context) (resource.ResourceWithConfigure, error) { + r := &vpcEndpointServicePrivateDNSVerificationResource{} r.SetDefaultCreateTimeout(30 * time.Minute) return r, nil } -const ( - ResNameEndpointServicePrivateDNSVerification = "Endpoint Service Private DNS Verification" -) - -type resourceEndpointServicePrivateDNSVerification struct { +type vpcEndpointServicePrivateDNSVerificationResource struct { framework.ResourceWithConfigure framework.WithNoOpRead framework.WithNoUpdate @@ -41,12 +36,12 @@ type resourceEndpointServicePrivateDNSVerification struct { framework.WithTimeouts } -func (r *resourceEndpointServicePrivateDNSVerification) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = "aws_vpc_endpoint_service_private_dns_verification" +func (*vpcEndpointServicePrivateDNSVerificationResource) Metadata(_ context.Context, request resource.MetadataRequest, response *resource.MetadataResponse) { + response.TypeName = "aws_vpc_endpoint_service_private_dns_verification" } -func (r *resourceEndpointServicePrivateDNSVerification) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ +func (r *vpcEndpointServicePrivateDNSVerificationResource) Schema(ctx context.Context, request resource.SchemaRequest, response *resource.SchemaResponse) { + response.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ "service_id": schema.StringAttribute{ Required: true, @@ -66,58 +61,39 @@ func (r *resourceEndpointServicePrivateDNSVerification) Schema(ctx context.Conte } } -func (r *resourceEndpointServicePrivateDNSVerification) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - conn := r.Meta().EC2Client(ctx) - - var plan resourceEndpointServicePrivateDNSVerificationData - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { +func (r *vpcEndpointServicePrivateDNSVerificationResource) Create(ctx context.Context, request resource.CreateRequest, response *resource.CreateResponse) { + var data vpcEndpointServicePrivateDNSVerificationResourceModel + response.Diagnostics.Append(request.Plan.Get(ctx, &data)...) + if response.Diagnostics.HasError() { return } - in := &ec2.StartVpcEndpointServicePrivateDnsVerificationInput{ - ServiceId: aws.String(plan.ServiceID.ValueString()), + conn := r.Meta().EC2Client(ctx) + + input := &ec2.StartVpcEndpointServicePrivateDnsVerificationInput{ + ServiceId: fwflex.StringFromFramework(ctx, data.ServiceID), } - out, err := conn.StartVpcEndpointServicePrivateDnsVerification(ctx, in) + _, err := conn.StartVpcEndpointServicePrivateDnsVerification(ctx, input) + if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointServicePrivateDNSVerification, plan.ServiceID.String(), err), - err.Error(), - ) - return - } - if out == nil || out.ReturnValue == nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointServicePrivateDNSVerification, plan.ServiceID.String(), nil), - errors.New("empty output").Error(), - ) - return - } - if !aws.ToBool(out.ReturnValue) { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionCreating, ResNameEndpointServicePrivateDNSVerification, plan.ServiceID.String(), nil), - errors.New("request failed").Error(), - ) + response.Diagnostics.AddError(fmt.Sprintf("starting VPC Endpoint Service Private DNS Verification (%s)", data.ServiceID.ValueString()), err.Error()) + return } - if plan.WaitForVerification.ValueBool() { - createTimeout := r.CreateTimeout(ctx, plan.Timeouts) - _, err := waitVPCEndpointServicePrivateDNSNameVerified(ctx, conn, plan.ServiceID.ValueString(), createTimeout) - if err != nil { - resp.Diagnostics.AddError( - create.ProblemStandardMessage(names.EC2, create.ErrActionWaitingForCreation, ResNameEndpointServicePrivateDNSVerification, plan.ServiceID.String(), err), - err.Error(), - ) + if data.WaitForVerification.ValueBool() { + if _, err := waitVPCEndpointServicePrivateDNSNameVerified(ctx, conn, data.ServiceID.ValueString(), r.CreateTimeout(ctx, data.Timeouts)); err != nil { + response.Diagnostics.AddError(fmt.Sprintf("waiting for VPC Endpoint Service Private DNS Verification (%s)", data.ServiceID.ValueString()), err.Error()) + return } } - resp.Diagnostics.Append(resp.State.Set(ctx, plan)...) + response.Diagnostics.Append(response.State.Set(ctx, data)...) } -type resourceEndpointServicePrivateDNSVerificationData struct { +type vpcEndpointServicePrivateDNSVerificationResourceModel struct { ServiceID types.String `tfsdk:"service_id"` Timeouts timeouts.Value `tfsdk:"timeouts"` WaitForVerification types.Bool `tfsdk:"wait_for_verification"` diff --git a/internal/service/ec2/vpc_endpoint_service_private_dns_verification_test.go b/internal/service/ec2/vpc_endpoint_service_private_dns_verification_test.go index 78bdf3b1c98..274217a5254 100644 --- a/internal/service/ec2/vpc_endpoint_service_private_dns_verification_test.go +++ b/internal/service/ec2/vpc_endpoint_service_private_dns_verification_test.go @@ -32,7 +32,7 @@ func TestAccVPCEndpointServicePrivateDNSVerification_basic(t *testing.T) { }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: nil, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCEndpointServicePrivateDNSVerificationConfig_basic(rName, domainName), @@ -60,20 +60,20 @@ func TestAccVPCEndpointServicePrivateDNSVerification_waitForVerification(t *test }, ErrorCheck: acctest.ErrorCheck(t, names.EC2ServiceID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: nil, + CheckDestroy: acctest.CheckDestroyNoop, Steps: []resource.TestStep{ { Config: testAccVPCEndpointServicePrivateDNSVerificationConfig_waitForVerification(rName, domainName), // Expect an error as private DNS setup and verification is not // included in this configuration. This test simply verifies the // create waiter functions as expected. - ExpectError: regexache.MustCompile("waiting for creation"), + ExpectError: regexache.MustCompile("waiting for VPC Endpoint Service Private DNS Verification"), }, }, }) } -func testAccVPCEndpointServicePrivateDNSVerificationConfigBase(rName, domainName string, count int) string { +func testAccVPCEndpointServicePrivateDNSVerificationConfig_base(rName, domainName string, count int) string { return acctest.ConfigCompose( acctest.ConfigVPCWithSubnets(rName, 2), fmt.Sprintf(` @@ -104,7 +104,7 @@ resource "aws_vpc_endpoint_service" "test" { func testAccVPCEndpointServicePrivateDNSVerificationConfig_basic(rName, domainName string) string { return acctest.ConfigCompose( - testAccVPCEndpointServicePrivateDNSVerificationConfigBase(rName, domainName, 1), + testAccVPCEndpointServicePrivateDNSVerificationConfig_base(rName, domainName, 1), ` resource "aws_vpc_endpoint_service_private_dns_verification" "test" { service_id = aws_vpc_endpoint_service.test.id @@ -114,7 +114,7 @@ resource "aws_vpc_endpoint_service_private_dns_verification" "test" { func testAccVPCEndpointServicePrivateDNSVerificationConfig_waitForVerification(rName, domainName string) string { return acctest.ConfigCompose( - testAccVPCEndpointServicePrivateDNSVerificationConfigBase(rName, domainName, 1), + testAccVPCEndpointServicePrivateDNSVerificationConfig_base(rName, domainName, 1), ` resource "aws_vpc_endpoint_service_private_dns_verification" "test" { service_id = aws_vpc_endpoint_service.test.id diff --git a/internal/service/ec2/vpc_endpoint_subnet_association.go b/internal/service/ec2/vpc_endpoint_subnet_association.go index 5d49422609f..18758a83f9b 100644 --- a/internal/service/ec2/vpc_endpoint_subnet_association.go +++ b/internal/service/ec2/vpc_endpoint_subnet_association.go @@ -22,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_endpoint_subnet_association") -func ResourceVPCEndpointSubnetAssociation() *schema.Resource { +// @SDKResource("aws_vpc_endpoint_subnet_association", name="VPC Endpoint Subnet Association") +func resourceVPCEndpointSubnetAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCEndpointSubnetAssociationCreate, ReadWithoutTimeout: resourceVPCEndpointSubnetAssociationRead, @@ -90,7 +90,7 @@ func resourceVPCEndpointSubnetAssociationCreate(ctx context.Context, d *schema.R return sdkdiag.AppendErrorf(diags, "creating VPC Endpoint Subnet Association (%s): %s", id, err) } - d.SetId(VPCEndpointSubnetAssociationCreateID(endpointID, subnetID)) + d.SetId(vpcEndpointSubnetAssociationCreateID(endpointID, subnetID)) _, err = waitVPCEndpointAvailable(ctx, conn, endpointID, d.Timeout(schema.TimeoutCreate)) @@ -169,7 +169,7 @@ func resourceVPCEndpointSubnetAssociationImport(ctx context.Context, d *schema.R subnetID := parts[1] log.Printf("[DEBUG] Importing VPC Endpoint (%s) Subnet (%s) Association", endpointID, subnetID) - d.SetId(VPCEndpointSubnetAssociationCreateID(endpointID, subnetID)) + d.SetId(vpcEndpointSubnetAssociationCreateID(endpointID, subnetID)) d.Set(names.AttrVPCEndpointID, endpointID) d.Set(names.AttrSubnetID, subnetID) diff --git a/internal/service/ec2/vpc_flow_log.go b/internal/service/ec2/vpc_flow_log.go index 4ba77f0eefb..2adec49a6ae 100644 --- a/internal/service/ec2/vpc_flow_log.go +++ b/internal/service/ec2/vpc_flow_log.go @@ -9,15 +9,17 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -28,7 +30,7 @@ import ( // @SDKResource("aws_flow_log", name="Flow Log") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceFlowLog() *schema.Resource { +func resourceFlowLog() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceLogFlowCreate, ReadWithoutTimeout: resourceLogFlowRead, @@ -59,11 +61,11 @@ func ResourceFlowLog() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "file_format": { - Type: schema.TypeString, - ValidateFunc: validation.StringInSlice(ec2.DestinationFileFormat_Values(), false), - Optional: true, - Default: ec2.DestinationFileFormatPlainText, - ForceNew: true, + Type: schema.TypeString, + Optional: true, + Default: awstypes.DestinationFileFormatPlainText, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.DestinationFileFormat](), }, "hive_compatible_partitions": { Type: schema.TypeBool, @@ -101,11 +103,11 @@ func ResourceFlowLog() *schema.Resource { ConflictsWith: []string{names.AttrLogGroupName}, }, "log_destination_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Default: ec2.LogDestinationTypeCloudWatchLogs, - ValidateFunc: validation.StringInSlice(ec2.LogDestinationType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: awstypes.LogDestinationTypeCloudWatchLogs, + ValidateDiagFunc: enum.Validate[awstypes.LogDestinationType](), }, "log_format": { Type: schema.TypeString, @@ -137,10 +139,10 @@ func ResourceFlowLog() *schema.Resource { names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), "traffic_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(ec2.TrafficType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.TrafficType](), }, names.AttrTransitGatewayAttachmentID: { Type: schema.TypeString, @@ -168,33 +170,33 @@ func ResourceFlowLog() *schema.Resource { func resourceLogFlowCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) var resourceID string - var resourceType string + var resourceType awstypes.FlowLogsResourceType for _, v := range []struct { ID string - Type string + Type awstypes.FlowLogsResourceType }{ { ID: d.Get(names.AttrVPCID).(string), - Type: ec2.FlowLogsResourceTypeVpc, + Type: awstypes.FlowLogsResourceTypeVpc, }, { ID: d.Get(names.AttrTransitGatewayID).(string), - Type: ec2.FlowLogsResourceTypeTransitGateway, + Type: awstypes.FlowLogsResourceTypeTransitGateway, }, { ID: d.Get(names.AttrTransitGatewayAttachmentID).(string), - Type: ec2.FlowLogsResourceTypeTransitGatewayAttachment, + Type: awstypes.FlowLogsResourceTypeTransitGatewayAttachment, }, { ID: d.Get(names.AttrSubnetID).(string), - Type: ec2.FlowLogsResourceTypeSubnet, + Type: awstypes.FlowLogsResourceTypeSubnet, }, { ID: d.Get("eni_id").(string), - Type: ec2.FlowLogsResourceTypeNetworkInterface, + Type: awstypes.FlowLogsResourceTypeNetworkInterface, }, } { if v.ID != "" { @@ -206,15 +208,15 @@ func resourceLogFlowCreate(ctx context.Context, d *schema.ResourceData, meta int input := &ec2.CreateFlowLogsInput{ ClientToken: aws.String(id.UniqueId()), - LogDestinationType: aws.String(d.Get("log_destination_type").(string)), - ResourceIds: aws.StringSlice([]string{resourceID}), - ResourceType: aws.String(resourceType), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeVpcFlowLog), + LogDestinationType: awstypes.LogDestinationType(d.Get("log_destination_type").(string)), + ResourceIds: []string{resourceID}, + ResourceType: resourceType, + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVpcFlowLog), } - if resourceType != ec2.FlowLogsResourceTypeTransitGateway && resourceType != ec2.FlowLogsResourceTypeTransitGatewayAttachment { + if resourceType != awstypes.FlowLogsResourceTypeTransitGateway && resourceType != awstypes.FlowLogsResourceTypeTransitGatewayAttachment { if v, ok := d.GetOk("traffic_type"); ok { - input.TrafficType = aws.String(v.(string)) + input.TrafficType = awstypes.TrafficType(v.(string)) } } @@ -243,31 +245,31 @@ func resourceLogFlowCreate(ctx context.Context, d *schema.ResourceData, meta int } if v, ok := d.GetOk("max_aggregation_interval"); ok { - input.MaxAggregationInterval = aws.Int64(int64(v.(int))) + input.MaxAggregationInterval = aws.Int32(int32(v.(int))) } outputRaw, err := tfresource.RetryWhenAWSErrMessageContains(ctx, iamPropagationTimeout, func() (interface{}, error) { - return conn.CreateFlowLogsWithContext(ctx, input) + return conn.CreateFlowLogs(ctx, input) }, errCodeInvalidParameter, "Unable to assume given IAM role") if err == nil && outputRaw != nil { - err = UnsuccessfulItemsError(outputRaw.(*ec2.CreateFlowLogsOutput).Unsuccessful) + err = unsuccessfulItemsError(outputRaw.(*ec2.CreateFlowLogsOutput).Unsuccessful) } if err != nil { return sdkdiag.AppendErrorf(diags, "creating Flow Log (%s): %s", resourceID, err) } - d.SetId(aws.StringValue(outputRaw.(*ec2.CreateFlowLogsOutput).FlowLogIds[0])) + d.SetId(outputRaw.(*ec2.CreateFlowLogsOutput).FlowLogIds[0]) return append(diags, resourceLogFlowRead(ctx, d, meta)...) } func resourceLogFlowRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - fl, err := FindFlowLogByID(ctx, conn, d.Id()) + fl, err := findFlowLogByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Flow Log %s not found, removing from state", d.Id()) @@ -281,7 +283,7 @@ func resourceLogFlowRead(ctx context.Context, d *schema.ResourceData, meta inter arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: meta.(*conns.AWSClient).AccountID, Resource: fmt.Sprintf("vpc-flow-log/%s", d.Id()), @@ -301,7 +303,7 @@ func resourceLogFlowRead(ctx context.Context, d *schema.ResourceData, meta inter d.Set("log_format", fl.LogFormat) d.Set(names.AttrLogGroupName, fl.LogGroupName) d.Set("max_aggregation_interval", fl.MaxAggregationInterval) - switch resourceID := aws.StringValue(fl.ResourceId); { + switch resourceID := aws.ToString(fl.ResourceId); { case strings.HasPrefix(resourceID, "vpc-"): d.Set(names.AttrVPCID, resourceID) case strings.HasPrefix(resourceID, "tgw-"): @@ -315,7 +317,7 @@ func resourceLogFlowRead(ctx context.Context, d *schema.ResourceData, meta inter case strings.HasPrefix(resourceID, "eni-"): d.Set("eni_id", resourceID) } - if !strings.HasPrefix(aws.StringValue(fl.ResourceId), "tgw-") { + if !strings.HasPrefix(aws.ToString(fl.ResourceId), "tgw-") { d.Set("traffic_type", fl.TrafficType) } @@ -334,15 +336,15 @@ func resourceLogFlowUpdate(ctx context.Context, d *schema.ResourceData, meta int func resourceLogFlowDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting Flow Log: %s", d.Id()) - output, err := conn.DeleteFlowLogsWithContext(ctx, &ec2.DeleteFlowLogsInput{ - FlowLogIds: aws.StringSlice([]string{d.Id()}), + output, err := conn.DeleteFlowLogs(ctx, &ec2.DeleteFlowLogsInput{ + FlowLogIds: []string{d.Id()}, }) if err == nil && output != nil { - err = UnsuccessfulItemsError(output.Unsuccessful) + err = unsuccessfulItemsError(output.Unsuccessful) } if tfawserr.ErrCodeEquals(err, errCodeInvalidFlowLogIdNotFound) { @@ -356,15 +358,15 @@ func resourceLogFlowDelete(ctx context.Context, d *schema.ResourceData, meta int return diags } -func expandDestinationOptionsRequest(tfMap map[string]interface{}) *ec2.DestinationOptionsRequest { +func expandDestinationOptionsRequest(tfMap map[string]interface{}) *awstypes.DestinationOptionsRequest { if tfMap == nil { return nil } - apiObject := &ec2.DestinationOptionsRequest{} + apiObject := &awstypes.DestinationOptionsRequest{} if v, ok := tfMap["file_format"].(string); ok && v != "" { - apiObject.FileFormat = aws.String(v) + apiObject.FileFormat = awstypes.DestinationFileFormat(v) } if v, ok := tfMap["hive_compatible_partitions"].(bool); ok { @@ -378,19 +380,17 @@ func expandDestinationOptionsRequest(tfMap map[string]interface{}) *ec2.Destinat return apiObject } -func flattenDestinationOptionsResponse(apiObject *ec2.DestinationOptionsResponse) map[string]interface{} { - tfMap := map[string]interface{}{} - - if v := apiObject.FileFormat; v != nil { - tfMap["file_format"] = aws.StringValue(v) +func flattenDestinationOptionsResponse(apiObject *awstypes.DestinationOptionsResponse) map[string]interface{} { + tfMap := map[string]interface{}{ + "file_format": apiObject.FileFormat, } if v := apiObject.HiveCompatiblePartitions; v != nil { - tfMap["hive_compatible_partitions"] = aws.BoolValue(v) + tfMap["hive_compatible_partitions"] = aws.ToBool(v) } if v := apiObject.PerHourPartition; v != nil { - tfMap["per_hour_partition"] = aws.BoolValue(v) + tfMap["per_hour_partition"] = aws.ToBool(v) } return tfMap diff --git a/internal/service/ec2/vpc_flow_log_test.go b/internal/service/ec2/vpc_flow_log_test.go index 698c9a3eb02..ff88d3d07a0 100644 --- a/internal/service/ec2/vpc_flow_log_test.go +++ b/internal/service/ec2/vpc_flow_log_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -22,7 +22,7 @@ import ( func TestAccVPCFlowLog_basic(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog cloudwatchLogGroupResourceName := "aws_cloudwatch_log_group.test" iamRoleResourceName := "aws_iam_role.test" resourceName := "aws_flow_log.test" @@ -62,7 +62,7 @@ func TestAccVPCFlowLog_basic(t *testing.T) { func TestAccVPCFlowLog_logFormat(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) logFormat := "${version} ${vpc-id} ${subnet-id}" @@ -91,7 +91,7 @@ func TestAccVPCFlowLog_logFormat(t *testing.T) { func TestAccVPCFlowLog_subnetID(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog cloudwatchLogGroupResourceName := "aws_cloudwatch_log_group.test" iamRoleResourceName := "aws_iam_role.test" resourceName := "aws_flow_log.test" @@ -128,7 +128,7 @@ func TestAccVPCFlowLog_subnetID(t *testing.T) { func TestAccVPCFlowLog_transitGatewayID(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog cloudwatchLogGroupResourceName := "aws_cloudwatch_log_group.test" iamRoleResourceName := "aws_iam_role.test" resourceName := "aws_flow_log.test" @@ -165,7 +165,7 @@ func TestAccVPCFlowLog_transitGatewayID(t *testing.T) { func TestAccVPCFlowLog_transitGatewayAttachmentID(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog cloudwatchLogGroupResourceName := "aws_cloudwatch_log_group.test" iamRoleResourceName := "aws_iam_role.test" resourceName := "aws_flow_log.test" @@ -202,7 +202,7 @@ func TestAccVPCFlowLog_transitGatewayAttachmentID(t *testing.T) { func TestAccVPCFlowLog_LogDestinationType_cloudWatchLogs(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog cloudwatchLogGroupResourceName := "aws_cloudwatch_log_group.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -234,7 +234,7 @@ func TestAccVPCFlowLog_LogDestinationType_cloudWatchLogs(t *testing.T) { func TestAccVPCFlowLog_LogDestinationType_kinesisFirehose(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog kinesisFirehoseResourceName := "aws_kinesis_firehose_delivery_stream.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -265,7 +265,7 @@ func TestAccVPCFlowLog_LogDestinationType_kinesisFirehose(t *testing.T) { func TestAccVPCFlowLog_LogDestinationType_s3(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog s3ResourceName := "aws_s3_bucket.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -314,7 +314,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3_invalid(t *testing.T) { func TestAccVPCFlowLog_LogDestinationTypeS3DO_plainText(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog s3ResourceName := "aws_s3_bucket.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -346,7 +346,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DO_plainText(t *testing.T) { func TestAccVPCFlowLog_LogDestinationTypeS3DOPlainText_hiveCompatible(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog s3ResourceName := "aws_s3_bucket.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -380,7 +380,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DOPlainText_hiveCompatible(t *testing func TestAccVPCFlowLog_LogDestinationTypeS3DO_parquet(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog s3ResourceName := "aws_s3_bucket.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -412,7 +412,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DO_parquet(t *testing.T) { func TestAccVPCFlowLog_LogDestinationTypeS3DOParquet_hiveCompatible(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog s3ResourceName := "aws_s3_bucket.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -445,7 +445,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DOParquet_hiveCompatible(t *testing.T func TestAccVPCFlowLog_LogDestinationTypeS3DOParquetHiveCompatible_perHour(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog s3ResourceName := "aws_s3_bucket.test" resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -479,7 +479,7 @@ func TestAccVPCFlowLog_LogDestinationTypeS3DOParquetHiveCompatible_perHour(t *te func TestAccVPCFlowLog_LogDestinationType_maxAggregationInterval(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -507,7 +507,7 @@ func TestAccVPCFlowLog_LogDestinationType_maxAggregationInterval(t *testing.T) { func TestAccVPCFlowLog_tags(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -553,7 +553,7 @@ func TestAccVPCFlowLog_tags(t *testing.T) { func TestAccVPCFlowLog_disappears(t *testing.T) { ctx := acctest.Context(t) - var flowLog ec2.FlowLog + var flowLog awstypes.FlowLog resourceName := "aws_flow_log.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -575,7 +575,7 @@ func TestAccVPCFlowLog_disappears(t *testing.T) { }) } -func testAccCheckFlowLogExists(ctx context.Context, n string, v *ec2.FlowLog) resource.TestCheckFunc { +func testAccCheckFlowLogExists(ctx context.Context, n string, v *awstypes.FlowLog) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -586,7 +586,7 @@ func testAccCheckFlowLogExists(ctx context.Context, n string, v *ec2.FlowLog) re return fmt.Errorf("No Flow Log ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindFlowLogByID(ctx, conn, rs.Primary.ID) @@ -602,7 +602,7 @@ func testAccCheckFlowLogExists(ctx context.Context, n string, v *ec2.FlowLog) re func testAccCheckFlowLogDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_flow_log" { diff --git a/internal/service/ec2/vpc_internet_gateway.go b/internal/service/ec2/vpc_internet_gateway.go index 042ee40740d..997b504c8f9 100644 --- a/internal/service/ec2/vpc_internet_gateway.go +++ b/internal/service/ec2/vpc_internet_gateway.go @@ -9,10 +9,11 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -26,7 +27,7 @@ import ( // @SDKResource("aws_internet_gateway", name="Internet Gateway") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceInternetGateway() *schema.Resource { +func resourceInternetGateway() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceInternetGatewayCreate, ReadWithoutTimeout: resourceInternetGatewayRead, @@ -67,20 +68,20 @@ func ResourceInternetGateway() *schema.Resource { func resourceInternetGatewayCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateInternetGatewayInput{ - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeInternetGateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeInternetGateway), } - log.Printf("[DEBUG] Creating EC2 Internet Gateway: %s", input) - output, err := conn.CreateInternetGatewayWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 Internet Gateway: %#v", input) + output, err := conn.CreateInternetGateway(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Internet Gateway: %s", err) } - d.SetId(aws.StringValue(output.InternetGateway.InternetGatewayId)) + d.SetId(aws.ToString(output.InternetGateway.InternetGatewayId)) if v, ok := d.GetOk(names.AttrVPCID); ok { if err := attachInternetGateway(ctx, conn, d.Id(), v.(string), d.Timeout(schema.TimeoutCreate)); err != nil { @@ -93,10 +94,10 @@ func resourceInternetGatewayCreate(ctx context.Context, d *schema.ResourceData, func resourceInternetGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindInternetGatewayByID(ctx, conn, d.Id()) + return findInternetGatewayByID(ctx, conn, d.Id()) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -109,12 +110,12 @@ func resourceInternetGatewayRead(ctx context.Context, d *schema.ResourceData, me return sdkdiag.AppendErrorf(diags, "reading EC2 Internet Gateway (%s): %s", d.Id(), err) } - ig := outputRaw.(*ec2.InternetGateway) + ig := outputRaw.(*awstypes.InternetGateway) - ownerID := aws.StringValue(ig.OwnerId) + ownerID := aws.ToString(ig.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("internet-gateway/%s", d.Id()), @@ -135,7 +136,7 @@ func resourceInternetGatewayRead(ctx context.Context, d *schema.ResourceData, me func resourceInternetGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) if d.HasChange(names.AttrVPCID) { o, n := d.GetChange(names.AttrVPCID) @@ -158,7 +159,7 @@ func resourceInternetGatewayUpdate(ctx context.Context, d *schema.ResourceData, func resourceInternetGatewayDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) // Detach if it is attached. if v, ok := d.GetOk(names.AttrVPCID); ok { @@ -173,7 +174,7 @@ func resourceInternetGatewayDelete(ctx context.Context, d *schema.ResourceData, log.Printf("[INFO] Deleting Internet Gateway: %s", d.Id()) _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { - return conn.DeleteInternetGatewayWithContext(ctx, input) + return conn.DeleteInternetGateway(ctx, input) }, errCodeDependencyViolation) if tfawserr.ErrCodeEquals(err, errCodeInvalidInternetGatewayIDNotFound) { @@ -187,22 +188,22 @@ func resourceInternetGatewayDelete(ctx context.Context, d *schema.ResourceData, return diags } -func attachInternetGateway(ctx context.Context, conn *ec2.EC2, internetGatewayID, vpcID string, timeout time.Duration) error { +func attachInternetGateway(ctx context.Context, conn *ec2.Client, internetGatewayID, vpcID string, timeout time.Duration) error { input := &ec2.AttachInternetGatewayInput{ InternetGatewayId: aws.String(internetGatewayID), VpcId: aws.String(vpcID), } - log.Printf("[INFO] Attaching EC2 Internet Gateway: %s", input) + log.Printf("[INFO] Attaching EC2 Internet Gateway: %#v", input) _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, timeout, func() (interface{}, error) { - return conn.AttachInternetGatewayWithContext(ctx, input) + return conn.AttachInternetGateway(ctx, input) }, errCodeInvalidInternetGatewayIDNotFound) if err != nil { return fmt.Errorf("attaching EC2 Internet Gateway (%s) to VPC (%s): %w", internetGatewayID, vpcID, err) } - _, err = WaitInternetGatewayAttached(ctx, conn, internetGatewayID, vpcID, timeout) + _, err = waitInternetGatewayAttached(ctx, conn, internetGatewayID, vpcID, timeout) if err != nil { return fmt.Errorf("waiting for EC2 Internet Gateway (%s) to attach to VPC (%s): %w", internetGatewayID, vpcID, err) @@ -211,15 +212,15 @@ func attachInternetGateway(ctx context.Context, conn *ec2.EC2, internetGatewayID return nil } -func detachInternetGateway(ctx context.Context, conn *ec2.EC2, internetGatewayID, vpcID string, timeout time.Duration) error { +func detachInternetGateway(ctx context.Context, conn *ec2.Client, internetGatewayID, vpcID string, timeout time.Duration) error { input := &ec2.DetachInternetGatewayInput{ InternetGatewayId: aws.String(internetGatewayID), VpcId: aws.String(vpcID), } - log.Printf("[INFO] Detaching EC2 Internet Gateway: %s", input) + log.Printf("[INFO] Detaching EC2 Internet Gateway: %#v", input) _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, timeout, func() (interface{}, error) { - return conn.DetachInternetGatewayWithContext(ctx, input) + return conn.DetachInternetGateway(ctx, input) }, errCodeDependencyViolation) if tfawserr.ErrCodeEquals(err, errCodeGatewayNotAttached) { @@ -230,7 +231,7 @@ func detachInternetGateway(ctx context.Context, conn *ec2.EC2, internetGatewayID return fmt.Errorf("detaching EC2 Internet Gateway (%s) from VPC (%s): %w", internetGatewayID, vpcID, err) } - _, err = WaitInternetGatewayDetached(ctx, conn, internetGatewayID, vpcID, timeout) + _, err = waitInternetGatewayDetached(ctx, conn, internetGatewayID, vpcID, timeout) if err != nil { return fmt.Errorf("waiting for EC2 Internet Gateway (%s) to detach from VPC (%s): %w", internetGatewayID, vpcID, err) diff --git a/internal/service/ec2/vpc_internet_gateway_attachment.go b/internal/service/ec2/vpc_internet_gateway_attachment.go index fb4b9700d84..dbffe72e566 100644 --- a/internal/service/ec2/vpc_internet_gateway_attachment.go +++ b/internal/service/ec2/vpc_internet_gateway_attachment.go @@ -10,7 +10,7 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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" @@ -19,8 +19,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_internet_gateway_attachment") -func ResourceInternetGatewayAttachment() *schema.Resource { +// @SDKResource("aws_internet_gateway_attachment", name="Internet Gateway Attachment") +func resourceInternetGatewayAttachment() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceInternetGatewayAttachmentCreate, ReadWithoutTimeout: resourceInternetGatewayAttachmentRead, @@ -52,7 +52,7 @@ func ResourceInternetGatewayAttachment() *schema.Resource { func resourceInternetGatewayAttachmentCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) igwID := d.Get("internet_gateway_id").(string) vpcID := d.Get(names.AttrVPCID).(string) @@ -61,23 +61,23 @@ func resourceInternetGatewayAttachmentCreate(ctx context.Context, d *schema.Reso return sdkdiag.AppendErrorf(diags, "creating EC2 Internet Gateway Attachment: %s", err) } - d.SetId(InternetGatewayAttachmentCreateResourceID(igwID, vpcID)) + d.SetId(internetGatewayAttachmentCreateResourceID(igwID, vpcID)) return append(diags, resourceInternetGatewayAttachmentRead(ctx, d, meta)...) } func resourceInternetGatewayAttachmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - igwID, vpcID, err := InternetGatewayAttachmentParseResourceID(d.Id()) + igwID, vpcID, err := internetGatewayAttachmentParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Internet Gateway Attachment (%s): %s", d.Id(), err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindInternetGatewayAttachment(ctx, conn, igwID, vpcID) + return findInternetGatewayAttachment(ctx, conn, igwID, vpcID) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -90,7 +90,7 @@ func resourceInternetGatewayAttachmentRead(ctx context.Context, d *schema.Resour return sdkdiag.AppendErrorf(diags, "reading EC2 Internet Gateway Attachment (%s): %s", d.Id(), err) } - igw := outputRaw.(*ec2.InternetGatewayAttachment) + igw := outputRaw.(*awstypes.InternetGatewayAttachment) d.Set("internet_gateway_id", igwID) d.Set(names.AttrVPCID, igw.VpcId) @@ -100,9 +100,9 @@ func resourceInternetGatewayAttachmentRead(ctx context.Context, d *schema.Resour func resourceInternetGatewayAttachmentDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - igwID, vpcID, err := InternetGatewayAttachmentParseResourceID(d.Id()) + igwID, vpcID, err := internetGatewayAttachmentParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "deleting EC2 Internet Gateway Attachment (%s): %s", d.Id(), err) } @@ -116,14 +116,14 @@ func resourceInternetGatewayAttachmentDelete(ctx context.Context, d *schema.Reso const internetGatewayAttachmentIDSeparator = ":" -func InternetGatewayAttachmentCreateResourceID(igwID, vpcID string) string { +func internetGatewayAttachmentCreateResourceID(igwID, vpcID string) string { parts := []string{igwID, vpcID} id := strings.Join(parts, internetGatewayAttachmentIDSeparator) return id } -func InternetGatewayAttachmentParseResourceID(id string) (string, string, error) { +func internetGatewayAttachmentParseResourceID(id string) (string, string, error) { parts := strings.Split(id, internetGatewayAttachmentIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/vpc_internet_gateway_attachment_test.go b/internal/service/ec2/vpc_internet_gateway_attachment_test.go index 0858e5c67e5..6c0c9e444d0 100644 --- a/internal/service/ec2/vpc_internet_gateway_attachment_test.go +++ b/internal/service/ec2/vpc_internet_gateway_attachment_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -21,7 +21,7 @@ import ( func TestAccVPCInternetGatewayAttachment_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.InternetGatewayAttachment + var v awstypes.InternetGatewayAttachment resourceName := "aws_internet_gateway_attachment.test" igwResourceName := "aws_internet_gateway.test" vpcResourceName := "aws_vpc.test" @@ -52,7 +52,7 @@ func TestAccVPCInternetGatewayAttachment_basic(t *testing.T) { func TestAccVPCInternetGatewayAttachment_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.InternetGatewayAttachment + var v awstypes.InternetGatewayAttachment resourceName := "aws_internet_gateway_attachment.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -76,7 +76,7 @@ func TestAccVPCInternetGatewayAttachment_disappears(t *testing.T) { func testAccCheckInternetGatewayAttachmentDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_internet_gateway_attachment" { @@ -106,7 +106,7 @@ func testAccCheckInternetGatewayAttachmentDestroy(ctx context.Context) resource. } } -func testAccCheckInternetGatewayAttachmentExists(ctx context.Context, n string, v *ec2.InternetGatewayAttachment) resource.TestCheckFunc { +func testAccCheckInternetGatewayAttachmentExists(ctx context.Context, n string, v *awstypes.InternetGatewayAttachment) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -117,7 +117,7 @@ func testAccCheckInternetGatewayAttachmentExists(ctx context.Context, n string, return fmt.Errorf("No EC2 Internet Gateway Attachment ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) igwID, vpcID, err := tfec2.InternetGatewayAttachmentParseResourceID(rs.Primary.ID) diff --git a/internal/service/ec2/vpc_internet_gateway_data_source.go b/internal/service/ec2/vpc_internet_gateway_data_source.go index fc6e2cb147c..dd2badb73bd 100644 --- a/internal/service/ec2/vpc_internet_gateway_data_source.go +++ b/internal/service/ec2/vpc_internet_gateway_data_source.go @@ -8,9 +8,10 @@ import ( "fmt" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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" @@ -20,8 +21,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_internet_gateway") -func DataSourceInternetGateway() *schema.Resource { +// @SDKDataSource("aws_internet_gateway", name="Internet Gateway") +func dataSourceInternetGateway() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceInternetGatewayRead, @@ -67,7 +68,7 @@ func DataSourceInternetGateway() *schema.Resource { func dataSourceInternetGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig internetGatewayId, internetGatewayIdOk := d.GetOk("internet_gateway_id") @@ -89,18 +90,18 @@ func dataSourceInternetGatewayRead(ctx context.Context, d *schema.ResourceData, filter.(*schema.Set), )...) - igw, err := FindInternetGateway(ctx, conn, input) + igw, err := findInternetGateway(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 Internet Gateway", err)) } - d.SetId(aws.StringValue(igw.InternetGatewayId)) + d.SetId(aws.ToString(igw.InternetGatewayId)) - ownerID := aws.StringValue(igw.OwnerId) + ownerID := aws.ToString(igw.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("internet-gateway/%s", d.Id()), @@ -114,19 +115,19 @@ func dataSourceInternetGatewayRead(ctx context.Context, d *schema.ResourceData, d.Set("internet_gateway_id", igw.InternetGatewayId) d.Set(names.AttrOwnerID, ownerID) - if err := d.Set(names.AttrTags, KeyValueTags(ctx, igw.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, igw.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } return diags } -func flattenInternetGatewayAttachments(igwAttachments []*ec2.InternetGatewayAttachment) []map[string]interface{} { +func flattenInternetGatewayAttachments(igwAttachments []awstypes.InternetGatewayAttachment) []map[string]interface{} { attachments := make([]map[string]interface{}, 0, len(igwAttachments)) for _, a := range igwAttachments { m := make(map[string]interface{}) - m[names.AttrState] = aws.StringValue(a.State) - m[names.AttrVPCID] = aws.StringValue(a.VpcId) + m[names.AttrState] = string(a.State) + m[names.AttrVPCID] = aws.ToString(a.VpcId) attachments = append(attachments, m) } diff --git a/internal/service/ec2/vpc_internet_gateway_test.go b/internal/service/ec2/vpc_internet_gateway_test.go index 289f5159fdd..b24252e6355 100644 --- a/internal/service/ec2/vpc_internet_gateway_test.go +++ b/internal/service/ec2/vpc_internet_gateway_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -22,7 +22,7 @@ import ( func TestAccVPCInternetGateway_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.InternetGateway + var v awstypes.InternetGateway resourceName := "aws_internet_gateway.test" resource.ParallelTest(t, resource.TestCase{ @@ -52,7 +52,7 @@ func TestAccVPCInternetGateway_basic(t *testing.T) { func TestAccVPCInternetGateway_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.InternetGateway + var v awstypes.InternetGateway resourceName := "aws_internet_gateway.test" resource.ParallelTest(t, resource.TestCase{ @@ -75,7 +75,7 @@ func TestAccVPCInternetGateway_disappears(t *testing.T) { func TestAccVPCInternetGateway_Attachment(t *testing.T) { ctx := acctest.Context(t) - var v ec2.InternetGateway + var v awstypes.InternetGateway resourceName := "aws_internet_gateway.test" vpc1ResourceName := "aws_vpc.test1" vpc2ResourceName := "aws_vpc.test2" @@ -112,7 +112,7 @@ func TestAccVPCInternetGateway_Attachment(t *testing.T) { func TestAccVPCInternetGateway_Tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.InternetGateway + var v awstypes.InternetGateway resourceName := "aws_internet_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -158,7 +158,7 @@ func TestAccVPCInternetGateway_Tags(t *testing.T) { func testAccCheckInternetGatewayDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_internet_gateway" { @@ -182,7 +182,7 @@ func testAccCheckInternetGatewayDestroy(ctx context.Context) resource.TestCheckF } } -func testAccCheckInternetGatewayExists(ctx context.Context, n string, v *ec2.InternetGateway) resource.TestCheckFunc { +func testAccCheckInternetGatewayExists(ctx context.Context, n string, v *awstypes.InternetGateway) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -193,7 +193,7 @@ func testAccCheckInternetGatewayExists(ctx context.Context, n string, v *ec2.Int return fmt.Errorf("No EC2 Internet Gateway ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindInternetGatewayByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_ipv4_cidr_block_association.go b/internal/service/ec2/vpc_ipv4_cidr_block_association.go index ee9ae918709..926d797dca8 100644 --- a/internal/service/ec2/vpc_ipv4_cidr_block_association.go +++ b/internal/service/ec2/vpc_ipv4_cidr_block_association.go @@ -8,9 +8,9 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + "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/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -20,8 +20,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_ipv4_cidr_block_association") -func ResourceVPCIPv4CIDRBlockAssociation() *schema.Resource { +// @SDKResource("aws_vpc_ipv4_cidr_block_association", name="VPC IPV4 CIDR Block Association") +func resourceVPCIPv4CIDRBlockAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCIPv4CIDRBlockAssociationCreate, ReadWithoutTimeout: resourceVPCIPv4CIDRBlockAssociationRead, @@ -49,7 +49,7 @@ func ResourceVPCIPv4CIDRBlockAssociation() *schema.Resource { Optional: true, Computed: true, ForceNew: true, - ValidateFunc: validation.IsCIDRNetwork(VPCCIDRMinIPv4, VPCCIDRMaxIPv4), + ValidateFunc: validation.IsCIDRNetwork(vpcCIDRMinIPv4Netmask, vpcCIDRMaxIPv4Netmask), }, "ipv4_ipam_pool_id": { Type: schema.TypeString, @@ -60,7 +60,7 @@ func ResourceVPCIPv4CIDRBlockAssociation() *schema.Resource { Type: schema.TypeInt, Optional: true, ForceNew: true, - ValidateFunc: validation.IntBetween(VPCCIDRMinIPv4, VPCCIDRMaxIPv4), + ValidateFunc: validation.IntBetween(vpcCIDRMinIPv4Netmask, vpcCIDRMaxIPv4Netmask), }, names.AttrVPCID: { Type: schema.TypeString, @@ -78,7 +78,7 @@ func ResourceVPCIPv4CIDRBlockAssociation() *schema.Resource { func resourceVPCIPv4CIDRBlockAssociationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) vpcID := d.Get(names.AttrVPCID).(string) input := &ec2.AssociateVpcCidrBlockInput{ @@ -94,19 +94,19 @@ func resourceVPCIPv4CIDRBlockAssociationCreate(ctx context.Context, d *schema.Re } if v, ok := d.GetOk("ipv4_netmask_length"); ok { - input.Ipv4NetmaskLength = aws.Int64(int64(v.(int))) + input.Ipv4NetmaskLength = aws.Int32(int32(v.(int))) } - log.Printf("[DEBUG] Creating EC2 VPC IPv4 CIDR Block Association: %s", input) - output, err := conn.AssociateVpcCidrBlockWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 VPC IPv4 CIDR Block Association: %#v", input) + output, err := conn.AssociateVpcCidrBlock(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 VPC (%s) IPv4 CIDR Block Association: %s", vpcID, err) } - d.SetId(aws.StringValue(output.CidrBlockAssociation.AssociationId)) + d.SetId(aws.ToString(output.CidrBlockAssociation.AssociationId)) - _, err = WaitVPCCIDRBlockAssociationCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) + _, err = waitVPCCIDRBlockAssociationCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 VPC (%s) IPv4 CIDR block (%s) to become associated: %s", vpcID, d.Id(), err) @@ -117,9 +117,9 @@ func resourceVPCIPv4CIDRBlockAssociationCreate(ctx context.Context, d *schema.Re func resourceVPCIPv4CIDRBlockAssociationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcCidrBlockAssociation, vpc, err := FindVPCCIDRBlockAssociationByID(ctx, conn, d.Id()) + vpcCidrBlockAssociation, vpc, err := findVPCCIDRBlockAssociationByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VPC IPv4 CIDR Block Association %s not found, removing from state", d.Id()) @@ -139,10 +139,10 @@ func resourceVPCIPv4CIDRBlockAssociationRead(ctx context.Context, d *schema.Reso func resourceVPCIPv4CIDRBlockAssociationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[DEBUG] Deleting EC2 VPC IPv4 CIDR Block Association: %s", d.Id()) - _, err := conn.DisassociateVpcCidrBlockWithContext(ctx, &ec2.DisassociateVpcCidrBlockInput{ + _, err := conn.DisassociateVpcCidrBlock(ctx, &ec2.DisassociateVpcCidrBlockInput{ AssociationId: aws.String(d.Id()), }) @@ -154,7 +154,7 @@ func resourceVPCIPv4CIDRBlockAssociationDelete(ctx context.Context, d *schema.Re return sdkdiag.AppendErrorf(diags, "deleting EC2 VPC IPv4 CIDR Block Association (%s): %s", d.Id(), err) } - _, err = WaitVPCCIDRBlockAssociationDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)) + _, err = waitVPCCIDRBlockAssociationDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 VPC IPv4 CIDR block (%s) to become disassociated: %s", d.Id(), err) diff --git a/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go b/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go index d3db9144aa0..0db5d8b01ba 100644 --- a/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go +++ b/internal/service/ec2/vpc_ipv4_cidr_block_association_test.go @@ -9,8 +9,8 @@ import ( "strings" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -23,7 +23,7 @@ import ( func TestAccVPCIPv4CIDRBlockAssociation_basic(t *testing.T) { ctx := acctest.Context(t) - var associationSecondary, associationTertiary ec2.VpcCidrBlockAssociation + var associationSecondary, associationTertiary awstypes.VpcCidrBlockAssociation resource1Name := "aws_vpc_ipv4_cidr_block_association.secondary_cidr" resource2Name := "aws_vpc_ipv4_cidr_block_association.tertiary_cidr" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -59,7 +59,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_basic(t *testing.T) { func TestAccVPCIPv4CIDRBlockAssociation_disappears(t *testing.T) { ctx := acctest.Context(t) - var associationSecondary, associationTertiary ec2.VpcCidrBlockAssociation + var associationSecondary, associationTertiary awstypes.VpcCidrBlockAssociation resource1Name := "aws_vpc_ipv4_cidr_block_association.secondary_cidr" resource2Name := "aws_vpc_ipv4_cidr_block_association.tertiary_cidr" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -89,7 +89,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_ipamBasic(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var associationSecondary ec2.VpcCidrBlockAssociation + var associationSecondary awstypes.VpcCidrBlockAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource.ParallelTest(t, resource.TestCase{ @@ -115,7 +115,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_ipamBasicExplicitCIDR(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var associationSecondary ec2.VpcCidrBlockAssociation + var associationSecondary awstypes.VpcCidrBlockAssociation cidr := "172.2.0.32/28" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -135,7 +135,7 @@ func TestAccVPCIPv4CIDRBlockAssociation_ipamBasicExplicitCIDR(t *testing.T) { }) } -func testAccCheckAdditionalVPCIPv4CIDRBlock(association *ec2.VpcCidrBlockAssociation, expected string) resource.TestCheckFunc { +func testAccCheckAdditionalVPCIPv4CIDRBlock(association *awstypes.VpcCidrBlockAssociation, expected string) resource.TestCheckFunc { return func(s *terraform.State) error { CIDRBlock := association.CidrBlock if *CIDRBlock != expected { @@ -146,10 +146,10 @@ func testAccCheckAdditionalVPCIPv4CIDRBlock(association *ec2.VpcCidrBlockAssocia } } -func testAccCheckVPCAssociationCIDRPrefix(association *ec2.VpcCidrBlockAssociation, expected string) resource.TestCheckFunc { +func testAccCheckVPCAssociationCIDRPrefix(association *awstypes.VpcCidrBlockAssociation, expected string) resource.TestCheckFunc { return func(s *terraform.State) error { - if strings.Split(aws.StringValue(association.CidrBlock), "/")[1] != expected { - return fmt.Errorf("Bad cidr prefix: %s", aws.StringValue(association.CidrBlock)) + if strings.Split(aws.ToString(association.CidrBlock), "/")[1] != expected { + return fmt.Errorf("Bad cidr prefix: %s", aws.ToString(association.CidrBlock)) } return nil @@ -158,7 +158,7 @@ func testAccCheckVPCAssociationCIDRPrefix(association *ec2.VpcCidrBlockAssociati func testAccCheckVPCIPv4CIDRBlockAssociationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_ipv4_cidr_block_association" { @@ -182,7 +182,7 @@ func testAccCheckVPCIPv4CIDRBlockAssociationDestroy(ctx context.Context) resourc } } -func testAccCheckVPCIPv4CIDRBlockAssociationExists(ctx context.Context, n string, v *ec2.VpcCidrBlockAssociation) resource.TestCheckFunc { +func testAccCheckVPCIPv4CIDRBlockAssociationExists(ctx context.Context, n string, v *awstypes.VpcCidrBlockAssociation) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -193,7 +193,7 @@ func testAccCheckVPCIPv4CIDRBlockAssociationExists(ctx context.Context, n string return fmt.Errorf("No EC2 VPC IPv4 CIDR Block Association is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, _, err := tfec2.FindVPCCIDRBlockAssociationByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_ipv6_cidr_block_association.go b/internal/service/ec2/vpc_ipv6_cidr_block_association.go index db3c2c9fbfe..7cc20acee91 100644 --- a/internal/service/ec2/vpc_ipv6_cidr_block_association.go +++ b/internal/service/ec2/vpc_ipv6_cidr_block_association.go @@ -8,9 +8,9 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + "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/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -21,8 +21,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_ipv6_cidr_block_association") -func ResourceVPCIPv6CIDRBlockAssociation() *schema.Resource { +// @SDKResource("aws_vpc_ipv6_cidr_block_association", name="VPC IPV6 CIDR Block Association") +func resourceVPCIPv6CIDRBlockAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCIPv6CIDRBlockAssociationCreate, ReadWithoutTimeout: resourceVPCIPv6CIDRBlockAssociationRead, @@ -50,7 +50,7 @@ func ResourceVPCIPv6CIDRBlockAssociation() *schema.Resource { ForceNew: true, ValidateFunc: validation.All( verify.ValidIPv6CIDRNetworkAddress, - validation.IsCIDRNetwork(VPCCIDRMaxIPv6, VPCCIDRMaxIPv6)), + validation.IsCIDRNetwork(vpcCIDRMaxIPv6Netmask, vpcCIDRMaxIPv6Netmask)), }, // ipam parameters are not required by the API but other usage mechanisms are not implemented yet. TODO ipv6 options: // --amazon-provided-ipv6-cidr-block @@ -64,7 +64,7 @@ func ResourceVPCIPv6CIDRBlockAssociation() *schema.Resource { Type: schema.TypeInt, Optional: true, ForceNew: true, - ValidateFunc: validation.IntInSlice([]int{VPCCIDRMaxIPv6}), + ValidateFunc: validation.IntInSlice([]int{vpcCIDRMaxIPv6Netmask}), ConflictsWith: []string{"ipv6_cidr_block"}, // This RequiredWith setting should be applied once L57 is completed // RequiredWith: []string{"ipv6_ipam_pool_id"}, @@ -85,7 +85,7 @@ func ResourceVPCIPv6CIDRBlockAssociation() *schema.Resource { func resourceVPCIPv6CIDRBlockAssociationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) vpcID := d.Get(names.AttrVPCID).(string) input := &ec2.AssociateVpcCidrBlockInput{ @@ -101,19 +101,19 @@ func resourceVPCIPv6CIDRBlockAssociationCreate(ctx context.Context, d *schema.Re } if v, ok := d.GetOk("ipv6_netmask_length"); ok { - input.Ipv6NetmaskLength = aws.Int64(int64(v.(int))) + input.Ipv6NetmaskLength = aws.Int32(int32(v.(int))) } - log.Printf("[DEBUG] Creating EC2 VPC IPv6 CIDR Block Association: %s", input) - output, err := conn.AssociateVpcCidrBlockWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 VPC IPv6 CIDR Block Association: %#v", input) + output, err := conn.AssociateVpcCidrBlock(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 VPC (%s) IPv6 CIDR Block Association: %s", vpcID, err) } - d.SetId(aws.StringValue(output.Ipv6CidrBlockAssociation.AssociationId)) + d.SetId(aws.ToString(output.Ipv6CidrBlockAssociation.AssociationId)) - _, err = WaitVPCIPv6CIDRBlockAssociationCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) + _, err = waitVPCIPv6CIDRBlockAssociationCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 VPC (%s) IPv6 CIDR block (%s) to become associated: %s", vpcID, d.Id(), err) @@ -124,9 +124,9 @@ func resourceVPCIPv6CIDRBlockAssociationCreate(ctx context.Context, d *schema.Re func resourceVPCIPv6CIDRBlockAssociationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcIpv6CidrBlockAssociation, vpc, err := FindVPCIPv6CIDRBlockAssociationByID(ctx, conn, d.Id()) + vpcIpv6CidrBlockAssociation, vpc, err := findVPCIPv6CIDRBlockAssociationByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VPC IPv6 CIDR Block Association %s not found, removing from state", d.Id()) @@ -146,10 +146,10 @@ func resourceVPCIPv6CIDRBlockAssociationRead(ctx context.Context, d *schema.Reso func resourceVPCIPv6CIDRBlockAssociationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[DEBUG] Deleting VPC IPv6 CIDR Block Association: %s", d.Id()) - _, err := conn.DisassociateVpcCidrBlockWithContext(ctx, &ec2.DisassociateVpcCidrBlockInput{ + _, err := conn.DisassociateVpcCidrBlock(ctx, &ec2.DisassociateVpcCidrBlockInput{ AssociationId: aws.String(d.Id()), }) @@ -161,7 +161,7 @@ func resourceVPCIPv6CIDRBlockAssociationDelete(ctx context.Context, d *schema.Re return sdkdiag.AppendErrorf(diags, "deleting EC2 VPC IPv6 CIDR Block Association (%s): %s", d.Id(), err) } - _, err = WaitVPCIPv6CIDRBlockAssociationDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)) + err = waitVPCIPv6CIDRBlockAssociationDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 VPC IPv6 CIDR block (%s) to become disassociated: %s", d.Id(), err) diff --git a/internal/service/ec2/vpc_ipv6_cidr_block_association_test.go b/internal/service/ec2/vpc_ipv6_cidr_block_association_test.go index 68cb484f6d7..6cd2e6f7af3 100644 --- a/internal/service/ec2/vpc_ipv6_cidr_block_association_test.go +++ b/internal/service/ec2/vpc_ipv6_cidr_block_association_test.go @@ -20,7 +20,7 @@ import ( func testAccCheckVPCIPv6CIDRBlockAssociationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_ipv6_cidr_block_association" { @@ -57,7 +57,7 @@ func testAccCheckVPCIPv6CIDRBlockAssociationExists(ctx context.Context, n string conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, _, err := tfec2.FindVPCIPv6CIDRBlockAssociationByIDV2(ctx, conn, rs.Primary.ID) + output, _, err := tfec2.FindVPCIPv6CIDRBlockAssociationByID(ctx, conn, rs.Primary.ID) if err != nil { return err diff --git a/internal/service/ec2/vpc_managed_prefix_list.go b/internal/service/ec2/vpc_managed_prefix_list.go index 85131a2209e..81a93c049f6 100644 --- a/internal/service/ec2/vpc_managed_prefix_list.go +++ b/internal/service/ec2/vpc_managed_prefix_list.go @@ -8,8 +8,9 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/customdiff" @@ -27,7 +28,7 @@ import ( // @SDKResource("aws_ec2_managed_prefix_list", name="Managed Prefix List") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceManagedPrefixList() *schema.Resource { +func resourceManagedPrefixList() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceManagedPrefixListCreate, ReadWithoutTimeout: resourceManagedPrefixListRead, @@ -102,30 +103,30 @@ func ResourceManagedPrefixList() *schema.Resource { func resourceManagedPrefixListCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) name := d.Get(names.AttrName).(string) input := &ec2.CreateManagedPrefixListInput{ AddressFamily: aws.String(d.Get("address_family").(string)), ClientToken: aws.String(id.UniqueId()), - MaxEntries: aws.Int64(int64(d.Get("max_entries").(int))), + MaxEntries: aws.Int32(int32(d.Get("max_entries").(int))), PrefixListName: aws.String(name), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypePrefixList), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypePrefixList), } if v, ok := d.GetOk("entry"); ok && v.(*schema.Set).Len() > 0 { input.Entries = expandAddPrefixListEntries(v.(*schema.Set).List()) } - output, err := conn.CreateManagedPrefixListWithContext(ctx, input) + output, err := conn.CreateManagedPrefixList(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Managed Prefix List (%s): %s", name, err) } - d.SetId(aws.StringValue(output.PrefixList.PrefixListId)) + d.SetId(aws.ToString(output.PrefixList.PrefixListId)) - if _, err := WaitManagedPrefixListCreated(ctx, conn, d.Id()); err != nil { + if _, err := waitManagedPrefixListCreated(ctx, conn, d.Id()); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Managed Prefix List (%s) create: %s", d.Id(), err) } @@ -135,9 +136,9 @@ func resourceManagedPrefixListCreate(ctx context.Context, d *schema.ResourceData func resourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - pl, err := FindManagedPrefixListByID(ctx, conn, d.Id()) + pl, err := findManagedPrefixListByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 Managed Prefix List %s not found, removing from state", d.Id()) @@ -149,7 +150,7 @@ func resourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "reading EC2 Managed Prefix List (%s): %s", d.Id(), err) } - prefixListEntries, err := FindManagedPrefixListEntriesByID(ctx, conn, d.Id()) + prefixListEntries, err := findManagedPrefixListEntriesByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Managed Prefix List (%s) Entries: %s", d.Id(), err) @@ -173,17 +174,17 @@ func resourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData, func resourceManagedPrefixListUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) // MaxEntries & Entry cannot change in the same API call. // If MaxEntry is increasing, complete before updating entry(s) // If MaxEntry is decreasing, complete after updating entry(s) maxEntryChangedDecrease := false - var newMaxEntryInt int64 + var newMaxEntryInt int32 if d.HasChange("max_entries") { oldMaxEntry, newMaxEntry := d.GetChange("max_entries") - newMaxEntryInt = int64(d.Get("max_entries").(int)) + newMaxEntryInt = int32(d.Get("max_entries").(int)) if newMaxEntry.(int) < oldMaxEntry.(int) { maxEntryChangedDecrease = true @@ -228,14 +229,14 @@ func resourceManagedPrefixListUpdate(ctx context.Context, d *schema.ResourceData // one with a collection of all description-only removals and the // second one will add them all back. if len(input.AddEntries) > 0 && len(input.RemoveEntries) > 0 { - descriptionOnlyRemovals := []*ec2.RemovePrefixListEntry{} - removals := []*ec2.RemovePrefixListEntry{} + descriptionOnlyRemovals := []awstypes.RemovePrefixListEntry{} + removals := []awstypes.RemovePrefixListEntry{} for _, removeEntry := range input.RemoveEntries { inAddAndRemove := false for _, addEntry := range input.AddEntries { - if aws.StringValue(addEntry.Cidr) == aws.StringValue(removeEntry.Cidr) { + if aws.ToString(addEntry.Cidr) == aws.ToString(removeEntry.Cidr) { inAddAndRemove = true break } @@ -249,7 +250,7 @@ func resourceManagedPrefixListUpdate(ctx context.Context, d *schema.ResourceData } if len(descriptionOnlyRemovals) > 0 { - _, err := conn.ModifyManagedPrefixListWithContext(ctx, &ec2.ModifyManagedPrefixListInput{ + _, err := conn.ModifyManagedPrefixList(ctx, &ec2.ModifyManagedPrefixListInput{ CurrentVersion: input.CurrentVersion, PrefixListId: aws.String(d.Id()), RemoveEntries: descriptionOnlyRemovals, @@ -259,7 +260,7 @@ func resourceManagedPrefixListUpdate(ctx context.Context, d *schema.ResourceData return sdkdiag.AppendErrorf(diags, "updating EC2 Managed Prefix List (%s): %s", d.Id(), err) } - managedPrefixList, err := WaitManagedPrefixListModified(ctx, conn, d.Id()) + managedPrefixList, err := waitManagedPrefixListModified(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Managed Prefix List (%s) update: %s", d.Id(), err) @@ -277,14 +278,14 @@ func resourceManagedPrefixListUpdate(ctx context.Context, d *schema.ResourceData } } - _, err := conn.ModifyManagedPrefixListWithContext(ctx, input) + _, err := conn.ModifyManagedPrefixList(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "updating EC2 Managed Prefix List (%s): %s", d.Id(), err) } if wait { - if _, err := WaitManagedPrefixListModified(ctx, conn, d.Id()); err != nil { + if _, err := waitManagedPrefixListModified(ctx, conn, d.Id()); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Managed Prefix List (%s) update: %s", d.Id(), err) } } @@ -304,10 +305,10 @@ func resourceManagedPrefixListUpdate(ctx context.Context, d *schema.ResourceData func resourceManagedPrefixListDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting EC2 Managed Prefix List: %s", d.Id()) - _, err := conn.DeleteManagedPrefixListWithContext(ctx, &ec2.DeleteManagedPrefixListInput{ + _, err := conn.DeleteManagedPrefixList(ctx, &ec2.DeleteManagedPrefixListInput{ PrefixListId: aws.String(d.Id()), }) @@ -319,24 +320,24 @@ func resourceManagedPrefixListDelete(ctx context.Context, d *schema.ResourceData return sdkdiag.AppendErrorf(diags, "deleting EC2 Managed Prefix List (%s): %s", d.Id(), err) } - if _, err := WaitManagedPrefixListDeleted(ctx, conn, d.Id()); err != nil { + if _, err := waitManagedPrefixListDeleted(ctx, conn, d.Id()); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Managed Prefix List (%s) delete: %s", d.Id(), err) } return diags } -func updateMaxEntry(ctx context.Context, conn *ec2.EC2, id string, maxEntries int64) error { - _, err := conn.ModifyManagedPrefixListWithContext(ctx, &ec2.ModifyManagedPrefixListInput{ +func updateMaxEntry(ctx context.Context, conn *ec2.Client, id string, maxEntries int32) error { + _, err := conn.ModifyManagedPrefixList(ctx, &ec2.ModifyManagedPrefixListInput{ PrefixListId: aws.String(id), - MaxEntries: aws.Int64(maxEntries), + MaxEntries: aws.Int32(maxEntries), }) if err != nil { return fmt.Errorf("updating MaxEntries for EC2 Managed Prefix List (%s): %s", id, err) } - _, err = WaitManagedPrefixListModified(ctx, conn, id) + _, err = waitManagedPrefixListModified(ctx, conn, id) if err != nil { return fmt.Errorf("waiting for EC2 Managed Prefix List (%s) MaxEntries update: %s", id, err) @@ -345,12 +346,8 @@ func updateMaxEntry(ctx context.Context, conn *ec2.EC2, id string, maxEntries in return nil } -func expandAddPrefixListEntry(tfMap map[string]interface{}) *ec2.AddPrefixListEntry { - if tfMap == nil { - return nil - } - - apiObject := &ec2.AddPrefixListEntry{} +func expandAddPrefixListEntry(tfMap map[string]interface{}) awstypes.AddPrefixListEntry { + apiObject := awstypes.AddPrefixListEntry{} if v, ok := tfMap["cidr"].(string); ok && v != "" { apiObject.Cidr = aws.String(v) @@ -363,12 +360,12 @@ func expandAddPrefixListEntry(tfMap map[string]interface{}) *ec2.AddPrefixListEn return apiObject } -func expandAddPrefixListEntries(tfList []interface{}) []*ec2.AddPrefixListEntry { +func expandAddPrefixListEntries(tfList []interface{}) []awstypes.AddPrefixListEntry { if len(tfList) == 0 { return nil } - var apiObjects []*ec2.AddPrefixListEntry + var apiObjects []awstypes.AddPrefixListEntry for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -377,24 +374,14 @@ func expandAddPrefixListEntries(tfList []interface{}) []*ec2.AddPrefixListEntry continue } - apiObject := expandAddPrefixListEntry(tfMap) - - if apiObject == nil { - continue - } - - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, expandAddPrefixListEntry(tfMap)) } return apiObjects } -func expandRemovePrefixListEntry(tfMap map[string]interface{}) *ec2.RemovePrefixListEntry { - if tfMap == nil { - return nil - } - - apiObject := &ec2.RemovePrefixListEntry{} +func expandRemovePrefixListEntry(tfMap map[string]interface{}) awstypes.RemovePrefixListEntry { + apiObject := awstypes.RemovePrefixListEntry{} if v, ok := tfMap["cidr"].(string); ok && v != "" { apiObject.Cidr = aws.String(v) @@ -403,12 +390,12 @@ func expandRemovePrefixListEntry(tfMap map[string]interface{}) *ec2.RemovePrefix return apiObject } -func expandRemovePrefixListEntries(tfList []interface{}) []*ec2.RemovePrefixListEntry { +func expandRemovePrefixListEntries(tfList []interface{}) []awstypes.RemovePrefixListEntry { if len(tfList) == 0 { return nil } - var apiObjects []*ec2.RemovePrefixListEntry + var apiObjects []awstypes.RemovePrefixListEntry for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -417,37 +404,27 @@ func expandRemovePrefixListEntries(tfList []interface{}) []*ec2.RemovePrefixList continue } - apiObject := expandRemovePrefixListEntry(tfMap) - - if apiObject == nil { - continue - } - - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, expandRemovePrefixListEntry(tfMap)) } return apiObjects } -func flattenPrefixListEntry(apiObject *ec2.PrefixListEntry) map[string]interface{} { - if apiObject == nil { - return nil - } - +func flattenPrefixListEntry(apiObject awstypes.PrefixListEntry) map[string]interface{} { tfMap := map[string]interface{}{} if v := apiObject.Cidr; v != nil { - tfMap["cidr"] = aws.StringValue(v) + tfMap["cidr"] = aws.ToString(v) } if v := apiObject.Description; v != nil { - tfMap[names.AttrDescription] = aws.StringValue(v) + tfMap[names.AttrDescription] = aws.ToString(v) } return tfMap } -func flattenPrefixListEntries(apiObjects []*ec2.PrefixListEntry) []interface{} { +func flattenPrefixListEntries(apiObjects []awstypes.PrefixListEntry) []interface{} { if len(apiObjects) == 0 { return nil } @@ -455,10 +432,6 @@ func flattenPrefixListEntries(apiObjects []*ec2.PrefixListEntry) []interface{} { var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenPrefixListEntry(apiObject)) } diff --git a/internal/service/ec2/vpc_managed_prefix_list_data_source.go b/internal/service/ec2/vpc_managed_prefix_list_data_source.go index 326b973d076..8307d8e1eaf 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_data_source.go +++ b/internal/service/ec2/vpc_managed_prefix_list_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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,8 +18,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_ec2_managed_prefix_list") -func DataSourceManagedPrefixList() *schema.Resource { +// @SDKDataSource("aws_ec2_managed_prefix_list", name="Managed Prefix List") +func dataSourceManagedPrefixList() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceManagedPrefixListRead, @@ -83,7 +83,7 @@ func DataSourceManagedPrefixList() *schema.Resource { func dataSourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &ec2.DescribeManagedPrefixListsInput{ @@ -93,7 +93,7 @@ func dataSourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData } if v, ok := d.GetOk(names.AttrID); ok { - input.PrefixListIds = aws.StringSlice([]string{v.(string)}) + input.PrefixListIds = []string{v.(string)} } input.Filters = append(input.Filters, newCustomFilterList( @@ -105,15 +105,15 @@ func dataSourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData input.Filters = nil } - pl, err := FindManagedPrefixList(ctx, conn, input) + pl, err := findManagedPrefixList(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 Managed Prefix List", err)) } - d.SetId(aws.StringValue(pl.PrefixListId)) + d.SetId(aws.ToString(pl.PrefixListId)) - prefixListEntries, err := FindManagedPrefixListEntriesByID(ctx, conn, d.Id()) + prefixListEntries, err := findManagedPrefixListEntriesByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Managed Prefix List (%s) Entries: %s", d.Id(), err) @@ -129,7 +129,7 @@ func dataSourceManagedPrefixListRead(ctx context.Context, d *schema.ResourceData d.Set(names.AttrOwnerID, pl.OwnerId) d.Set(names.AttrVersion, pl.Version) - if err := d.Set(names.AttrTags, KeyValueTags(ctx, pl.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, pl.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go b/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go index 2eb49f09c38..2c6a551ea24 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go +++ b/internal/service/ec2/vpc_managed_prefix_list_data_source_test.go @@ -9,8 +9,9 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" @@ -20,13 +21,13 @@ import ( func testAccManagedPrefixListGetIdByNameDataSource(ctx context.Context, name string, id *string, arn *string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := conn.DescribeManagedPrefixListsWithContext(ctx, &ec2.DescribeManagedPrefixListsInput{ - Filters: []*ec2.Filter{ + output, err := conn.DescribeManagedPrefixLists(ctx, &ec2.DescribeManagedPrefixListsInput{ + Filters: []awstypes.Filter{ { Name: aws.String("prefix-list-name"), - Values: aws.StringSlice([]string{name}), + Values: []string{name}, }, }, }) diff --git a/internal/service/ec2/vpc_managed_prefix_list_entry.go b/internal/service/ec2/vpc_managed_prefix_list_entry.go index 1de77232636..0fdb787c0f4 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_entry.go +++ b/internal/service/ec2/vpc_managed_prefix_list_entry.go @@ -9,8 +9,10 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" @@ -20,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_ec2_managed_prefix_list_entry") -func ResourceManagedPrefixListEntry() *schema.Resource { +// @SDKResource("aws_ec2_managed_prefix_list_entry", name="Managed Prefix List Entry") +func resourceManagedPrefixListEntry() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceManagedPrefixListEntryCreate, @@ -57,13 +59,13 @@ func ResourceManagedPrefixListEntry() *schema.Resource { func resourceManagedPrefixListEntryCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) cidr := d.Get("cidr").(string) plID := d.Get("prefix_list_id").(string) - id := ManagedPrefixListEntryCreateResourceID(plID, cidr) + id := managedPrefixListEntryCreateResourceID(plID, cidr) - addPrefixListEntry := &ec2.AddPrefixListEntry{Cidr: aws.String(cidr)} + addPrefixListEntry := awstypes.AddPrefixListEntry{Cidr: aws.String(cidr)} if v, ok := d.GetOk(names.AttrDescription); ok { addPrefixListEntry.Description = aws.String(v.(string)) @@ -74,19 +76,19 @@ func resourceManagedPrefixListEntryCreate(ctx context.Context, d *schema.Resourc conns.GlobalMutexKV.Lock(mutexKey) defer conns.GlobalMutexKV.Unlock(mutexKey) - pl, err := FindManagedPrefixListByID(ctx, conn, plID) + pl, err := findManagedPrefixListByID(ctx, conn, plID) if err != nil { return nil, fmt.Errorf("reading VPC Managed Prefix List (%s): %w", plID, err) } input := &ec2.ModifyManagedPrefixListInput{ - AddEntries: []*ec2.AddPrefixListEntry{addPrefixListEntry}, + AddEntries: []awstypes.AddPrefixListEntry{addPrefixListEntry}, CurrentVersion: pl.Version, PrefixListId: aws.String(plID), } - return conn.ModifyManagedPrefixListWithContext(ctx, input) + return conn.ModifyManagedPrefixList(ctx, input) }, errCodeIncorrectState, errCodePrefixListVersionMismatch) if err != nil { @@ -95,7 +97,7 @@ func resourceManagedPrefixListEntryCreate(ctx context.Context, d *schema.Resourc d.SetId(id) - if _, err := WaitManagedPrefixListModified(ctx, conn, plID); err != nil { + if _, err := waitManagedPrefixListModified(ctx, conn, plID); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for VPC Managed Prefix List Entry (%s) create: %s", d.Id(), err) } @@ -105,16 +107,16 @@ func resourceManagedPrefixListEntryCreate(ctx context.Context, d *schema.Resourc func resourceManagedPrefixListEntryRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - plID, cidr, err := ManagedPrefixListEntryParseResourceID(d.Id()) + plID, cidr, err := managedPrefixListEntryParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } - outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ManagedPrefixListEntryCreateTimeout, func() (interface{}, error) { - return FindManagedPrefixListEntryByIDAndCIDR(ctx, conn, plID, cidr) + outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, managedPrefixListEntryCreateTimeout, func() (interface{}, error) { + return findManagedPrefixListEntryByIDAndCIDR(ctx, conn, plID, cidr) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -127,7 +129,7 @@ func resourceManagedPrefixListEntryRead(ctx context.Context, d *schema.ResourceD return sdkdiag.AppendErrorf(diags, "reading VPC Managed Prefix List Entry (%s): %s", d.Id(), err) } - entry := outputRaw.(*ec2.PrefixListEntry) + entry := outputRaw.(*awstypes.PrefixListEntry) d.Set("cidr", entry.Cidr) d.Set(names.AttrDescription, entry.Description) @@ -138,9 +140,9 @@ func resourceManagedPrefixListEntryRead(ctx context.Context, d *schema.ResourceD func resourceManagedPrefixListEntryDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - plID, cidr, err := ManagedPrefixListEntryParseResourceID(d.Id()) + plID, cidr, err := managedPrefixListEntryParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) @@ -151,7 +153,7 @@ func resourceManagedPrefixListEntryDelete(ctx context.Context, d *schema.Resourc conns.GlobalMutexKV.Lock(mutexKey) defer conns.GlobalMutexKV.Unlock(mutexKey) - pl, err := FindManagedPrefixListByID(ctx, conn, plID) + pl, err := findManagedPrefixListByID(ctx, conn, plID) if err != nil { return nil, fmt.Errorf("reading VPC Managed Prefix List (%s): %w", plID, err) @@ -160,17 +162,21 @@ func resourceManagedPrefixListEntryDelete(ctx context.Context, d *schema.Resourc input := &ec2.ModifyManagedPrefixListInput{ CurrentVersion: pl.Version, PrefixListId: aws.String(plID), - RemoveEntries: []*ec2.RemovePrefixListEntry{{Cidr: aws.String(cidr)}}, + RemoveEntries: []awstypes.RemovePrefixListEntry{{Cidr: aws.String(cidr)}}, } - return conn.ModifyManagedPrefixListWithContext(ctx, input) + return conn.ModifyManagedPrefixList(ctx, input) }, errCodeIncorrectState, errCodePrefixListVersionMismatch) + if tfawserr.ErrMessageContains(err, errCodeInvalidPrefixListModification, "does not exist.") { + return diags + } + if err != nil { return sdkdiag.AppendErrorf(diags, "deleting VPC Managed Prefix List Entry (%s): %s", d.Id(), err) } - _, err = WaitManagedPrefixListModified(ctx, conn, plID) + _, err = waitManagedPrefixListModified(ctx, conn, plID) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for VPC Managed Prefix List Entry (%s) delete: %s", d.Id(), err) @@ -180,7 +186,7 @@ func resourceManagedPrefixListEntryDelete(ctx context.Context, d *schema.Resourc } func resourceManagedPrefixListEntryImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - plID, cidr, err := ManagedPrefixListEntryParseResourceID(d.Id()) + plID, cidr, err := managedPrefixListEntryParseResourceID(d.Id()) if err != nil { return nil, err @@ -194,14 +200,14 @@ func resourceManagedPrefixListEntryImport(ctx context.Context, d *schema.Resourc const managedPrefixListEntryIDSeparator = "," -func ManagedPrefixListEntryCreateResourceID(prefixListID, cidrBlock string) string { +func managedPrefixListEntryCreateResourceID(prefixListID, cidrBlock string) string { parts := []string{prefixListID, cidrBlock} id := strings.Join(parts, managedPrefixListEntryIDSeparator) return id } -func ManagedPrefixListEntryParseResourceID(id string) (string, string, error) { +func managedPrefixListEntryParseResourceID(id string) (string, string, error) { parts := strings.Split(id, managedPrefixListEntryIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/vpc_managed_prefix_list_entry_test.go b/internal/service/ec2/vpc_managed_prefix_list_entry_test.go index e5c8fd3b301..3670773639d 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_entry_test.go +++ b/internal/service/ec2/vpc_managed_prefix_list_entry_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -22,7 +22,7 @@ import ( func TestAccVPCManagedPrefixListEntry_ipv4(t *testing.T) { ctx := acctest.Context(t) - var entry ec2.PrefixListEntry + var entry awstypes.PrefixListEntry resourceName := "aws_ec2_managed_prefix_list_entry.test" plResourceName := "aws_ec2_managed_prefix_list.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -54,7 +54,7 @@ func TestAccVPCManagedPrefixListEntry_ipv4(t *testing.T) { func TestAccVPCManagedPrefixListEntry_ipv4Multiple(t *testing.T) { ctx := acctest.Context(t) - var entry ec2.PrefixListEntry + var entry awstypes.PrefixListEntry resourceName1 := "aws_ec2_managed_prefix_list_entry.test1" resourceName2 := "aws_ec2_managed_prefix_list_entry.test2" resourceName3 := "aws_ec2_managed_prefix_list_entry.test3" @@ -83,7 +83,7 @@ func TestAccVPCManagedPrefixListEntry_ipv4Multiple(t *testing.T) { func TestAccVPCManagedPrefixListEntry_ipv6(t *testing.T) { ctx := acctest.Context(t) - var entry ec2.PrefixListEntry + var entry awstypes.PrefixListEntry resourceName := "aws_ec2_managed_prefix_list_entry.test" plResourceName := "aws_ec2_managed_prefix_list.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -155,7 +155,7 @@ func TestAccVPCManagedPrefixListEntry_expectInvalidCIDR(t *testing.T) { func TestAccVPCManagedPrefixListEntry_description(t *testing.T) { ctx := acctest.Context(t) - var entry ec2.PrefixListEntry + var entry awstypes.PrefixListEntry resourceName := "aws_ec2_managed_prefix_list_entry.test" plResourceName := "aws_ec2_managed_prefix_list.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -187,7 +187,7 @@ func TestAccVPCManagedPrefixListEntry_description(t *testing.T) { func TestAccVPCManagedPrefixListEntry_disappears(t *testing.T) { ctx := acctest.Context(t) - var entry ec2.PrefixListEntry + var entry awstypes.PrefixListEntry resourceName := "aws_ec2_managed_prefix_list_entry.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -211,7 +211,7 @@ func TestAccVPCManagedPrefixListEntry_disappears(t *testing.T) { func testAccCheckManagedPrefixListEntryDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_ec2_managed_prefix_list_entry" { @@ -241,7 +241,7 @@ func testAccCheckManagedPrefixListEntryDestroy(ctx context.Context) resource.Tes } } -func testAccCheckManagedPrefixListEntryExists(ctx context.Context, n string, v *ec2.PrefixListEntry) resource.TestCheckFunc { +func testAccCheckManagedPrefixListEntryExists(ctx context.Context, n string, v *awstypes.PrefixListEntry) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -252,7 +252,7 @@ func testAccCheckManagedPrefixListEntryExists(ctx context.Context, n string, v * return fmt.Errorf("No EC2 Managed Prefix List Entry ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) plID, cidr, err := tfec2.ManagedPrefixListEntryParseResourceID(rs.Primary.ID) diff --git a/internal/service/ec2/vpc_managed_prefix_list_test.go b/internal/service/ec2/vpc_managed_prefix_list_test.go index 85a9ab06e58..c89c07e42a1 100644 --- a/internal/service/ec2/vpc_managed_prefix_list_test.go +++ b/internal/service/ec2/vpc_managed_prefix_list_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -360,7 +360,7 @@ func TestAccVPCManagedPrefixList_tags(t *testing.T) { func testAccCheckManagedPrefixListDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_ec2_managed_prefix_list" { @@ -395,7 +395,7 @@ func testAccManagedPrefixListExists(ctx context.Context, resourceName string) re return fmt.Errorf("No EC2 Managed Prefix List ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) _, err := tfec2.FindManagedPrefixListByID(ctx, conn, rs.Primary.ID) @@ -404,11 +404,11 @@ func testAccManagedPrefixListExists(ctx context.Context, resourceName string) re } func testAccPreCheckManagedPrefixList(ctx context.Context, t *testing.T) { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeManagedPrefixListsInput{} - _, err := conn.DescribeManagedPrefixListsWithContext(ctx, input) + _, err := conn.DescribeManagedPrefixLists(ctx, input) if acctest.PreCheckSkipError(err) { t.Skipf("skipping acceptance testing: %s", err) diff --git a/internal/service/ec2/vpc_managed_prefix_lists_data_source.go b/internal/service/ec2/vpc_managed_prefix_lists_data_source.go index 5d8445a2d35..17bf480291c 100644 --- a/internal/service/ec2/vpc_managed_prefix_lists_data_source.go +++ b/internal/service/ec2/vpc_managed_prefix_lists_data_source.go @@ -6,8 +6,8 @@ package ec2 import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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" @@ -16,8 +16,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_ec2_managed_prefix_lists") -func DataSourceManagedPrefixLists() *schema.Resource { +// @SDKDataSource("aws_ec2_managed_prefix_lists", name="Managed Prefix Lists") +func dataSourceManagedPrefixLists() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceManagedPrefixListsRead, @@ -36,7 +36,7 @@ func DataSourceManagedPrefixLists() *schema.Resource { func dataSourceManagedPrefixListsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeManagedPrefixListsInput{} @@ -53,7 +53,7 @@ func dataSourceManagedPrefixListsRead(ctx context.Context, d *schema.ResourceDat input.Filters = nil } - prefixLists, err := FindManagedPrefixLists(ctx, conn, input) + prefixLists, err := findManagedPrefixLists(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Managed Prefix Lists: %s", err) @@ -62,7 +62,7 @@ func dataSourceManagedPrefixListsRead(ctx context.Context, d *schema.ResourceDat var prefixListIDs []string for _, v := range prefixLists { - prefixListIDs = append(prefixListIDs, aws.StringValue(v.PrefixListId)) + prefixListIDs = append(prefixListIDs, aws.ToString(v.PrefixListId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_migrate.go b/internal/service/ec2/vpc_migrate.go index 6ce1ced9176..371f190e74f 100644 --- a/internal/service/ec2/vpc_migrate.go +++ b/internal/service/ec2/vpc_migrate.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func VPCMigrateState( +func vpcMigrateState( v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: diff --git a/internal/service/ec2/vpc_nat_gateway.go b/internal/service/ec2/vpc_nat_gateway.go index 71476cb8c77..26efc388af2 100644 --- a/internal/service/ec2/vpc_nat_gateway.go +++ b/internal/service/ec2/vpc_nat_gateway.go @@ -10,15 +10,17 @@ import ( "slices" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/customdiff" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/flex" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -30,7 +32,7 @@ import ( // @SDKResource("aws_nat_gateway", name="NAT Gateway") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceNATGateway() *schema.Resource { +func resourceNATGateway() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceNATGatewayCreate, ReadWithoutTimeout: resourceNATGatewayRead, @@ -58,11 +60,11 @@ func ResourceNATGateway() *schema.Resource { Computed: true, }, "connectivity_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Default: ec2.ConnectivityTypePublic, - ValidateFunc: validation.StringInSlice(ec2.ConnectivityType_Values(), false), + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: awstypes.ConnectivityTypePublic, + ValidateDiagFunc: enum.Validate[awstypes.ConnectivityType](), }, names.AttrNetworkInterfaceID: { Type: schema.TypeString, @@ -117,11 +119,11 @@ func ResourceNATGateway() *schema.Resource { func resourceNATGatewayCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateNatGatewayInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeNatgateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeNatgateway), } if v, ok := d.GetOk("allocation_id"); ok { @@ -129,7 +131,7 @@ func resourceNATGatewayCreate(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("connectivity_type"); ok { - input.ConnectivityType = aws.String(v.(string)) + input.ConnectivityType = awstypes.ConnectivityType(v.(string)) } if v, ok := d.GetOk("private_ip"); ok { @@ -137,30 +139,30 @@ func resourceNATGatewayCreate(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk("secondary_allocation_ids"); ok && v.(*schema.Set).Len() > 0 { - input.SecondaryAllocationIds = flex.ExpandStringSet(v.(*schema.Set)) + input.SecondaryAllocationIds = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk("secondary_private_ip_address_count"); ok { - input.SecondaryPrivateIpAddressCount = aws.Int64(int64(v.(int))) + input.SecondaryPrivateIpAddressCount = aws.Int32(int32(v.(int))) } if v, ok := d.GetOk("secondary_private_ip_addresses"); ok && v.(*schema.Set).Len() > 0 { - input.SecondaryPrivateIpAddresses = flex.ExpandStringSet(v.(*schema.Set)) + input.SecondaryPrivateIpAddresses = flex.ExpandStringValueSet(v.(*schema.Set)) } if v, ok := d.GetOk(names.AttrSubnetID); ok { input.SubnetId = aws.String(v.(string)) } - output, err := conn.CreateNatGatewayWithContext(ctx, input) + output, err := conn.CreateNatGateway(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 NAT Gateway: %s", err) } - d.SetId(aws.StringValue(output.NatGateway.NatGatewayId)) + d.SetId(aws.ToString(output.NatGateway.NatGatewayId)) - if _, err := WaitNATGatewayCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + if _, err := waitNATGatewayCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 NAT Gateway (%s) create: %s", d.Id(), err) } @@ -170,9 +172,9 @@ func resourceNATGatewayCreate(ctx context.Context, d *schema.ResourceData, meta func resourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - ng, err := FindNATGatewayByID(ctx, conn, d.Id()) + ng, err := findNATGatewayByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 NAT Gateway (%s) not found, removing from state", d.Id()) @@ -188,17 +190,17 @@ func resourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta in for _, address := range ng.NatGatewayAddresses { // Length check guarantees the attributes are always set (#30865). - if isPrimary := aws.BoolValue(address.IsPrimary); isPrimary || len(ng.NatGatewayAddresses) == 1 { + if isPrimary := aws.ToBool(address.IsPrimary); isPrimary || len(ng.NatGatewayAddresses) == 1 { d.Set("allocation_id", address.AllocationId) d.Set(names.AttrAssociationID, address.AssociationId) d.Set(names.AttrNetworkInterfaceID, address.NetworkInterfaceId) d.Set("private_ip", address.PrivateIp) d.Set("public_ip", address.PublicIp) } else if !isPrimary { - if allocationID := aws.StringValue(address.AllocationId); allocationID != "" { + if allocationID := aws.ToString(address.AllocationId); allocationID != "" { secondaryAllocationIDs = append(secondaryAllocationIDs, allocationID) } - if privateIP := aws.StringValue(address.PrivateIp); privateIP != "" { + if privateIP := aws.ToString(address.PrivateIp); privateIP != "" { secondaryPrivateIPAddresses = append(secondaryPrivateIPAddresses, privateIP) } } @@ -218,10 +220,10 @@ func resourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta in func resourceNATGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) switch d.Get("connectivity_type").(string) { - case ec2.ConnectivityTypePrivate: + case string(awstypes.ConnectivityTypePrivate): if d.HasChanges("secondary_private_ip_addresses") { oRaw, nRaw := d.GetChange("secondary_private_ip_addresses") o, n := oRaw.(*schema.Set), nRaw.(*schema.Set) @@ -229,17 +231,17 @@ func resourceNATGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta if add := n.Difference(o); add.Len() > 0 { input := &ec2.AssignPrivateNatGatewayAddressInput{ NatGatewayId: aws.String(d.Id()), - PrivateIpAddresses: flex.ExpandStringSet(add), + PrivateIpAddresses: flex.ExpandStringValueSet(add), } - _, err := conn.AssignPrivateNatGatewayAddressWithContext(ctx, input) + _, err := conn.AssignPrivateNatGatewayAddress(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "assigning EC2 NAT Gateway (%s) private IP addresses: %s", d.Id(), err) } for _, privateIP := range flex.ExpandStringValueSet(add) { - if _, err := WaitNATGatewayAddressAssigned(ctx, conn, d.Id(), privateIP, d.Timeout(schema.TimeoutUpdate)); err != nil { + if _, err := waitNATGatewayAddressAssigned(ctx, conn, d.Id(), privateIP, d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 NAT Gateway (%s) private IP address (%s) assign: %s", d.Id(), privateIP, err) } } @@ -248,31 +250,31 @@ func resourceNATGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta if del := o.Difference(n); del.Len() > 0 { input := &ec2.UnassignPrivateNatGatewayAddressInput{ NatGatewayId: aws.String(d.Id()), - PrivateIpAddresses: flex.ExpandStringSet(del), + PrivateIpAddresses: flex.ExpandStringValueSet(del), } - _, err := conn.UnassignPrivateNatGatewayAddressWithContext(ctx, input) + _, err := conn.UnassignPrivateNatGatewayAddress(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "unassigning EC2 NAT Gateway (%s) private IP addresses: %s", d.Id(), err) } for _, privateIP := range flex.ExpandStringValueSet(del) { - if _, err := WaitNATGatewayAddressUnassigned(ctx, conn, d.Id(), privateIP, d.Timeout(schema.TimeoutUpdate)); err != nil { + if _, err := waitNATGatewayAddressUnassigned(ctx, conn, d.Id(), privateIP, d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 NAT Gateway (%s) private IP address (%s) unassign: %s", d.Id(), privateIP, err) } } } } - case ec2.ConnectivityTypePublic: + case string(awstypes.ConnectivityTypePublic): if d.HasChanges("secondary_allocation_ids") { oRaw, nRaw := d.GetChange("secondary_allocation_ids") o, n := oRaw.(*schema.Set), nRaw.(*schema.Set) if add := n.Difference(o); add.Len() > 0 { input := &ec2.AssociateNatGatewayAddressInput{ - AllocationIds: flex.ExpandStringSet(add), + AllocationIds: flex.ExpandStringValueSet(add), NatGatewayId: aws.String(d.Id()), } @@ -281,25 +283,25 @@ func resourceNATGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta o, n := oRaw.(*schema.Set), nRaw.(*schema.Set) if add := n.Difference(o); add.Len() > 0 { - input.PrivateIpAddresses = flex.ExpandStringSet(add) + input.PrivateIpAddresses = flex.ExpandStringValueSet(add) } } - _, err := conn.AssociateNatGatewayAddressWithContext(ctx, input) + _, err := conn.AssociateNatGatewayAddress(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "associating EC2 NAT Gateway (%s) allocation IDs: %s", d.Id(), err) } for _, allocationID := range flex.ExpandStringValueSet(add) { - if _, err := WaitNATGatewayAddressAssociated(ctx, conn, d.Id(), allocationID, d.Timeout(schema.TimeoutUpdate)); err != nil { + if _, err := waitNATGatewayAddressAssociated(ctx, conn, d.Id(), allocationID, d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 NAT Gateway (%s) allocation ID (%s) associate: %s", d.Id(), allocationID, err) } } } if del := o.Difference(n); del.Len() > 0 { - natGateway, err := FindNATGatewayByID(ctx, conn, d.Id()) + natGateway, err := findNATGatewayByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 NAT Gateway (%s): %s", d.Id(), err) @@ -309,25 +311,25 @@ func resourceNATGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta var associationIDs []string for _, natGatewayAddress := range natGateway.NatGatewayAddresses { - allocationID := aws.StringValue(natGatewayAddress.AllocationId) + allocationID := aws.ToString(natGatewayAddress.AllocationId) if slices.Contains(allocationIDs, allocationID) { - associationIDs = append(associationIDs, aws.StringValue(natGatewayAddress.AssociationId)) + associationIDs = append(associationIDs, aws.ToString(natGatewayAddress.AssociationId)) } } input := &ec2.DisassociateNatGatewayAddressInput{ - AssociationIds: aws.StringSlice(associationIDs), + AssociationIds: associationIDs, NatGatewayId: aws.String(d.Id()), } - _, err = conn.DisassociateNatGatewayAddressWithContext(ctx, input) + _, err = conn.DisassociateNatGatewayAddress(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "disassociating EC2 NAT Gateway (%s) allocation IDs: %s", d.Id(), err) } for _, allocationID := range allocationIDs { - if _, err := WaitNATGatewayAddressDisassociated(ctx, conn, d.Id(), allocationID, d.Timeout(schema.TimeoutUpdate)); err != nil { + if _, err := waitNATGatewayAddressDisassociated(ctx, conn, d.Id(), allocationID, d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 NAT Gateway (%s) allocation ID (%s) disassociate: %s", d.Id(), allocationID, err) } } @@ -341,10 +343,10 @@ func resourceNATGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceNATGatewayDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting EC2 NAT Gateway: %s", d.Id()) - _, err := conn.DeleteNatGatewayWithContext(ctx, &ec2.DeleteNatGatewayInput{ + _, err := conn.DeleteNatGateway(ctx, &ec2.DeleteNatGatewayInput{ NatGatewayId: aws.String(d.Id()), }) @@ -356,7 +358,7 @@ func resourceNATGatewayDelete(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "deleting EC2 NAT Gateway (%s): %s", d.Id(), err) } - if _, err := WaitNATGatewayDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + if _, err := waitNATGatewayDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 NAT Gateway (%s) delete: %s", d.Id(), err) } @@ -365,7 +367,7 @@ func resourceNATGatewayDelete(ctx context.Context, d *schema.ResourceData, meta func resourceNATGatewayCustomizeDiff(ctx context.Context, diff *schema.ResourceDiff, meta interface{}) error { switch connectivityType := diff.Get("connectivity_type").(string); connectivityType { - case ec2.ConnectivityTypePrivate: + case string(awstypes.ConnectivityTypePrivate): if _, ok := diff.GetOk("allocation_id"); ok { return fmt.Errorf(`allocation_id is not supported with connectivity_type = "%s"`, connectivityType) } @@ -373,7 +375,7 @@ func resourceNATGatewayCustomizeDiff(ctx context.Context, diff *schema.ResourceD return fmt.Errorf(`secondary_allocation_ids is not supported with connectivity_type = "%s"`, connectivityType) } - case ec2.ConnectivityTypePublic: + case string(awstypes.ConnectivityTypePublic): if v := diff.GetRawConfig().GetAttr("secondary_private_ip_address_count"); v.IsKnown() && !v.IsNull() { return fmt.Errorf(`secondary_private_ip_address_count is not supported with connectivity_type = "%s"`, connectivityType) } diff --git a/internal/service/ec2/vpc_nat_gateway_data_source.go b/internal/service/ec2/vpc_nat_gateway_data_source.go index 1950f82f483..9a13d56312a 100644 --- a/internal/service/ec2/vpc_nat_gateway_data_source.go +++ b/internal/service/ec2/vpc_nat_gateway_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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,8 +18,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_nat_gateway") -func DataSourceNATGateway() *schema.Resource { +// @SDKDataSource("aws_nat_gateway", name="NAT Gateway") +func dataSourceNATGateway() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceNATGatewayRead, @@ -93,7 +93,7 @@ func DataSourceNATGateway() *schema.Resource { } func dataSourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) var diags diag.Diagnostics ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig @@ -109,7 +109,7 @@ func dataSourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta } if v, ok := d.GetOk(names.AttrID); ok { - input.NatGatewayIds = aws.StringSlice([]string{v.(string)}) + input.NatGatewayIds = []string{v.(string)} } if tags, ok := d.GetOk(names.AttrTags); ok { @@ -126,13 +126,13 @@ func dataSourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta input.Filter = nil } - ngw, err := FindNATGateway(ctx, conn, input) + ngw, err := findNATGateway(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 NAT Gateway", err)) } - d.SetId(aws.StringValue(ngw.NatGatewayId)) + d.SetId(aws.ToString(ngw.NatGatewayId)) d.Set("connectivity_type", ngw.ConnectivityType) d.Set(names.AttrState, ngw.State) d.Set(names.AttrSubnetID, ngw.SubnetId) @@ -142,17 +142,17 @@ func dataSourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta for _, address := range ngw.NatGatewayAddresses { // Length check guarantees the attributes are always set (#30865). - if isPrimary := aws.BoolValue(address.IsPrimary); isPrimary || len(ngw.NatGatewayAddresses) == 1 { + if isPrimary := aws.ToBool(address.IsPrimary); isPrimary || len(ngw.NatGatewayAddresses) == 1 { d.Set("allocation_id", address.AllocationId) d.Set(names.AttrAssociationID, address.AssociationId) d.Set(names.AttrNetworkInterfaceID, address.NetworkInterfaceId) d.Set("private_ip", address.PrivateIp) d.Set("public_ip", address.PublicIp) } else if !isPrimary { - if allocationID := aws.StringValue(address.AllocationId); allocationID != "" { + if allocationID := aws.ToString(address.AllocationId); allocationID != "" { secondaryAllocationIDs = append(secondaryAllocationIDs, allocationID) } - if privateIP := aws.StringValue(address.PrivateIp); privateIP != "" { + if privateIP := aws.ToString(address.PrivateIp); privateIP != "" { secondaryPrivateIPAddresses = append(secondaryPrivateIPAddresses, privateIP) } } @@ -162,7 +162,7 @@ func dataSourceNATGatewayRead(ctx context.Context, d *schema.ResourceData, meta d.Set("secondary_private_ip_address_count", len(secondaryPrivateIPAddresses)) d.Set("secondary_private_ip_addresses", secondaryPrivateIPAddresses) - if err := d.Set(names.AttrTags, KeyValueTags(ctx, ngw.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, ngw.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_nat_gateway_test.go b/internal/service/ec2/vpc_nat_gateway_test.go index f29133ab675..d67904c7f73 100644 --- a/internal/service/ec2/vpc_nat_gateway_test.go +++ b/internal/service/ec2/vpc_nat_gateway_test.go @@ -9,7 +9,7 @@ import ( "strconv" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -22,7 +22,7 @@ import ( func TestAccVPCNATGateway_basic(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -59,7 +59,7 @@ func TestAccVPCNATGateway_basic(t *testing.T) { func TestAccVPCNATGateway_disappears(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -83,7 +83,7 @@ func TestAccVPCNATGateway_disappears(t *testing.T) { func TestAccVPCNATGateway_ConnectivityType_private(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -119,7 +119,7 @@ func TestAccVPCNATGateway_ConnectivityType_private(t *testing.T) { func TestAccVPCNATGateway_privateIP(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -155,7 +155,7 @@ func TestAccVPCNATGateway_privateIP(t *testing.T) { func TestAccVPCNATGateway_tags(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -201,7 +201,7 @@ func TestAccVPCNATGateway_tags(t *testing.T) { func TestAccVPCNATGateway_secondaryAllocationIDs(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" eipResourceName := "aws_eip.secondary" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -252,7 +252,7 @@ func TestAccVPCNATGateway_secondaryAllocationIDs(t *testing.T) { func TestAccVPCNATGateway_secondaryPrivateIPAddressCount(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -284,7 +284,7 @@ func TestAccVPCNATGateway_secondaryPrivateIPAddressCount(t *testing.T) { func TestAccVPCNATGateway_secondaryPrivateIPAddresses(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) eipResourceName := "aws_eip.secondary" @@ -337,7 +337,7 @@ func TestAccVPCNATGateway_secondaryPrivateIPAddresses(t *testing.T) { func TestAccVPCNATGateway_SecondaryPrivateIPAddresses_private(t *testing.T) { ctx := acctest.Context(t) - var natGateway ec2.NatGateway + var natGateway awstypes.NatGateway resourceName := "aws_nat_gateway.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -401,7 +401,7 @@ func TestAccVPCNATGateway_SecondaryPrivateIPAddresses_private(t *testing.T) { func testAccCheckNATGatewayDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_nat_gateway" { @@ -425,7 +425,7 @@ func testAccCheckNATGatewayDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckNATGatewayExists(ctx context.Context, n string, v *ec2.NatGateway) resource.TestCheckFunc { +func testAccCheckNATGatewayExists(ctx context.Context, n string, v *awstypes.NatGateway) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -436,7 +436,7 @@ func testAccCheckNATGatewayExists(ctx context.Context, n string, v *ec2.NatGatew return fmt.Errorf("No EC2 NAT Gateway ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindNATGatewayByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_nat_gateways_data_source.go b/internal/service/ec2/vpc_nat_gateways_data_source.go index cee1b2b7cb9..10d6a3da972 100644 --- a/internal/service/ec2/vpc_nat_gateways_data_source.go +++ b/internal/service/ec2/vpc_nat_gateways_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_nat_gateways") -func DataSourceNATGateways() *schema.Resource { +// @SDKDataSource("aws_nat_gateways", name="NAT Gateways") +func dataSourceNATGateways() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceNATGatewaysRead, @@ -45,7 +45,7 @@ func DataSourceNATGateways() *schema.Resource { func dataSourceNATGatewaysRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeNatGatewaysInput{} @@ -71,7 +71,7 @@ func dataSourceNATGatewaysRead(ctx context.Context, d *schema.ResourceData, meta input.Filter = nil } - output, err := FindNATGateways(ctx, conn, input) + output, err := findNATGateways(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 NAT Gateways: %s", err) @@ -80,7 +80,7 @@ func dataSourceNATGatewaysRead(ctx context.Context, d *schema.ResourceData, meta var natGatewayIDs []string for _, v := range output { - natGatewayIDs = append(natGatewayIDs, aws.StringValue(v.NatGatewayId)) + natGatewayIDs = append(natGatewayIDs, aws.ToString(v.NatGatewayId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_network_acl.go b/internal/service/ec2/vpc_network_acl.go index 544c2c471a6..9fa62b3a92f 100644 --- a/internal/service/ec2/vpc_network_acl.go +++ b/internal/service/ec2/vpc_network_acl.go @@ -11,16 +11,18 @@ import ( "strconv" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" @@ -40,15 +42,15 @@ func resourceNetworkACL() *schema.Resource { Importer: &schema.ResourceImporter{ StateContext: func(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - nacl, err := FindNetworkACLByID(ctx, conn, d.Id()) + nacl, err := findNetworkACLByID(ctx, conn, d.Id()) if err != nil { return nil, err } - if aws.BoolValue(nacl.IsDefault) { + if aws.ToBool(nacl.IsDefault) { return nil, fmt.Errorf("use the `aws_default_network_acl` resource instead") } @@ -112,7 +114,8 @@ func networkACLRuleNestedBlock() *schema.Resource { DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { return strings.EqualFold(old, new) }, - ValidateFunc: validation.StringInSlice(ec2.RuleAction_Values(), true), + // Accept pascal case for backwards compatibility reasons, See: TestAccVPCNetworkACL_caseSensitivityNoChanges + ValidateFunc: validation.StringInSlice(enum.Slice(awstypes.RuleAction.Values("")...), true), }, names.AttrCIDRBlock: { Type: schema.TypeString, @@ -166,21 +169,21 @@ func networkACLRuleNestedBlock() *schema.Resource { func resourceNetworkACLCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateNetworkAclInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeNetworkAcl), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeNetworkAcl), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } - output, err := conn.CreateNetworkAclWithContext(ctx, input) + output, err := conn.CreateNetworkAcl(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Network ACL: %s", err) } - d.SetId(aws.StringValue(output.NetworkAcl.NetworkAclId)) + d.SetId(aws.ToString(output.NetworkAcl.NetworkAclId)) if err := modifyNetworkACLAttributesOnCreate(ctx, conn, d); err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Network ACL: %s", err) @@ -191,10 +194,10 @@ func resourceNetworkACLCreate(ctx context.Context, d *schema.ResourceData, meta func resourceNetworkACLRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindNetworkACLByID(ctx, conn, d.Id()) + return findNetworkACLByID(ctx, conn, d.Id()) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -207,12 +210,12 @@ func resourceNetworkACLRead(ctx context.Context, d *schema.ResourceData, meta in return sdkdiag.AppendErrorf(diags, "reading EC2 Network ACL (%s): %s", d.Id(), err) } - nacl := outputRaw.(*ec2.NetworkAcl) + nacl := outputRaw.(*awstypes.NetworkAcl) - ownerID := aws.StringValue(nacl.OwnerId) + ownerID := aws.ToString(nacl.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("network-acl/%s", d.Id()), @@ -222,22 +225,22 @@ func resourceNetworkACLRead(ctx context.Context, d *schema.ResourceData, meta in var subnetIDs []string for _, v := range nacl.Associations { - subnetIDs = append(subnetIDs, aws.StringValue(v.SubnetId)) + subnetIDs = append(subnetIDs, aws.ToString(v.SubnetId)) } d.Set(names.AttrSubnetIDs, subnetIDs) d.Set(names.AttrVPCID, nacl.VpcId) - var egressEntries []*ec2.NetworkAclEntry - var ingressEntries []*ec2.NetworkAclEntry + var egressEntries []awstypes.NetworkAclEntry + var ingressEntries []awstypes.NetworkAclEntry for _, v := range nacl.Entries { // Skip the default rules added by AWS. They can be neither // configured or deleted by users. - if v := aws.Int64Value(v.RuleNumber); v == defaultACLRuleNumberIPv4 || v == defaultACLRuleNumberIPv6 { + if v := aws.ToInt32(v.RuleNumber); v == defaultACLRuleNumberIPv4 || v == defaultACLRuleNumberIPv6 { continue } - if aws.BoolValue(v.Egress) { + if aws.ToBool(v.Egress) { egressEntries = append(egressEntries, v) } else { ingressEntries = append(ingressEntries, v) @@ -257,7 +260,7 @@ func resourceNetworkACLRead(ctx context.Context, d *schema.ResourceData, meta in func resourceNetworkACLUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) if err := modifyNetworkACLAttributesOnUpdate(ctx, conn, d, true); err != nil { return sdkdiag.AppendErrorf(diags, "updating EC2 Network ACL (%s): %s", d.Id(), err) @@ -268,10 +271,10 @@ func resourceNetworkACLUpdate(ctx context.Context, d *schema.ResourceData, meta func resourceNetworkACLDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) // Delete all NACL/Subnet associations, even if they are managed via aws_network_acl_association resources. - nacl, err := FindNetworkACLByID(ctx, conn, d.Id()) + nacl, err := findNetworkACLByID(ctx, conn, d.Id()) if tfresource.NotFound(err) { return diags @@ -283,7 +286,7 @@ func resourceNetworkACLDelete(ctx context.Context, d *schema.ResourceData, meta var subnetIDs []interface{} for _, v := range nacl.Associations { - subnetIDs = append(subnetIDs, aws.StringValue(v.SubnetId)) + subnetIDs = append(subnetIDs, aws.ToString(v.SubnetId)) } if len(subnetIDs) > 0 { if err := networkACLAssociationsDelete(ctx, conn, d.Get(names.AttrVPCID).(string), subnetIDs); err != nil { @@ -297,7 +300,7 @@ func resourceNetworkACLDelete(ctx context.Context, d *schema.ResourceData, meta log.Printf("[INFO] Deleting EC2 Network ACL: %s", d.Id()) _, err = tfresource.RetryWhenAWSErrCodeEquals(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return conn.DeleteNetworkAclWithContext(ctx, input) + return conn.DeleteNetworkAcl(ctx, input) }, errCodeDependencyViolation) if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkACLIDNotFound) { @@ -314,7 +317,7 @@ func resourceNetworkACLDelete(ctx context.Context, d *schema.ResourceData, meta // modifyNetworkACLAttributesOnCreate sets NACL attributes on resource Create. // Called after new NACL creation or existing default NACL adoption. // Tags are not configured. -func modifyNetworkACLAttributesOnCreate(ctx context.Context, conn *ec2.EC2, d *schema.ResourceData) error { +func modifyNetworkACLAttributesOnCreate(ctx context.Context, conn *ec2.Client, d *schema.ResourceData) error { if v, ok := d.GetOk("egress"); ok && v.(*schema.Set).Len() > 0 { if err := createNetworkACLEntries(ctx, conn, d.Id(), v.(*schema.Set).List(), true); err != nil { return err @@ -340,7 +343,7 @@ func modifyNetworkACLAttributesOnCreate(ctx context.Context, conn *ec2.EC2, d *s // modifyNetworkACLAttributesOnUpdate sets NACL attributes on resource Update. // Tags are configured. -func modifyNetworkACLAttributesOnUpdate(ctx context.Context, conn *ec2.EC2, d *schema.ResourceData, deleteAssociations bool) error { +func modifyNetworkACLAttributesOnUpdate(ctx context.Context, conn *ec2.Client, d *schema.ResourceData, deleteAssociations bool) error { if d.HasChange("ingress") { o, n := d.GetChange("ingress") os, ns := o.(*schema.Set), n.(*schema.Set) @@ -410,20 +413,16 @@ func networkACLRuleHash(v interface{}) int { return create.StringHashcode(buf.String()) } -func createNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, tfList []interface{}, egress bool) error { +func createNetworkACLEntries(ctx context.Context, conn *ec2.Client, naclID string, tfList []interface{}, egress bool) error { naclEntries := expandNetworkACLEntries(tfList, egress) for _, naclEntry := range naclEntries { - if naclEntry == nil { - continue - } - - if aws.StringValue(naclEntry.Protocol) == "-1" { + if aws.ToString(naclEntry.Protocol) == "-1" { // Protocol -1 rules don't store ports in AWS. Thus, they'll always // hash differently when being read out of the API. Force the user // to set from_port and to_port to 0 for these rules, to keep the // hashing consistent. - if from, to := aws.Int64Value(naclEntry.PortRange.From), aws.Int64Value(naclEntry.PortRange.To); from != 0 || to != 0 { + if from, to := aws.ToInt32(naclEntry.PortRange.From), aws.ToInt32(naclEntry.PortRange.To); from != 0 || to != 0 { return fmt.Errorf("to_port (%d) and from_port (%d) must both be 0 to use the 'all' \"-1\" protocol!", to, from) } } @@ -440,8 +439,8 @@ func createNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, RuleNumber: naclEntry.RuleNumber, } - log.Printf("[INFO] Creating EC2 Network ACL Entry: %s", input) - _, err := conn.CreateNetworkAclEntryWithContext(ctx, input) + log.Printf("[INFO] Creating EC2 Network ACL Entry: %#v", input) + _, err := conn.CreateNetworkAclEntry(ctx, input) if err != nil { return fmt.Errorf("creating EC2 Network ACL (%s) Entry: %w", naclID, err) @@ -451,21 +450,17 @@ func createNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, return nil } -func deleteNetworkACLEntriesList(ctx context.Context, conn *ec2.EC2, naclID string, tfList []interface{}, egress bool) error { +func deleteNetworkACLEntriesList(ctx context.Context, conn *ec2.Client, naclID string, tfList []interface{}, egress bool) error { return deleteNetworkACLEntries(ctx, conn, naclID, expandNetworkACLEntries(tfList, egress)) } -func deleteNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, naclEntries []*ec2.NetworkAclEntry) error { +func deleteNetworkACLEntries(ctx context.Context, conn *ec2.Client, naclID string, naclEntries []awstypes.NetworkAclEntry) error { for _, naclEntry := range naclEntries { - if naclEntry == nil { - continue - } - // AWS includes default rules with all network ACLs that can be // neither modified nor destroyed. They have a custom rule // number that is out of bounds for any other rule. If we // encounter it, just continue. There's no work to be done. - if v := aws.Int64Value(naclEntry.RuleNumber); v == defaultACLRuleNumberIPv4 || v == defaultACLRuleNumberIPv6 { + if v := aws.ToInt32(naclEntry.RuleNumber); v == defaultACLRuleNumberIPv4 || v == defaultACLRuleNumberIPv6 { continue } @@ -475,8 +470,8 @@ func deleteNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, RuleNumber: naclEntry.RuleNumber, } - log.Printf("[INFO] Deleting EC2 Network ACL Entry: %s", input) - _, err := conn.DeleteNetworkAclEntryWithContext(ctx, input) + log.Printf("[INFO] Deleting EC2 Network ACL Entry: %#v", input) + _, err := conn.DeleteNetworkAclEntry(ctx, input) if err != nil { return fmt.Errorf("deleting EC2 Network ACL (%s) Entry: %w", naclID, err) @@ -486,7 +481,7 @@ func deleteNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, return nil } -func updateNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, os, ns *schema.Set, egress bool) error { +func updateNetworkACLEntries(ctx context.Context, conn *ec2.Client, naclID string, os, ns *schema.Set, egress bool) error { if err := deleteNetworkACLEntriesList(ctx, conn, naclID, os.Difference(ns).List(), egress); err != nil { return err } @@ -498,22 +493,22 @@ func updateNetworkACLEntries(ctx context.Context, conn *ec2.EC2, naclID string, return nil } -func expandNetworkACLEntry(tfMap map[string]interface{}, egress bool) *ec2.NetworkAclEntry { +func expandNetworkACLEntry(tfMap map[string]interface{}, egress bool) *awstypes.NetworkAclEntry { if tfMap == nil { return nil } - apiObject := &ec2.NetworkAclEntry{ + apiObject := &awstypes.NetworkAclEntry{ Egress: aws.Bool(egress), - PortRange: &ec2.PortRange{}, + PortRange: &awstypes.PortRange{}, } if v, ok := tfMap["rule_no"].(int); ok { - apiObject.RuleNumber = aws.Int64(int64(v)) + apiObject.RuleNumber = aws.Int32(int32(v)) } if v, ok := tfMap[names.AttrAction].(string); ok && v != "" { - apiObject.RuleAction = aws.String(v) + apiObject.RuleAction = awstypes.RuleAction(v) } if v, ok := tfMap[names.AttrCIDRBlock].(string); ok && v != "" { @@ -525,11 +520,11 @@ func expandNetworkACLEntry(tfMap map[string]interface{}, egress bool) *ec2.Netwo } if v, ok := tfMap["from_port"].(int); ok { - apiObject.PortRange.From = aws.Int64(int64(v)) + apiObject.PortRange.From = aws.Int32(int32(v)) } if v, ok := tfMap["to_port"].(int); ok { - apiObject.PortRange.To = aws.Int64(int64(v)) + apiObject.PortRange.To = aws.Int32(int32(v)) } if v, ok := tfMap[names.AttrProtocol].(string); ok && v != "" { @@ -544,14 +539,14 @@ func expandNetworkACLEntry(tfMap map[string]interface{}, egress bool) *ec2.Netwo // Specify additional required fields for ICMP. if protocolNumber == 1 || protocolNumber == 58 { - apiObject.IcmpTypeCode = &ec2.IcmpTypeCode{} + apiObject.IcmpTypeCode = &awstypes.IcmpTypeCode{} if v, ok := tfMap["icmp_code"].(int); ok { - apiObject.IcmpTypeCode.Code = aws.Int64(int64(v)) + apiObject.IcmpTypeCode.Code = aws.Int32(int32(v)) } if v, ok := tfMap["icmp_type"].(int); ok { - apiObject.IcmpTypeCode.Type = aws.Int64(int64(v)) + apiObject.IcmpTypeCode.Type = aws.Int32(int32(v)) } } } @@ -559,12 +554,12 @@ func expandNetworkACLEntry(tfMap map[string]interface{}, egress bool) *ec2.Netwo return apiObject } -func expandNetworkACLEntries(tfList []interface{}, egress bool) []*ec2.NetworkAclEntry { +func expandNetworkACLEntries(tfList []interface{}, egress bool) []awstypes.NetworkAclEntry { if len(tfList) == 0 { return nil } - var apiObjects []*ec2.NetworkAclEntry + var apiObjects []awstypes.NetworkAclEntry for _, tfMapRaw := range tfList { tfMap, ok := tfMapRaw.(map[string]interface{}) @@ -579,46 +574,40 @@ func expandNetworkACLEntries(tfList []interface{}, egress bool) []*ec2.NetworkAc continue } - apiObjects = append(apiObjects, apiObject) + apiObjects = append(apiObjects, *apiObject) } return apiObjects } -func flattenNetworkACLEntry(apiObject *ec2.NetworkAclEntry) map[string]interface{} { - if apiObject == nil { - return nil +func flattenNetworkACLEntry(apiObject awstypes.NetworkAclEntry) map[string]interface{} { + tfMap := map[string]interface{}{ + names.AttrAction: apiObject.RuleAction, } - tfMap := map[string]interface{}{} - if v := apiObject.RuleNumber; v != nil { - tfMap["rule_no"] = aws.Int64Value(v) - } - - if v := apiObject.RuleAction; v != nil { - tfMap[names.AttrAction] = aws.StringValue(v) + tfMap["rule_no"] = aws.ToInt32(v) } if v := apiObject.CidrBlock; v != nil { - tfMap[names.AttrCIDRBlock] = aws.StringValue(v) + tfMap[names.AttrCIDRBlock] = aws.ToString(v) } if v := apiObject.Ipv6CidrBlock; v != nil { - tfMap["ipv6_cidr_block"] = aws.StringValue(v) + tfMap["ipv6_cidr_block"] = aws.ToString(v) } if apiObject := apiObject.PortRange; apiObject != nil { if v := apiObject.From; v != nil { - tfMap["from_port"] = aws.Int64Value(v) + tfMap["from_port"] = aws.ToInt32(v) } if v := apiObject.To; v != nil { - tfMap["to_port"] = aws.Int64Value(v) + tfMap["to_port"] = aws.ToInt32(v) } } - if v := aws.StringValue(apiObject.Protocol); v != "" { + if v := aws.ToString(apiObject.Protocol); v != "" { // The AWS network ACL API only speaks protocol numbers, and // that's all we record. protocolNumber, err := networkACLProtocolNumber(v) @@ -633,18 +622,18 @@ func flattenNetworkACLEntry(apiObject *ec2.NetworkAclEntry) map[string]interface if apiObject := apiObject.IcmpTypeCode; apiObject != nil { if v := apiObject.Code; v != nil { - tfMap["icmp_code"] = aws.Int64Value(v) + tfMap["icmp_code"] = aws.ToInt32(v) } if v := apiObject.Type; v != nil { - tfMap["icmp_type"] = aws.Int64Value(v) + tfMap["icmp_type"] = aws.ToInt32(v) } } return tfMap } -func flattenNetworkACLEntries(apiObjects []*ec2.NetworkAclEntry) []interface{} { +func flattenNetworkACLEntries(apiObjects []awstypes.NetworkAclEntry) []interface{} { if len(apiObjects) == 0 { return nil } @@ -652,10 +641,6 @@ func flattenNetworkACLEntries(apiObjects []*ec2.NetworkAclEntry) []interface{} { var tfList []interface{} for _, apiObject := range apiObjects { - if apiObject == nil { - continue - } - tfList = append(tfList, flattenNetworkACLEntry(apiObject)) } diff --git a/internal/service/ec2/vpc_network_acl_association.go b/internal/service/ec2/vpc_network_acl_association.go index 28c5e15c45b..02f101dcd3b 100644 --- a/internal/service/ec2/vpc_network_acl_association.go +++ b/internal/service/ec2/vpc_network_acl_association.go @@ -8,9 +8,10 @@ import ( "fmt" "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -19,8 +20,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_network_acl_association") -func ResourceNetworkACLAssociation() *schema.Resource { +// @SDKResource("aws_network_acl_association", name="Network ACL Association") +func resourceNetworkACLAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceNetworkACLAssociationCreate, ReadWithoutTimeout: resourceNetworkACLAssociationRead, @@ -46,7 +47,7 @@ func ResourceNetworkACLAssociation() *schema.Resource { func resourceNetworkACLAssociationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) associationID, err := networkACLAssociationCreate(ctx, conn, d.Get("network_acl_id").(string), d.Get(names.AttrSubnetID).(string)) @@ -61,10 +62,10 @@ func resourceNetworkACLAssociationCreate(ctx context.Context, d *schema.Resource func resourceNetworkACLAssociationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindNetworkACLAssociationByID(ctx, conn, d.Id()) + return findNetworkACLAssociationByID(ctx, conn, d.Id()) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -77,7 +78,7 @@ func resourceNetworkACLAssociationRead(ctx context.Context, d *schema.ResourceDa return sdkdiag.AppendErrorf(diags, "reading EC2 Network ACL Association (%s): %s", d.Id(), err) } - association := outputRaw.(*ec2.NetworkAclAssociation) + association := outputRaw.(*awstypes.NetworkAclAssociation) d.Set("network_acl_id", association.NetworkAclId) d.Set(names.AttrSubnetID, association.SubnetId) @@ -87,7 +88,7 @@ func resourceNetworkACLAssociationRead(ctx context.Context, d *schema.ResourceDa func resourceNetworkACLAssociationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeNetworkAclsInput{ Filters: newAttributeFilterList(map[string]string{ @@ -95,20 +96,24 @@ func resourceNetworkACLAssociationDelete(ctx context.Context, d *schema.Resource }), } - nacl, err := FindNetworkACL(ctx, conn, input) + nacl, err := findNetworkACL(ctx, conn, input) + + if tfresource.NotFound(err) { + return diags + } if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Network ACL for Association (%s): %s", d.Id(), err) } - vpcID := aws.StringValue(nacl.VpcId) - defaultNACL, err := FindVPCDefaultNetworkACL(ctx, conn, vpcID) + vpcID := aws.ToString(nacl.VpcId) + defaultNACL, err := findVPCDefaultNetworkACL(ctx, conn, vpcID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC (%s) default NACL: %s", vpcID, err) } - if err := networkACLAssociationDelete(ctx, conn, d.Id(), aws.StringValue(defaultNACL.NetworkAclId)); err != nil { + if err := networkACLAssociationDelete(ctx, conn, d.Id(), aws.ToString(defaultNACL.NetworkAclId)); err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -117,8 +122,8 @@ func resourceNetworkACLAssociationDelete(ctx context.Context, d *schema.Resource // networkACLAssociationCreate creates an association between the specified NACL and subnet. // The subnet's current association is replaced and the new association's ID is returned. -func networkACLAssociationCreate(ctx context.Context, conn *ec2.EC2, naclID, subnetID string) (string, error) { - association, err := FindNetworkACLAssociationBySubnetID(ctx, conn, subnetID) +func networkACLAssociationCreate(ctx context.Context, conn *ec2.Client, naclID, subnetID string) (string, error) { + association, err := findNetworkACLAssociationBySubnetID(ctx, conn, subnetID) if err != nil { return "", fmt.Errorf("reading EC2 Network ACL Association for EC2 Subnet (%s): %w", subnetID, err) @@ -129,20 +134,20 @@ func networkACLAssociationCreate(ctx context.Context, conn *ec2.EC2, naclID, sub NetworkAclId: aws.String(naclID), } - log.Printf("[DEBUG] Creating EC2 Network ACL Association: %s", input) + log.Printf("[DEBUG] Creating EC2 Network ACL Association: %#v", input) outputRaw, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return conn.ReplaceNetworkAclAssociationWithContext(ctx, input) + return conn.ReplaceNetworkAclAssociation(ctx, input) }, errCodeInvalidAssociationIDNotFound) if err != nil { return "", fmt.Errorf("creating EC2 Network ACL (%s) Association: %w", naclID, err) } - return aws.StringValue(outputRaw.(*ec2.ReplaceNetworkAclAssociationOutput).NewAssociationId), nil + return aws.ToString(outputRaw.(*ec2.ReplaceNetworkAclAssociationOutput).NewAssociationId), nil } // networkACLAssociationsCreate creates associations between the specified NACL and subnets. -func networkACLAssociationsCreate(ctx context.Context, conn *ec2.EC2, naclID string, subnetIDs []interface{}) error { +func networkACLAssociationsCreate(ctx context.Context, conn *ec2.Client, naclID string, subnetIDs []interface{}) error { for _, v := range subnetIDs { subnetID := v.(string) _, err := networkACLAssociationCreate(ctx, conn, naclID, subnetID) @@ -162,14 +167,14 @@ func networkACLAssociationsCreate(ctx context.Context, conn *ec2.EC2, naclID str // networkACLAssociationDelete deletes the specified association between a NACL and subnet. // The subnet's current association is replaced by an association with the VPC's default NACL. -func networkACLAssociationDelete(ctx context.Context, conn *ec2.EC2, associationID, naclID string) error { +func networkACLAssociationDelete(ctx context.Context, conn *ec2.Client, associationID, naclID string) error { input := &ec2.ReplaceNetworkAclAssociationInput{ AssociationId: aws.String(associationID), NetworkAclId: aws.String(naclID), } log.Printf("[DEBUG] Deleting EC2 Network ACL Association: %s", associationID) - _, err := conn.ReplaceNetworkAclAssociationWithContext(ctx, input) + _, err := conn.ReplaceNetworkAclAssociation(ctx, input) if tfawserr.ErrCodeEquals(err, errCodeInvalidAssociationIDNotFound) { return nil @@ -184,8 +189,8 @@ func networkACLAssociationDelete(ctx context.Context, conn *ec2.EC2, association // networkACLAssociationsDelete deletes the specified NACL associations for the specified subnets. // Each subnet's current association is replaced by an association with the specified VPC's default NACL. -func networkACLAssociationsDelete(ctx context.Context, conn *ec2.EC2, vpcID string, subnetIDs []interface{}) error { - defaultNACL, err := FindVPCDefaultNetworkACL(ctx, conn, vpcID) +func networkACLAssociationsDelete(ctx context.Context, conn *ec2.Client, vpcID string, subnetIDs []interface{}) error { + defaultNACL, err := findVPCDefaultNetworkACL(ctx, conn, vpcID) if err != nil { return fmt.Errorf("reading EC2 VPC (%s) default NACL: %w", vpcID, err) @@ -193,7 +198,7 @@ func networkACLAssociationsDelete(ctx context.Context, conn *ec2.EC2, vpcID stri for _, v := range subnetIDs { subnetID := v.(string) - association, err := FindNetworkACLAssociationBySubnetID(ctx, conn, subnetID) + association, err := findNetworkACLAssociationBySubnetID(ctx, conn, subnetID) if tfresource.NotFound(err) { // Subnet has been deleted. @@ -204,7 +209,7 @@ func networkACLAssociationsDelete(ctx context.Context, conn *ec2.EC2, vpcID stri return fmt.Errorf("reading EC2 Network ACL Association for EC2 Subnet (%s): %w", subnetID, err) } - if err := networkACLAssociationDelete(ctx, conn, aws.StringValue(association.NetworkAclAssociationId), aws.StringValue(defaultNACL.NetworkAclId)); err != nil { + if err := networkACLAssociationDelete(ctx, conn, aws.ToString(association.NetworkAclAssociationId), aws.ToString(defaultNACL.NetworkAclId)); err != nil { return err } } diff --git a/internal/service/ec2/vpc_network_acl_association_test.go b/internal/service/ec2/vpc_network_acl_association_test.go index dcd0bc76fab..003dbc3690f 100644 --- a/internal/service/ec2/vpc_network_acl_association_test.go +++ b/internal/service/ec2/vpc_network_acl_association_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -21,7 +21,7 @@ import ( func TestAccVPCNetworkACLAssociation_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAclAssociation + var v awstypes.NetworkAclAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_network_acl_association.test" naclResourceName := "aws_network_acl.test" @@ -52,7 +52,7 @@ func TestAccVPCNetworkACLAssociation_basic(t *testing.T) { func TestAccVPCNetworkACLAssociation_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAclAssociation + var v awstypes.NetworkAclAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_network_acl_association.test" @@ -76,7 +76,7 @@ func TestAccVPCNetworkACLAssociation_disappears(t *testing.T) { func TestAccVPCNetworkACLAssociation_disappears_NACL(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAclAssociation + var v awstypes.NetworkAclAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_network_acl_association.test" naclResourceName := "aws_network_acl.test" @@ -101,7 +101,7 @@ func TestAccVPCNetworkACLAssociation_disappears_NACL(t *testing.T) { func TestAccVPCNetworkACLAssociation_disappears_Subnet(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAclAssociation + var v awstypes.NetworkAclAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_network_acl_association.test" subnetResourceName := "aws_subnet.test" @@ -126,7 +126,7 @@ func TestAccVPCNetworkACLAssociation_disappears_Subnet(t *testing.T) { func TestAccVPCNetworkACLAssociation_twoAssociations(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.NetworkAclAssociation + var v1, v2 awstypes.NetworkAclAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource1Name := "aws_network_acl_association.test1" resource2Name := "aws_network_acl_association.test2" @@ -167,7 +167,7 @@ func TestAccVPCNetworkACLAssociation_twoAssociations(t *testing.T) { func TestAccVPCNetworkACLAssociation_associateWithDefaultNACL(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAclAssociation + var v awstypes.NetworkAclAssociation rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_network_acl_association.test" subnetResourceName := "aws_subnet.test" @@ -196,7 +196,7 @@ func TestAccVPCNetworkACLAssociation_associateWithDefaultNACL(t *testing.T) { func testAccCheckNetworkACLAssociationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_network_acl_association" { @@ -220,7 +220,7 @@ func testAccCheckNetworkACLAssociationDestroy(ctx context.Context) resource.Test } } -func testAccCheckNetworkACLAssociationExists(ctx context.Context, n string, v *ec2.NetworkAclAssociation) resource.TestCheckFunc { +func testAccCheckNetworkACLAssociationExists(ctx context.Context, n string, v *awstypes.NetworkAclAssociation) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -231,7 +231,7 @@ func testAccCheckNetworkACLAssociationExists(ctx context.Context, n string, v *e return fmt.Errorf("No EC2 Network ACL Association ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindNetworkACLAssociationByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_network_acl_rule.go b/internal/service/ec2/vpc_network_acl_rule.go index e8c83e15388..5d2f2733014 100644 --- a/internal/service/ec2/vpc_network_acl_rule.go +++ b/internal/service/ec2/vpc_network_acl_rule.go @@ -11,14 +11,15 @@ import ( "strconv" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" "github.com/hashicorp/terraform-provider-aws/names" @@ -105,7 +106,7 @@ func resourceNetworkACLRule() *schema.Resource { DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { return strings.EqualFold(old, new) }, - ValidateFunc: validation.StringInSlice(ec2.RuleAction_Values(), true), + ValidateDiagFunc: enum.Validate[awstypes.RuleAction](), }, "rule_number": { Type: schema.TypeInt, @@ -123,7 +124,7 @@ func resourceNetworkACLRule() *schema.Resource { func resourceNetworkACLRuleCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) protocol := d.Get(names.AttrProtocol).(string) protocolNumber, err := networkACLProtocolNumber(protocol) @@ -134,7 +135,7 @@ func resourceNetworkACLRuleCreate(ctx context.Context, d *schema.ResourceData, m naclID, egress, ruleNumber := d.Get("network_acl_id").(string), d.Get("egress").(bool), d.Get("rule_number").(int) // CreateNetworkAclEntry succeeds if there is an existing rule with identical attributes. - _, err = FindNetworkACLEntryByThreePartKey(ctx, conn, naclID, egress, ruleNumber) + _, err = findNetworkACLEntryByThreePartKey(ctx, conn, naclID, egress, ruleNumber) switch { case err == nil: @@ -148,13 +149,13 @@ func resourceNetworkACLRuleCreate(ctx context.Context, d *schema.ResourceData, m input := &ec2.CreateNetworkAclEntryInput{ Egress: aws.Bool(egress), NetworkAclId: aws.String(naclID), - PortRange: &ec2.PortRange{ - From: aws.Int64(int64(d.Get("from_port").(int))), - To: aws.Int64(int64(d.Get("to_port").(int))), + PortRange: &awstypes.PortRange{ + From: aws.Int32(int32(d.Get("from_port").(int))), + To: aws.Int32(int32(d.Get("to_port").(int))), }, Protocol: aws.String(strconv.Itoa(protocolNumber)), - RuleAction: aws.String(d.Get("rule_action").(string)), - RuleNumber: aws.Int64(int64(ruleNumber)), + RuleAction: awstypes.RuleAction(d.Get("rule_action").(string)), + RuleNumber: aws.Int32(int32(ruleNumber)), } if v, ok := d.GetOk(names.AttrCIDRBlock); ok { @@ -168,34 +169,34 @@ func resourceNetworkACLRuleCreate(ctx context.Context, d *schema.ResourceData, m // Specify additional required fields for ICMP. For the list // of ICMP codes and types, see: https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml if protocolNumber == 1 || protocolNumber == 58 { - input.IcmpTypeCode = &ec2.IcmpTypeCode{ - Code: aws.Int64(int64(d.Get("icmp_code").(int))), - Type: aws.Int64(int64(d.Get("icmp_type").(int))), + input.IcmpTypeCode = &awstypes.IcmpTypeCode{ + Code: aws.Int32(int32(d.Get("icmp_code").(int))), + Type: aws.Int32(int32(d.Get("icmp_type").(int))), } } - log.Printf("[DEBUG] Creating EC2 Network ACL Rule: %s", input) - _, err = conn.CreateNetworkAclEntryWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 Network ACL Rule: %#v", input) + _, err = conn.CreateNetworkAclEntry(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Network ACL (%s) Rule (egress: %t)(%d): %s", naclID, egress, ruleNumber, err) } - d.SetId(NetworkACLRuleCreateResourceID(naclID, ruleNumber, egress, protocol)) + d.SetId(networkACLRuleCreateResourceID(naclID, ruleNumber, egress, protocol)) return append(diags, resourceNetworkACLRuleRead(ctx, d, meta)...) } func resourceNetworkACLRuleRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) egress := d.Get("egress").(bool) naclID := d.Get("network_acl_id").(string) ruleNumber := d.Get("rule_number").(int) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindNetworkACLEntryByThreePartKey(ctx, conn, naclID, egress, ruleNumber) + return findNetworkACLEntryByThreePartKey(ctx, conn, naclID, egress, ruleNumber) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -208,7 +209,7 @@ func resourceNetworkACLRuleRead(ctx context.Context, d *schema.ResourceData, met return sdkdiag.AppendErrorf(diags, "reading EC2 Network ACL Rule (%s): %s", d.Id(), err) } - naclEntry := outputRaw.(*ec2.NetworkAclEntry) + naclEntry := outputRaw.(*awstypes.NetworkAclEntry) d.Set(names.AttrCIDRBlock, naclEntry.CidrBlock) d.Set("egress", naclEntry.Egress) @@ -224,7 +225,7 @@ func resourceNetworkACLRuleRead(ctx context.Context, d *schema.ResourceData, met d.Set("rule_action", naclEntry.RuleAction) d.Set("rule_number", naclEntry.RuleNumber) - if v := aws.StringValue(naclEntry.Protocol); v != "" { + if v := aws.ToString(naclEntry.Protocol); v != "" { // The AWS network ACL API only speaks protocol numbers, and // that's all we record. protocolNumber, err := networkACLProtocolNumber(v) @@ -243,13 +244,13 @@ func resourceNetworkACLRuleRead(ctx context.Context, d *schema.ResourceData, met func resourceNetworkACLRuleDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting EC2 Network ACL Rule: %s", d.Id()) - _, err := conn.DeleteNetworkAclEntryWithContext(ctx, &ec2.DeleteNetworkAclEntryInput{ + _, err := conn.DeleteNetworkAclEntry(ctx, &ec2.DeleteNetworkAclEntryInput{ Egress: aws.Bool(d.Get("egress").(bool)), NetworkAclId: aws.String(d.Get("network_acl_id").(string)), - RuleNumber: aws.Int64(int64(d.Get("rule_number").(int))), + RuleNumber: aws.Int32(int32(d.Get("rule_number").(int))), }) if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkACLIDNotFound, errCodeInvalidNetworkACLEntryNotFound) { @@ -264,10 +265,10 @@ func resourceNetworkACLRuleDelete(ctx context.Context, d *schema.ResourceData, m } func resourceNetworkACLRuleImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - parts := strings.Split(d.Id(), NetworkACLRuleImportIDSeparator) + parts := strings.Split(d.Id(), networkACLRuleImportIDSeparator) if len(parts) != 4 || parts[0] == "" || parts[1] == "" || parts[2] == "" || parts[3] == "" { - return nil, fmt.Errorf("unexpected format of ID (%[1]s), expected NETWORK_ACL_ID%[2]sRULE_NUMBER%[2]sPROTOCOL%[2]sEGRESS", d.Id(), NetworkACLRuleImportIDSeparator) + return nil, fmt.Errorf("unexpected format of ID (%[1]s), expected NETWORK_ACL_ID%[2]sRULE_NUMBER%[2]sPROTOCOL%[2]sEGRESS", d.Id(), networkACLRuleImportIDSeparator) } naclID := parts[0] @@ -284,7 +285,7 @@ func resourceNetworkACLRuleImport(ctx context.Context, d *schema.ResourceData, m return nil, err } - d.SetId(NetworkACLRuleCreateResourceID(naclID, ruleNumber, egress, protocol)) + d.SetId(networkACLRuleCreateResourceID(naclID, ruleNumber, egress, protocol)) d.Set("egress", egress) d.Set("network_acl_id", naclID) d.Set("rule_number", ruleNumber) @@ -292,9 +293,9 @@ func resourceNetworkACLRuleImport(ctx context.Context, d *schema.ResourceData, m return []*schema.ResourceData{d}, nil } -const NetworkACLRuleImportIDSeparator = ":" +const networkACLRuleImportIDSeparator = ":" -func NetworkACLRuleCreateResourceID(naclID string, ruleNumber int, egress bool, protocol string) string { +func networkACLRuleCreateResourceID(naclID string, ruleNumber int, egress bool, protocol string) string { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("%s-", naclID)) buf.WriteString(fmt.Sprintf("%d-", ruleNumber)) diff --git a/internal/service/ec2/vpc_network_acl_rule_test.go b/internal/service/ec2/vpc_network_acl_rule_test.go index af14d5d140f..e50df38d739 100644 --- a/internal/service/ec2/vpc_network_acl_rule_test.go +++ b/internal/service/ec2/vpc_network_acl_rule_test.go @@ -11,7 +11,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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" @@ -234,7 +234,7 @@ func TestAccVPCNetworkACLRule_ipv6ICMP(t *testing.T) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/6710 func TestAccVPCNetworkACLRule_ipv6VPCAssignGeneratedIPv6CIDRBlockUpdate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Vpc + var v awstypes.Vpc rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) vpcResourceName := "aws_vpc.test" resourceName := "aws_network_acl_rule.test" @@ -358,7 +358,7 @@ func TestAccVPCNetworkACLRule_duplicate(t *testing.T) { func testAccCheckNetworkACLRuleDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_network_acl_rule" { @@ -398,7 +398,7 @@ func testAccCheckNetworkACLRuleDestroy(ctx context.Context) resource.TestCheckFu func testAccCheckNetworkACLRuleExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) diff --git a/internal/service/ec2/vpc_network_acl_test.go b/internal/service/ec2/vpc_network_acl_test.go index 6764e4e927e..63a74eebd7f 100644 --- a/internal/service/ec2/vpc_network_acl_test.go +++ b/internal/service/ec2/vpc_network_acl_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -22,7 +22,7 @@ import ( func TestAccVPCNetworkACL_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" vpcResourceName := "aws_vpc.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -57,7 +57,7 @@ func TestAccVPCNetworkACL_basic(t *testing.T) { func TestAccVPCNetworkACL_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -81,7 +81,7 @@ func TestAccVPCNetworkACL_disappears(t *testing.T) { func TestAccVPCNetworkACL_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -127,7 +127,7 @@ func TestAccVPCNetworkACL_tags(t *testing.T) { func TestAccVPCNetworkACL_Egress_mode(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -164,7 +164,7 @@ func TestAccVPCNetworkACL_Egress_mode(t *testing.T) { func TestAccVPCNetworkACL_Ingress_mode(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -201,7 +201,7 @@ func TestAccVPCNetworkACL_Ingress_mode(t *testing.T) { func TestAccVPCNetworkACL_egressAndIngressRules(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -239,7 +239,7 @@ func TestAccVPCNetworkACL_egressAndIngressRules(t *testing.T) { func TestAccVPCNetworkACL_OnlyIngressRules_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -269,7 +269,7 @@ func TestAccVPCNetworkACL_OnlyIngressRules_basic(t *testing.T) { func TestAccVPCNetworkACL_OnlyIngressRules_update(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -319,7 +319,7 @@ func TestAccVPCNetworkACL_OnlyIngressRules_update(t *testing.T) { func TestAccVPCNetworkACL_caseSensitivityNoChanges(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -341,7 +341,7 @@ func TestAccVPCNetworkACL_caseSensitivityNoChanges(t *testing.T) { func TestAccVPCNetworkACL_onlyEgressRules(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -363,7 +363,7 @@ func TestAccVPCNetworkACL_onlyEgressRules(t *testing.T) { func TestAccVPCNetworkACL_subnetChange(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -400,7 +400,7 @@ func TestAccVPCNetworkACL_subnetChange(t *testing.T) { func TestAccVPCNetworkACL_subnets(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -440,7 +440,7 @@ func TestAccVPCNetworkACL_subnets(t *testing.T) { func TestAccVPCNetworkACL_subnetsDelete(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -478,7 +478,7 @@ func TestAccVPCNetworkACL_subnetsDelete(t *testing.T) { func TestAccVPCNetworkACL_ipv6Rules(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -510,7 +510,7 @@ func TestAccVPCNetworkACL_ipv6Rules(t *testing.T) { func TestAccVPCNetworkACL_ipv6ICMPRules(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -532,7 +532,7 @@ func TestAccVPCNetworkACL_ipv6ICMPRules(t *testing.T) { func TestAccVPCNetworkACL_ipv6VPCRules(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -558,7 +558,7 @@ func TestAccVPCNetworkACL_ipv6VPCRules(t *testing.T) { func TestAccVPCNetworkACL_espProtocol(t *testing.T) { ctx := acctest.Context(t) - var v ec2.NetworkAcl + var v awstypes.NetworkAcl resourceName := "aws_network_acl.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -580,7 +580,7 @@ func TestAccVPCNetworkACL_espProtocol(t *testing.T) { func testAccCheckNetworkACLDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_network_acl" { @@ -604,7 +604,7 @@ func testAccCheckNetworkACLDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckNetworkACLExists(ctx context.Context, n string, v *ec2.NetworkAcl) resource.TestCheckFunc { +func testAccCheckNetworkACLExists(ctx context.Context, n string, v *awstypes.NetworkAcl) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -615,7 +615,7 @@ func testAccCheckNetworkACLExists(ctx context.Context, n string, v *ec2.NetworkA return fmt.Errorf("No EC2 Network ACL ID is set: %s", n) } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindNetworkACLByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_network_acls_data_source.go b/internal/service/ec2/vpc_network_acls_data_source.go index 7bc0a37974c..1135e2b6b61 100644 --- a/internal/service/ec2/vpc_network_acls_data_source.go +++ b/internal/service/ec2/vpc_network_acls_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_network_acls") -func DataSourceNetworkACLs() *schema.Resource { +// @SDKDataSource("aws_network_acls", name="Network ACLs") +func dataSourceNetworkACLs() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceNetworkACLsRead, @@ -44,7 +44,7 @@ func DataSourceNetworkACLs() *schema.Resource { func dataSourceNetworkACLsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeNetworkAclsInput{} @@ -68,7 +68,7 @@ func dataSourceNetworkACLsRead(ctx context.Context, d *schema.ResourceData, meta input.Filters = nil } - output, err := FindNetworkACLs(ctx, conn, input) + output, err := findNetworkACLs(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Network ACLs: %s", err) @@ -77,7 +77,7 @@ func dataSourceNetworkACLsRead(ctx context.Context, d *schema.ResourceData, meta var naclIDs []string for _, v := range output { - naclIDs = append(naclIDs, aws.StringValue(v.NetworkAclId)) + naclIDs = append(naclIDs, aws.ToString(v.NetworkAclId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_network_insights_analysis.go b/internal/service/ec2/vpc_network_insights_analysis.go index 7078ab583a0..478d055c269 100644 --- a/internal/service/ec2/vpc_network_insights_analysis.go +++ b/internal/service/ec2/vpc_network_insights_analysis.go @@ -1418,7 +1418,7 @@ func resourceNetworkInsightsAnalysisCreate(ctx context.Context, d *schema.Resour input := &ec2.StartNetworkInsightsAnalysisInput{ NetworkInsightsPathId: aws.String(d.Get("network_insights_path_id").(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeNetworkInsightsAnalysis), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeNetworkInsightsAnalysis), } if v, ok := d.GetOk("filter_in_arns"); ok && v.(*schema.Set).Len() > 0 { @@ -1479,7 +1479,7 @@ func resourceNetworkInsightsAnalysisRead(ctx context.Context, d *schema.Resource d.Set(names.AttrStatusMessage, output.StatusMessage) d.Set("warning_message", output.WarningMessage) - setTagsOutV2(ctx, output.Tags) + setTagsOut(ctx, output.Tags) return diags } diff --git a/internal/service/ec2/vpc_network_insights_analysis_data_source.go b/internal/service/ec2/vpc_network_insights_analysis_data_source.go index 6c6959e3772..10e93c30386 100644 --- a/internal/service/ec2/vpc_network_insights_analysis_data_source.go +++ b/internal/service/ec2/vpc_network_insights_analysis_data_source.go @@ -101,7 +101,7 @@ func dataSourceNetworkInsightsAnalysisRead(ctx context.Context, d *schema.Resour input.NetworkInsightsAnalysisIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -140,7 +140,7 @@ func dataSourceNetworkInsightsAnalysisRead(ctx context.Context, d *schema.Resour d.Set(names.AttrStatusMessage, output.StatusMessage) d.Set("warning_message", output.WarningMessage) - setTagsOutV2(ctx, output.Tags) + setTagsOut(ctx, output.Tags) return diags } diff --git a/internal/service/ec2/vpc_network_insights_path.go b/internal/service/ec2/vpc_network_insights_path.go index 94a4259cf78..24ea0873f9e 100644 --- a/internal/service/ec2/vpc_network_insights_path.go +++ b/internal/service/ec2/vpc_network_insights_path.go @@ -100,7 +100,7 @@ func resourceNetworkInsightsPathCreate(ctx context.Context, d *schema.ResourceDa ClientToken: aws.String(id.UniqueId()), Protocol: awstypes.Protocol(d.Get(names.AttrProtocol).(string)), Source: aws.String(d.Get(names.AttrSource).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeNetworkInsightsPath), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeNetworkInsightsPath), } if v, ok := d.GetOk(names.AttrDestination); ok { @@ -156,7 +156,7 @@ func resourceNetworkInsightsPathRead(ctx context.Context, d *schema.ResourceData d.Set("source_arn", nip.SourceArn) d.Set("source_ip", nip.SourceIp) - setTagsOutV2(ctx, nip.Tags) + setTagsOut(ctx, nip.Tags) return diags } diff --git a/internal/service/ec2/vpc_network_insights_path_data_source.go b/internal/service/ec2/vpc_network_insights_path_data_source.go index c1f503d67f9..61bb1525650 100644 --- a/internal/service/ec2/vpc_network_insights_path_data_source.go +++ b/internal/service/ec2/vpc_network_insights_path_data_source.go @@ -82,7 +82,7 @@ func dataSourceNetworkInsightsPathRead(ctx context.Context, d *schema.ResourceDa input.NetworkInsightsPathIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -110,7 +110,7 @@ func dataSourceNetworkInsightsPathRead(ctx context.Context, d *schema.ResourceDa d.Set("source_arn", nip.SourceArn) d.Set("source_ip", nip.SourceIp) - setTagsOutV2(ctx, nip.Tags) + setTagsOut(ctx, nip.Tags) return diags } diff --git a/internal/service/ec2/vpc_network_interface.go b/internal/service/ec2/vpc_network_interface.go index 4d748289e0a..4eb1ca84967 100644 --- a/internal/service/ec2/vpc_network_interface.go +++ b/internal/service/ec2/vpc_network_interface.go @@ -420,7 +420,7 @@ func resourceNetworkInterfaceCreate(ctx context.Context, d *schema.ResourceData, // If IPv4 or IPv6 prefixes are specified, tag after create. // Otherwise "An error occurred (InternalError) when calling the CreateNetworkInterface operation". if !(ipv4PrefixesSpecified || ipv6PrefixesSpecified) { - input.TagSpecifications = getTagSpecificationsInV2(ctx, types.ResourceTypeNetworkInterface) + input.TagSpecifications = getTagSpecificationsIn(ctx, types.ResourceTypeNetworkInterface) } output, err := conn.CreateNetworkInterface(ctx, input) @@ -457,7 +457,7 @@ func resourceNetworkInterfaceCreate(ctx context.Context, d *schema.ResourceData, } if ipv4PrefixesSpecified || ipv6PrefixesSpecified { - if err := createTagsV2(ctx, conn, d.Id(), getTagsInV2(ctx)); err != nil { + if err := createTags(ctx, conn, d.Id(), getTagsIn(ctx)); err != nil { return sdkdiag.AppendErrorf(diags, "setting EC2 Network Interface (%s) tags: %s", d.Id(), err) } } @@ -560,7 +560,7 @@ func resourceNetworkInterfaceRead(ctx context.Context, d *schema.ResourceData, m d.Set("source_dest_check", eni.SourceDestCheck) d.Set(names.AttrSubnetID, eni.SubnetId) - setTagsOutV2(ctx, eni.TagSet) + setTagsOut(ctx, eni.TagSet) return diags } @@ -576,7 +576,7 @@ func resourceNetworkInterfaceUpdate(ctx context.Context, d *schema.ResourceData, if oa != nil && oa.(*schema.Set).Len() > 0 { attachment := oa.(*schema.Set).List()[0].(map[string]interface{}) - if err := detachNetworkInterface(ctx, conn, d.Id(), attachment["attachment_id"].(string), NetworkInterfaceDetachedTimeout); err != nil { + if err := detachNetworkInterface(ctx, conn, d.Id(), attachment["attachment_id"].(string), networkInterfaceDetachedTimeout); err != nil { return sdkdiag.AppendFromErr(diags, err) } } @@ -1043,7 +1043,7 @@ func resourceNetworkInterfaceDelete(ctx context.Context, d *schema.ResourceData, if v, ok := d.GetOk("attachment"); ok && v.(*schema.Set).Len() > 0 { attachment := v.(*schema.Set).List()[0].(map[string]interface{}) - if err := detachNetworkInterface(ctx, conn, d.Id(), attachment["attachment_id"].(string), NetworkInterfaceDetachedTimeout); err != nil { + if err := detachNetworkInterface(ctx, conn, d.Id(), attachment["attachment_id"].(string), networkInterfaceDetachedTimeout); err != nil { return sdkdiag.AppendFromErr(diags, err) } } @@ -1457,7 +1457,7 @@ func deleteLingeringENIs(ctx context.Context, conn *ec2.Client, filterName, reso tflog.Trace(ctx, "Checking for lingering ENIs") enis, err := findNetworkInterfaces(ctx, conn, &ec2.DescribeNetworkInterfacesInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ filterName: resourceId, }), }) diff --git a/internal/service/ec2/vpc_network_interface_attachment.go b/internal/service/ec2/vpc_network_interface_attachment.go index 9c299a0b654..408f8383100 100644 --- a/internal/service/ec2/vpc_network_interface_attachment.go +++ b/internal/service/ec2/vpc_network_interface_attachment.go @@ -15,8 +15,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_network_interface_attachment") -func ResourceNetworkInterfaceAttachment() *schema.Resource { +// @SDKResource("aws_network_interface_attachment", name="Network Interface Attachment") +func resourceNetworkInterfaceAttachment() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceNetworkInterfaceAttachmentCreate, ReadWithoutTimeout: resourceNetworkInterfaceAttachmentRead, @@ -77,9 +77,9 @@ func resourceNetworkInterfaceAttachmentCreate(ctx context.Context, d *schema.Res func resourceNetworkInterfaceAttachmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - network_interface, err := FindNetworkInterfaceByAttachmentID(ctx, conn, d.Id()) + network_interface, err := findNetworkInterfaceByAttachmentID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 Network Interface Attachment (%s) not found, removing from state", d.Id()) @@ -104,7 +104,7 @@ func resourceNetworkInterfaceAttachmentDelete(ctx context.Context, d *schema.Res var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - if err := detachNetworkInterface(ctx, conn, d.Get(names.AttrNetworkInterfaceID).(string), d.Id(), NetworkInterfaceDetachedTimeout); err != nil { + if err := detachNetworkInterface(ctx, conn, d.Get(names.AttrNetworkInterfaceID).(string), d.Id(), networkInterfaceDetachedTimeout); err != nil { return sdkdiag.AppendFromErr(diags, err) } diff --git a/internal/service/ec2/vpc_network_interface_data_source.go b/internal/service/ec2/vpc_network_interface_data_source.go index 46fa290d419..fdd0a5a76cb 100644 --- a/internal/service/ec2/vpc_network_interface_data_source.go +++ b/internal/service/ec2/vpc_network_interface_data_source.go @@ -173,7 +173,7 @@ func dataSourceNetworkInterfaceRead(ctx context.Context, d *schema.ResourceData, input := &ec2.DescribeNetworkInterfacesInput{} if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } if v, ok := d.GetOk(names.AttrID); ok { @@ -225,7 +225,7 @@ func dataSourceNetworkInterfaceRead(ctx context.Context, d *schema.ResourceData, d.Set(names.AttrSubnetID, eni.SubnetId) d.Set(names.AttrVPCID, eni.VpcId) - setTagsOutV2(ctx, eni.TagSet) + setTagsOut(ctx, eni.TagSet) return diags } diff --git a/internal/service/ec2/vpc_network_interface_sg_attachment.go b/internal/service/ec2/vpc_network_interface_sg_attachment.go index 48b73ab2a5a..b5fbe800bd1 100644 --- a/internal/service/ec2/vpc_network_interface_sg_attachment.go +++ b/internal/service/ec2/vpc_network_interface_sg_attachment.go @@ -10,9 +10,10 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -21,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_network_interface_sg_attachment") -func ResourceNetworkInterfaceSGAttachment() *schema.Resource { +// @SDKResource("aws_network_interface_sg_attachment", name="Network Interface SG Attachement") +func resourceNetworkInterfaceSGAttachment() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceNetworkInterfaceSGAttachmentCreate, ReadWithoutTimeout: resourceNetworkInterfaceSGAttachmentRead, @@ -55,7 +56,7 @@ func ResourceNetworkInterfaceSGAttachment() *schema.Resource { func resourceNetworkInterfaceSGAttachmentCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) networkInterfaceID := d.Get(names.AttrNetworkInterfaceID).(string) sgID := d.Get("security_group_id").(string) @@ -63,7 +64,7 @@ func resourceNetworkInterfaceSGAttachmentCreate(ctx context.Context, d *schema.R conns.GlobalMutexKV.Lock(mutexKey) defer conns.GlobalMutexKV.Unlock(mutexKey) - eni, err := FindNetworkInterfaceByID(ctx, conn, networkInterfaceID) + eni, err := findNetworkInterfaceByID(ctx, conn, networkInterfaceID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Network Interface (%s): %s", networkInterfaceID, err) @@ -72,11 +73,7 @@ func resourceNetworkInterfaceSGAttachmentCreate(ctx context.Context, d *schema.R groupIDs := []string{sgID} for _, group := range eni.Groups { - if group == nil { - continue - } - - groupID := aws.StringValue(group.GroupId) + groupID := aws.ToString(group.GroupId) if groupID == sgID { return sdkdiag.AppendErrorf(diags, "EC2 Security Group (%s) already attached to EC2 Network Interface (%s)", sgID, networkInterfaceID) @@ -87,11 +84,11 @@ func resourceNetworkInterfaceSGAttachmentCreate(ctx context.Context, d *schema.R input := &ec2.ModifyNetworkInterfaceAttributeInput{ NetworkInterfaceId: aws.String(networkInterfaceID), - Groups: aws.StringSlice(groupIDs), + Groups: groupIDs, } - log.Printf("[INFO] Modifying EC2 Network Interface: %s", input) - _, err = conn.ModifyNetworkInterfaceAttributeWithContext(ctx, input) + log.Printf("[INFO] Modifying EC2 Network Interface: %#v", input) + _, err = conn.ModifyNetworkInterfaceAttribute(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "modifying EC2 Network Interface (%s): %s", networkInterfaceID, err) @@ -104,12 +101,12 @@ func resourceNetworkInterfaceSGAttachmentCreate(ctx context.Context, d *schema.R func resourceNetworkInterfaceSGAttachmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) networkInterfaceID := d.Get(names.AttrNetworkInterfaceID).(string) sgID := d.Get("security_group_id").(string) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, maxDuration(ec2PropagationTimeout, d.Timeout(schema.TimeoutRead)), func() (interface{}, error) { - return FindNetworkInterfaceSecurityGroup(ctx, conn, networkInterfaceID, sgID) + return findNetworkInterfaceSecurityGroup(ctx, conn, networkInterfaceID, sgID) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -122,7 +119,7 @@ func resourceNetworkInterfaceSGAttachmentRead(ctx context.Context, d *schema.Res return sdkdiag.AppendErrorf(diags, "reading EC2 Network Interface (%s) Security Group (%s) Attachment: %s", networkInterfaceID, sgID, err) } - groupIdentifier := outputRaw.(*ec2.GroupIdentifier) + groupIdentifier := outputRaw.(*awstypes.GroupIdentifier) d.Set(names.AttrNetworkInterfaceID, networkInterfaceID) d.Set("security_group_id", groupIdentifier.GroupId) @@ -140,7 +137,7 @@ func maxDuration(a, b time.Duration) time.Duration { func resourceNetworkInterfaceSGAttachmentDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) networkInterfaceID := d.Get(names.AttrNetworkInterfaceID).(string) sgID := d.Get("security_group_id").(string) @@ -148,7 +145,7 @@ func resourceNetworkInterfaceSGAttachmentDelete(ctx context.Context, d *schema.R conns.GlobalMutexKV.Lock(mutexKey) defer conns.GlobalMutexKV.Unlock(mutexKey) - eni, err := FindNetworkInterfaceByID(ctx, conn, networkInterfaceID) + eni, err := findNetworkInterfaceByID(ctx, conn, networkInterfaceID) if tfresource.NotFound(err) { return diags @@ -161,11 +158,7 @@ func resourceNetworkInterfaceSGAttachmentDelete(ctx context.Context, d *schema.R groupIDs := []string{} for _, group := range eni.Groups { - if group == nil { - continue - } - - groupID := aws.StringValue(group.GroupId) + groupID := aws.ToString(group.GroupId) if groupID == sgID { continue @@ -176,11 +169,11 @@ func resourceNetworkInterfaceSGAttachmentDelete(ctx context.Context, d *schema.R input := &ec2.ModifyNetworkInterfaceAttributeInput{ NetworkInterfaceId: aws.String(networkInterfaceID), - Groups: aws.StringSlice(groupIDs), + Groups: groupIDs, } - log.Printf("[INFO] Modifying EC2 Network Interface: %s", input) - _, err = conn.ModifyNetworkInterfaceAttributeWithContext(ctx, input) + log.Printf("[INFO] Modifying EC2 Network Interface: %#v", input) + _, err = conn.ModifyNetworkInterfaceAttribute(ctx, input) if tfawserr.ErrCodeEquals(err, errCodeInvalidNetworkInterfaceIDNotFound) { return diags @@ -204,9 +197,9 @@ func resourceNetworkInterfaceSGAttachmentImport(ctx context.Context, d *schema.R log.Printf("[DEBUG] Importing network interface security group association, Interface: %s, Security Group: %s", networkInterfaceID, securityGroupID) - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - networkInterface, err := FindNetworkInterfaceByID(ctx, conn, networkInterfaceID) + networkInterface, err := findNetworkInterfaceByID(ctx, conn, networkInterfaceID) if err != nil { return nil, err @@ -215,7 +208,7 @@ func resourceNetworkInterfaceSGAttachmentImport(ctx context.Context, d *schema.R var associationID string for _, attachedSecurityGroup := range networkInterface.Groups { - if aws.StringValue(attachedSecurityGroup.GroupId) == securityGroupID { + if aws.ToString(attachedSecurityGroup.GroupId) == securityGroupID { d.Set("security_group_id", securityGroupID) associationID = securityGroupID + "_" + networkInterfaceID diff --git a/internal/service/ec2/vpc_network_interface_sg_attachment_test.go b/internal/service/ec2/vpc_network_interface_sg_attachment_test.go index ff784529819..d0f6aa5b912 100644 --- a/internal/service/ec2/vpc_network_interface_sg_attachment_test.go +++ b/internal/service/ec2/vpc_network_interface_sg_attachment_test.go @@ -148,7 +148,7 @@ func testAccCheckNetworkInterfaceSGAttachmentExists(ctx context.Context, resourc return fmt.Errorf("No EC2 Network Interface Security Group Attachment ID is set: %s", resourceName) } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) _, err := tfec2.FindNetworkInterfaceSecurityGroup(ctx, conn, rs.Primary.Attributes[names.AttrNetworkInterfaceID], rs.Primary.Attributes["security_group_id"]) @@ -158,7 +158,7 @@ func testAccCheckNetworkInterfaceSGAttachmentExists(ctx context.Context, resourc func testAccCheckNetworkInterfaceSGAttachmentDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_network_interface_sg_attachment" { diff --git a/internal/service/ec2/vpc_network_interface_test.go b/internal/service/ec2/vpc_network_interface_test.go index 1944ed1c639..060faa137b0 100644 --- a/internal/service/ec2/vpc_network_interface_test.go +++ b/internal/service/ec2/vpc_network_interface_test.go @@ -41,7 +41,7 @@ func TestAccVPCNetworkInterface_basic(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), acctest.MatchResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", regexache.MustCompile(`network-interface/.+$`)), resource.TestCheckResourceAttr(resourceName, "attachment.#", acctest.Ct0), resource.TestCheckResourceAttr(resourceName, names.AttrDescription, ""), @@ -85,7 +85,7 @@ func TestAccVPCNetworkInterface_ipv6(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "ipv6_addresses.#", acctest.Ct1), ), @@ -99,7 +99,7 @@ func TestAccVPCNetworkInterface_ipv6(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6Multiple(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct2), resource.TestCheckResourceAttr(resourceName, "ipv6_addresses.#", acctest.Ct2), ), @@ -107,7 +107,7 @@ func TestAccVPCNetworkInterface_ipv6(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "ipv6_addresses.#", acctest.Ct1), ), @@ -131,7 +131,7 @@ func TestAccVPCNetworkInterface_tags(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_tags1(rName, acctest.CtKey1, acctest.CtValue1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct1), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey1, acctest.CtValue1), ), @@ -145,7 +145,7 @@ func TestAccVPCNetworkInterface_tags(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_tags2(rName, acctest.CtKey1, acctest.CtValue1Updated, acctest.CtKey2, acctest.CtValue2), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct2), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey1, acctest.CtValue1Updated), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey2, acctest.CtValue2), @@ -154,7 +154,7 @@ func TestAccVPCNetworkInterface_tags(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_tags1(rName, acctest.CtKey2, acctest.CtValue2), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct1), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsKey2, acctest.CtValue2), ), @@ -178,7 +178,7 @@ func TestAccVPCNetworkInterface_ipv6Count(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct1), ), }, @@ -191,21 +191,21 @@ func TestAccVPCNetworkInterface_ipv6Count(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct2), ), }, { Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 0), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct0), ), }, { Config: testAccVPCNetworkInterfaceConfig_ipv6Count(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_address_count", acctest.Ct1), ), }, @@ -228,7 +228,7 @@ func TestAccVPCNetworkInterface_disappears(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceNetworkInterface(), resourceName), ), ExpectNonEmptyPlan: true, @@ -254,7 +254,7 @@ func TestAccVPCNetworkInterface_description(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_description(rName, "description 1"), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "attachment.#", acctest.Ct0), resource.TestCheckResourceAttr(resourceName, names.AttrDescription, "description 1"), resource.TestCheckResourceAttr(resourceName, "interface_type", "interface"), @@ -283,7 +283,7 @@ func TestAccVPCNetworkInterface_description(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_description(rName, "description 2"), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "attachment.#", acctest.Ct0), resource.TestCheckResourceAttr(resourceName, names.AttrDescription, "description 2"), resource.TestCheckResourceAttr(resourceName, "interface_type", "interface"), @@ -326,7 +326,7 @@ func TestAccVPCNetworkInterface_attachment(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_attachment(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "attachment.#", acctest.Ct1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "attachment.*", map[string]string{ "device_index": acctest.Ct1, @@ -349,6 +349,7 @@ func TestAccVPCNetworkInterface_attachment(t *testing.T) { func TestAccVPCNetworkInterface_ignoreExternalAttachment(t *testing.T) { ctx := acctest.Context(t) var conf types.NetworkInterface + var attachmentId string resourceName := "aws_network_interface.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -361,8 +362,8 @@ func TestAccVPCNetworkInterface_ignoreExternalAttachment(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_externalAttachment(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), - testAccCheckENIMakeExternalAttachment(ctx, "aws_instance.test", &conf), + testAccCheckENIExists(ctx, resourceName, &conf), + testAccCheckENIMakeExternalAttachment(ctx, "aws_instance.test", &conf, &attachmentId), ), }, { @@ -375,6 +376,13 @@ func TestAccVPCNetworkInterface_ignoreExternalAttachment(t *testing.T) { "private_ip_list_enabled", }, }, + { + Config: testAccVPCNetworkInterfaceConfig_externalAttachment(rName), + Check: resource.ComposeTestCheckFunc( + // Detach the external network interface attachment for the post-destroy to be able to the delete network interface + testAccCheckENIRemoveExternalAttachment(ctx, &attachmentId), + ), + }, }, }) } @@ -394,7 +402,7 @@ func TestAccVPCNetworkInterface_sourceDestCheck(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName, false), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "source_dest_check", acctest.CtFalse), ), }, @@ -407,14 +415,14 @@ func TestAccVPCNetworkInterface_sourceDestCheck(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName, true), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "source_dest_check", acctest.CtTrue), ), }, { Config: testAccVPCNetworkInterfaceConfig_sourceDestCheck(rName, false), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "source_dest_check", acctest.CtFalse), ), }, @@ -437,7 +445,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", acctest.Ct1), ), }, @@ -450,7 +458,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", acctest.Ct2), ), }, @@ -463,7 +471,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 0), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", acctest.Ct0), ), }, @@ -476,7 +484,7 @@ func TestAccVPCNetworkInterface_privateIPsCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_privateIPsCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "private_ips_count", acctest.Ct1), ), }, @@ -505,7 +513,7 @@ func TestAccVPCNetworkInterface_ENIInterfaceType_efa(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_type(rName, "efa"), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "interface_type", "efa"), ), }, @@ -534,7 +542,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4Prefix(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv4Prefix(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "ipv4_prefixes.#", acctest.Ct1), ), @@ -548,7 +556,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4Prefix(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixMultiple(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct2), resource.TestCheckResourceAttr(resourceName, "ipv4_prefixes.#", acctest.Ct2), ), @@ -556,7 +564,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4Prefix(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv4Prefix(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "ipv4_prefixes.#", acctest.Ct1), ), @@ -580,7 +588,7 @@ func TestAccVPCNetworkInterface_ENI_ipv4PrefixCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct1), ), }, @@ -593,21 +601,21 @@ func TestAccVPCNetworkInterface_ENI_ipv4PrefixCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct2), ), }, { Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 0), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct0), ), }, { Config: testAccVPCNetworkInterfaceConfig_ipv4PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv4_prefix_count", acctest.Ct1), ), }, @@ -630,7 +638,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6Prefix(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6Prefix(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "ipv6_prefixes.#", acctest.Ct1), ), @@ -644,7 +652,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6Prefix(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixMultiple(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct2), resource.TestCheckResourceAttr(resourceName, "ipv6_prefixes.#", acctest.Ct2), ), @@ -652,7 +660,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6Prefix(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6Prefix(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct1), resource.TestCheckResourceAttr(resourceName, "ipv6_prefixes.#", acctest.Ct1), ), @@ -676,7 +684,7 @@ func TestAccVPCNetworkInterface_ENI_ipv6PrefixCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct1), ), }, @@ -689,21 +697,21 @@ func TestAccVPCNetworkInterface_ENI_ipv6PrefixCount(t *testing.T) { { Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 2), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct2), ), }, { Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 0), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct0), ), }, { Config: testAccVPCNetworkInterfaceConfig_ipv6PrefixCount(rName, 1), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &conf), + testAccCheckENIExists(ctx, resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "ipv6_prefix_count", acctest.Ct1), ), }, @@ -726,9 +734,9 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { { // Configuration with three private_ips Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}, &networkInterface), - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { @@ -740,63 +748,63 @@ func TestAccVPCNetworkInterface_privateIPSet(t *testing.T) { { // Change order of private_ips Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.44", "172.16.10.59"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Add secondaries to private_ips Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.12", "172.16.10.44", "172.16.10.59"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.12", "172.16.10.59", "172.16.10.123"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Remove secondary to private_ips Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.44", "172.16.10.59"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.59", "172.16.10.123"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Remove primary Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.57"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.57", "172.16.10.59", "172.16.10.123"}, &networkInterface), testAccCheckENIDifferent(&lastInterface, &networkInterface), // different - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Use count to add IPs Config: testAccVPCNetworkInterfaceConfig_privateIPSetCount(rName, 4), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Change list, retain primary Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.44", "172.16.10.57"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.44", "172.16.10.57"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // New list Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17"}, &networkInterface), testAccCheckENIDifferent(&lastInterface, &networkInterface), // different - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, }, @@ -822,9 +830,9 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { { // Build a set incrementally in order Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17"}, &networkInterface), - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { @@ -836,117 +844,117 @@ func TestAccVPCNetworkInterface_privateIPList(t *testing.T) { { // Add to set Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17", "172.16.10.45"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Add to set Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17", "172.16.10.45", "172.16.10.89"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Add to set Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Change from set to list using same order Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.45", "172.16.10.89", "172.16.10.122"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Change order of private_ip_list Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.122"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.122"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Remove secondaries from end Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.45"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Add secondaries to end Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.45", "172.16.10.123"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Add secondaries to middle Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.77", "172.16.10.45", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.77", "172.16.10.45", "172.16.10.123"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Remove secondaries from middle Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.17", "172.16.10.89", "172.16.10.123"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.17", "172.16.10.89", "172.16.10.123"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Use count to add IPs Config: testAccVPCNetworkInterfaceConfig_privateIPSetCount(rName, 4), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Change to specific list - forces new Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.59", "172.16.10.123", "172.16.10.38"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.59", "172.16.10.123", "172.16.10.38"}, &networkInterface), testAccCheckENIDifferent(&lastInterface, &networkInterface), // different - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Change first of private_ip_list - forces new Config: testAccVPCNetworkInterfaceConfig_privateIPList(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPList([]string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}, &networkInterface), testAccCheckENIDifferent(&lastInterface, &networkInterface), // different - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, { // Change from list to set using same set Config: testAccVPCNetworkInterfaceConfig_privateIPSet(rName, []string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}), Check: resource.ComposeTestCheckFunc( - testAccCheckENIExistsV2(ctx, resourceName, &networkInterface), + testAccCheckENIExists(ctx, resourceName, &networkInterface), testAccCheckENIPrivateIPSet([]string{"172.16.10.123", "172.16.10.59", "172.16.10.38"}, &networkInterface), testAccCheckENISame(&lastInterface, &networkInterface), // same - testAccCheckENIExistsV2(ctx, resourceName, &lastInterface), + testAccCheckENIExists(ctx, resourceName, &lastInterface), ), }, }, @@ -977,27 +985,6 @@ func regionalPrivateDNSSuffix(region string) string { } func testAccCheckENIExists(ctx context.Context, n string, v *types.NetworkInterface) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - - output, err := tfec2.FindNetworkInterfaceByIDV2(ctx, conn, rs.Primary.ID) - - if err != nil { - return err - } - - *v = *output - - return nil - } -} - -func testAccCheckENIExistsV2(ctx context.Context, n string, v *types.NetworkInterface) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -1010,7 +997,7 @@ func testAccCheckENIExistsV2(ctx context.Context, n string, v *types.NetworkInte conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindNetworkInterfaceByIDV2(ctx, conn, rs.Primary.ID) + output, err := tfec2.FindNetworkInterfaceByID(ctx, conn, rs.Primary.ID) if err != nil { return err @@ -1031,7 +1018,7 @@ func testAccCheckENIDestroy(ctx context.Context) resource.TestCheckFunc { continue } - _, err := tfec2.FindNetworkInterfaceByIDV2(ctx, conn, rs.Primary.ID) + _, err := tfec2.FindNetworkInterfaceByID(ctx, conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -1048,7 +1035,7 @@ func testAccCheckENIDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckENIMakeExternalAttachment(ctx context.Context, n string, networkInterface *types.NetworkInterface) resource.TestCheckFunc { +func testAccCheckENIMakeExternalAttachment(ctx context.Context, n string, networkInterface *types.NetworkInterface, attachmentId *string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok || rs.Primary.ID == "" { @@ -1061,7 +1048,8 @@ func testAccCheckENIMakeExternalAttachment(ctx context.Context, n string, networ NetworkInterfaceId: networkInterface.NetworkInterfaceId, } - _, err := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx).AttachNetworkInterface(ctx, input) + output, err := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx).AttachNetworkInterface(ctx, input) + *attachmentId = *output.AttachmentId if err != nil { return fmt.Errorf("error attaching ENI: %w", err) @@ -1070,6 +1058,21 @@ func testAccCheckENIMakeExternalAttachment(ctx context.Context, n string, networ } } +func testAccCheckENIRemoveExternalAttachment(ctx context.Context, attachmentId *string) resource.TestCheckFunc { + return func(s *terraform.State) error { + input := &ec2.DetachNetworkInterfaceInput{ + AttachmentId: attachmentId, + } + + _, err := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx).DetachNetworkInterface(ctx, input) + + if err != nil { + return fmt.Errorf("error detaching ENI: %w", err) + } + return nil + } +} + func testAccCheckENIPrivateIPSet(ips []string, iface *types.NetworkInterface) resource.TestCheckFunc { return func(s *terraform.State) error { iIPs := tfec2.FlattenNetworkInterfacePrivateIPAddresses(iface.PrivateIpAddresses) diff --git a/internal/service/ec2/vpc_network_interfaces_data_source.go b/internal/service/ec2/vpc_network_interfaces_data_source.go index 7972b59ace3..c5e70609641 100644 --- a/internal/service/ec2/vpc_network_interfaces_data_source.go +++ b/internal/service/ec2/vpc_network_interfaces_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_network_interfaces") -func DataSourceNetworkInterfaces() *schema.Resource { +// @SDKDataSource("aws_network_interfaces", name="Network Interfaces") +func dataSourceNetworkInterfaces() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceNetworkInterfacesRead, @@ -40,7 +40,7 @@ func DataSourceNetworkInterfaces() *schema.Resource { func dataSourceNetworkInterfacesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeNetworkInterfacesInput{} @@ -58,14 +58,14 @@ func dataSourceNetworkInterfacesRead(ctx context.Context, d *schema.ResourceData networkInterfaceIDs := []string{} - output, err := FindNetworkInterfaces(ctx, conn, input) + output, err := findNetworkInterfaces(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Network Interfaces: %s", err) } for _, v := range output { - networkInterfaceIDs = append(networkInterfaceIDs, aws.StringValue(v.NetworkInterfaceId)) + networkInterfaceIDs = append(networkInterfaceIDs, aws.ToString(v.NetworkInterfaceId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_network_performance_metric_subscription.go b/internal/service/ec2/vpc_network_performance_metric_subscription.go index 6be117e88fe..49e98ab9486 100644 --- a/internal/service/ec2/vpc_network_performance_metric_subscription.go +++ b/internal/service/ec2/vpc_network_performance_metric_subscription.go @@ -21,8 +21,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_vpc_network_performance_metric_subscription") -func ResourceNetworkPerformanceMetricSubscription() *schema.Resource { +// @SDKResource("aws_vpc_network_performance_metric_subscription", name="VPC Network Performance Metric Subscription") +func resourceNetworkPerformanceMetricSubscription() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceNetworkPerformanceMetricSubscriptionCreate, ReadWithoutTimeout: resourceNetworkPerformanceMetricSubscriptionRead, @@ -63,14 +63,13 @@ func ResourceNetworkPerformanceMetricSubscription() *schema.Resource { func resourceNetworkPerformanceMetricSubscriptionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) source := d.Get(names.AttrSource).(string) destination := d.Get(names.AttrDestination).(string) metric := d.Get("metric").(string) statistic := d.Get("statistic").(string) - id := NetworkPerformanceMetricSubscriptionCreateResourceID(source, destination, metric, statistic) + id := networkPerformanceMetricSubscriptionCreateResourceID(source, destination, metric, statistic) input := &ec2.EnableAwsNetworkPerformanceMetricSubscriptionInput{ Destination: aws.String(destination), Metric: types.MetricType(metric), @@ -91,11 +90,9 @@ func resourceNetworkPerformanceMetricSubscriptionCreate(ctx context.Context, d * func resourceNetworkPerformanceMetricSubscriptionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - source, destination, metric, statistic, err := NetworkPerformanceMetricSubscriptionResourceID(d.Id()) - + source, destination, metric, statistic, err := networkPerformanceMetricSubscriptionParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -123,11 +120,9 @@ func resourceNetworkPerformanceMetricSubscriptionRead(ctx context.Context, d *sc func resourceNetworkPerformanceMetricSubscriptionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Client(ctx) - source, destination, metric, statistic, err := NetworkPerformanceMetricSubscriptionResourceID(d.Id()) - + source, destination, metric, statistic, err := networkPerformanceMetricSubscriptionParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -149,14 +144,14 @@ func resourceNetworkPerformanceMetricSubscriptionDelete(ctx context.Context, d * const networkPerformanceMetricSubscriptionRuleIDSeparator = "/" -func NetworkPerformanceMetricSubscriptionCreateResourceID(source, destination, metric, statistic string) string { +func networkPerformanceMetricSubscriptionCreateResourceID(source, destination, metric, statistic string) string { parts := []string{source, destination, metric, statistic} id := strings.Join(parts, networkPerformanceMetricSubscriptionRuleIDSeparator) return id } -func NetworkPerformanceMetricSubscriptionResourceID(id string) (string, string, string, string, error) { +func networkPerformanceMetricSubscriptionParseResourceID(id string) (string, string, string, string, error) { parts := strings.Split(id, networkPerformanceMetricSubscriptionRuleIDSeparator) if len(parts) == 4 && parts[0] != "" && parts[1] != "" && parts[2] != "" && parts[3] != "" { diff --git a/internal/service/ec2/vpc_network_performance_metric_subscription_test.go b/internal/service/ec2/vpc_network_performance_metric_subscription_test.go index 542dd8c2bca..44a0877d467 100644 --- a/internal/service/ec2/vpc_network_performance_metric_subscription_test.go +++ b/internal/service/ec2/vpc_network_performance_metric_subscription_test.go @@ -85,19 +85,10 @@ func testAccCheckNetworkPerformanceMetricSubscriptionExists(ctx context.Context, if !ok { return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 AWS Network Performance Metric Subscription ID is set") - } - - source, destination, metric, statistic, err := tfec2.NetworkPerformanceMetricSubscriptionResourceID(rs.Primary.ID) - - if err != nil { - return err - } conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - _, err = tfec2.FindNetworkPerformanceMetricSubscriptionByFourPartKey(ctx, conn, source, destination, metric, statistic) + _, err := tfec2.FindNetworkPerformanceMetricSubscriptionByFourPartKey(ctx, conn, rs.Primary.Attributes[names.AttrSource], rs.Primary.Attributes[names.AttrDestination], rs.Primary.Attributes["metric"], rs.Primary.Attributes["statistic"]) return err } @@ -112,13 +103,7 @@ func testAccCheckNetworkPerformanceMetricSubscriptionDestroy(ctx context.Context continue } - source, destination, metric, statistic, err := tfec2.NetworkPerformanceMetricSubscriptionResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindNetworkPerformanceMetricSubscriptionByFourPartKey(ctx, conn, source, destination, metric, statistic) + _, err := tfec2.FindNetworkPerformanceMetricSubscriptionByFourPartKey(ctx, conn, rs.Primary.Attributes[names.AttrSource], rs.Primary.Attributes[names.AttrDestination], rs.Primary.Attributes["metric"], rs.Primary.Attributes["statistic"]) if tfresource.NotFound(err) { continue diff --git a/internal/service/ec2/vpc_peering_connection.go b/internal/service/ec2/vpc_peering_connection.go index ae41366eecc..fa5fcf69f46 100644 --- a/internal/service/ec2/vpc_peering_connection.go +++ b/internal/service/ec2/vpc_peering_connection.go @@ -10,9 +10,10 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -27,7 +28,7 @@ import ( // @SDKResource("aws_vpc_peering_connection", name="VPC Peering Connection") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVPCPeeringConnection() *schema.Resource { +func resourceVPCPeeringConnection() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCPeeringConnectionCreate, ReadWithoutTimeout: resourceVPCPeeringConnectionRead, @@ -104,11 +105,11 @@ var vpcPeeringConnectionOptionsSchema = &schema.Schema{ func resourceVPCPeeringConnectionCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateVpcPeeringConnectionInput{ PeerVpcId: aws.String(d.Get("peer_vpc_id").(string)), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeVpcPeeringConnection), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVpcPeeringConnection), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -124,22 +125,22 @@ func resourceVPCPeeringConnectionCreate(ctx context.Context, d *schema.ResourceD input.PeerRegion = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating EC2 VPC Peering Connection: %s", input) - output, err := conn.CreateVpcPeeringConnectionWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 VPC Peering Connection: %#v", input) + output, err := conn.CreateVpcPeeringConnection(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 VPC Peering Connection: %s", err) } - d.SetId(aws.StringValue(output.VpcPeeringConnection.VpcPeeringConnectionId)) + d.SetId(aws.ToString(output.VpcPeeringConnection.VpcPeeringConnectionId)) - vpcPeeringConnection, err := WaitVPCPeeringConnectionActive(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) + vpcPeeringConnection, err := waitVPCPeeringConnectionActive(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 VPC Peering Connection (%s) create: %s", d.Id(), err) } - if _, ok := d.GetOk("auto_accept"); ok && aws.StringValue(vpcPeeringConnection.Status.Code) == ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance { + if _, ok := d.GetOk("auto_accept"); ok && vpcPeeringConnection.Status.Code == awstypes.VpcPeeringConnectionStateReasonCodePendingAcceptance { vpcPeeringConnection, err = acceptVPCPeeringConnection(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { @@ -156,9 +157,9 @@ func resourceVPCPeeringConnectionCreate(ctx context.Context, d *schema.ResourceD func resourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, d.Id()) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VPC Peering Connection %s not found, removing from state", d.Id()) @@ -173,7 +174,7 @@ func resourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceDat d.Set("accept_status", vpcPeeringConnection.Status.Code) d.Set("peer_region", vpcPeeringConnection.AccepterVpcInfo.Region) - if accountID := meta.(*conns.AWSClient).AccountID; accountID == aws.StringValue(vpcPeeringConnection.AccepterVpcInfo.OwnerId) && accountID != aws.StringValue(vpcPeeringConnection.RequesterVpcInfo.OwnerId) { + if accountID := meta.(*conns.AWSClient).AccountID; accountID == aws.ToString(vpcPeeringConnection.AccepterVpcInfo.OwnerId) && accountID != aws.ToString(vpcPeeringConnection.RequesterVpcInfo.OwnerId) { // We're the accepter. d.Set("peer_owner_id", vpcPeeringConnection.RequesterVpcInfo.OwnerId) d.Set("peer_vpc_id", vpcPeeringConnection.RequesterVpcInfo.VpcId) @@ -208,15 +209,15 @@ func resourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceDat func resourceVPCPeeringConnectionUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, d.Id()) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC Peering Connection (%s): %s", d.Id(), err) } - if _, ok := d.GetOk("auto_accept"); ok && aws.StringValue(vpcPeeringConnection.Status.Code) == ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance { + if _, ok := d.GetOk("auto_accept"); ok && vpcPeeringConnection.Status.Code == awstypes.VpcPeeringConnectionStateReasonCodePendingAcceptance { vpcPeeringConnection, err = acceptVPCPeeringConnection(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { @@ -235,10 +236,10 @@ func resourceVPCPeeringConnectionUpdate(ctx context.Context, d *schema.ResourceD func resourceVPCPeeringConnectionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting EC2 VPC Peering Connection: %s", d.Id()) - _, err := conn.DeleteVpcPeeringConnectionWithContext(ctx, &ec2.DeleteVpcPeeringConnectionInput{ + _, err := conn.DeleteVpcPeeringConnection(ctx, &ec2.DeleteVpcPeeringConnectionInput{ VpcPeeringConnectionId: aws.String(d.Id()), }) @@ -255,16 +256,16 @@ func resourceVPCPeeringConnectionDelete(ctx context.Context, d *schema.ResourceD return sdkdiag.AppendErrorf(diags, "deleting EC2 VPC Peering Connection (%s): %s", d.Id(), err) } - if _, err := WaitVPCPeeringConnectionDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { + if _, err := waitVPCPeeringConnectionDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 VPC Peering Connection (%s) delete: %s", d.Id(), err) } return diags } -func acceptVPCPeeringConnection(ctx context.Context, conn *ec2.EC2, vpcPeeringConnectionID string, timeout time.Duration) (*ec2.VpcPeeringConnection, error) { +func acceptVPCPeeringConnection(ctx context.Context, conn *ec2.Client, vpcPeeringConnectionID string, timeout time.Duration) (*awstypes.VpcPeeringConnection, error) { log.Printf("[INFO] Accepting EC2 VPC Peering Connection: %s", vpcPeeringConnectionID) - _, err := conn.AcceptVpcPeeringConnectionWithContext(ctx, &ec2.AcceptVpcPeeringConnectionInput{ + _, err := conn.AcceptVpcPeeringConnection(ctx, &ec2.AcceptVpcPeeringConnectionInput{ VpcPeeringConnectionId: aws.String(vpcPeeringConnectionID), }) @@ -273,7 +274,7 @@ func acceptVPCPeeringConnection(ctx context.Context, conn *ec2.EC2, vpcPeeringCo } // "OperationNotPermitted: Peering pcx-0000000000000000 is not active. Peering options can be added only to active peerings." - vpcPeeringConnection, err := WaitVPCPeeringConnectionActive(ctx, conn, vpcPeeringConnectionID, timeout) + vpcPeeringConnection, err := waitVPCPeeringConnectionActive(ctx, conn, vpcPeeringConnectionID, timeout) if err != nil { return nil, fmt.Errorf("accepting EC2 VPC Peering Connection (%s): waiting for completion: %w", vpcPeeringConnectionID, err) @@ -282,8 +283,8 @@ func acceptVPCPeeringConnection(ctx context.Context, conn *ec2.EC2, vpcPeeringCo return vpcPeeringConnection, nil } -func modifyVPCPeeringConnectionOptions(ctx context.Context, conn *ec2.EC2, d *schema.ResourceData, vpcPeeringConnection *ec2.VpcPeeringConnection, checkActive bool) error { - var accepterPeeringConnectionOptions, requesterPeeringConnectionOptions *ec2.PeeringConnectionOptionsRequest +func modifyVPCPeeringConnectionOptions(ctx context.Context, conn *ec2.Client, d *schema.ResourceData, vpcPeeringConnection *awstypes.VpcPeeringConnection, checkActive bool) error { + var accepterPeeringConnectionOptions, requesterPeeringConnectionOptions *awstypes.PeeringConnectionOptionsRequest if key := "accepter"; d.HasChange(key) { if v, ok := d.GetOk(key); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { @@ -302,8 +303,8 @@ func modifyVPCPeeringConnectionOptions(ctx context.Context, conn *ec2.EC2, d *sc } if checkActive { - switch statusCode := aws.StringValue(vpcPeeringConnection.Status.Code); statusCode { - case ec2.VpcPeeringConnectionStateReasonCodeActive, ec2.VpcPeeringConnectionStateReasonCodeProvisioning: + switch statusCode := vpcPeeringConnection.Status.Code; statusCode { + case awstypes.VpcPeeringConnectionStateReasonCodeActive, awstypes.VpcPeeringConnectionStateReasonCodeProvisioning: default: return fmt.Errorf( "Unable to modify EC2 VPC Peering Connection Options. EC2 VPC Peering Connection (%s) is not active (current status: %s). "+ @@ -318,15 +319,15 @@ func modifyVPCPeeringConnectionOptions(ctx context.Context, conn *ec2.EC2, d *sc VpcPeeringConnectionId: aws.String(d.Id()), } - log.Printf("[DEBUG] Modifying VPC Peering Connection Options: %s", input) - if _, err := conn.ModifyVpcPeeringConnectionOptionsWithContext(ctx, input); err != nil { + log.Printf("[DEBUG] Modifying VPC Peering Connection Options: %#v", input) + if _, err := conn.ModifyVpcPeeringConnectionOptions(ctx, input); err != nil { return fmt.Errorf("modifying EC2 VPC Peering Connection (%s) Options: %w", d.Id(), err) } // Retry reading back the modified options to deal with eventual consistency. // Often this is to do with a delay transitioning from pending-acceptance to active. err := retry.RetryContext(ctx, ec2PropagationTimeout, func() *retry.RetryError { // nosemgrep:ci.helper-schema-retry-RetryContext-without-TimeoutError-check - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, d.Id()) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, d.Id()) if err != nil { return retry.NonRetryableError(err) @@ -354,16 +355,16 @@ func modifyVPCPeeringConnectionOptions(ctx context.Context, conn *ec2.EC2, d *sc return nil } -func vpcPeeringConnectionOptionsEqual(o1 *ec2.VpcPeeringConnectionOptionsDescription, o2 *ec2.PeeringConnectionOptionsRequest) bool { - return aws.BoolValue(o1.AllowDnsResolutionFromRemoteVpc) == aws.BoolValue(o2.AllowDnsResolutionFromRemoteVpc) +func vpcPeeringConnectionOptionsEqual(o1 *awstypes.VpcPeeringConnectionOptionsDescription, o2 *awstypes.PeeringConnectionOptionsRequest) bool { + return aws.ToBool(o1.AllowDnsResolutionFromRemoteVpc) == aws.ToBool(o2.AllowDnsResolutionFromRemoteVpc) } -func expandPeeringConnectionOptionsRequest(tfMap map[string]interface{}) *ec2.PeeringConnectionOptionsRequest { +func expandPeeringConnectionOptionsRequest(tfMap map[string]interface{}) *awstypes.PeeringConnectionOptionsRequest { if tfMap == nil { return nil } - apiObject := &ec2.PeeringConnectionOptionsRequest{} + apiObject := &awstypes.PeeringConnectionOptionsRequest{} if v, ok := tfMap["allow_remote_vpc_dns_resolution"].(bool); ok { apiObject.AllowDnsResolutionFromRemoteVpc = aws.Bool(v) @@ -372,7 +373,7 @@ func expandPeeringConnectionOptionsRequest(tfMap map[string]interface{}) *ec2.Pe return apiObject } -func flattenVPCPeeringConnectionOptionsDescription(apiObject *ec2.VpcPeeringConnectionOptionsDescription) map[string]interface{} { +func flattenVPCPeeringConnectionOptionsDescription(apiObject *awstypes.VpcPeeringConnectionOptionsDescription) map[string]interface{} { if apiObject == nil { return nil } @@ -380,7 +381,7 @@ func flattenVPCPeeringConnectionOptionsDescription(apiObject *ec2.VpcPeeringConn tfMap := map[string]interface{}{} if v := apiObject.AllowDnsResolutionFromRemoteVpc; v != nil { - tfMap["allow_remote_vpc_dns_resolution"] = aws.BoolValue(v) + tfMap["allow_remote_vpc_dns_resolution"] = aws.ToBool(v) } return tfMap diff --git a/internal/service/ec2/vpc_peering_connection_accepter.go b/internal/service/ec2/vpc_peering_connection_accepter.go index ca5b8fd1576..a730d3719c7 100644 --- a/internal/service/ec2/vpc_peering_connection_accepter.go +++ b/internal/service/ec2/vpc_peering_connection_accepter.go @@ -7,8 +7,7 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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" @@ -21,7 +20,7 @@ import ( // @SDKResource("aws_vpc_peering_connection_accepter", name="VPC Peering Connection") // @Tags(identifierAttribute="id") // @Testing(tagsTest=false) -func ResourceVPCPeeringConnectionAccepter() *schema.Resource { +func resourceVPCPeeringConnectionAccepter() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCPeeringAccepterCreate, ReadWithoutTimeout: resourceVPCPeeringConnectionRead, @@ -90,10 +89,10 @@ func ResourceVPCPeeringConnectionAccepter() *schema.Resource { func resourceVPCPeeringAccepterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) vpcPeeringConnectionID := d.Get("vpc_peering_connection_id").(string) - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, vpcPeeringConnectionID) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, vpcPeeringConnectionID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC Peering Connection (%s): %s", vpcPeeringConnectionID, err) @@ -101,7 +100,7 @@ func resourceVPCPeeringAccepterCreate(ctx context.Context, d *schema.ResourceDat d.SetId(vpcPeeringConnectionID) - if _, ok := d.GetOk("auto_accept"); ok && aws.StringValue(vpcPeeringConnection.Status.Code) == ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance { + if _, ok := d.GetOk("auto_accept"); ok && vpcPeeringConnection.Status.Code == awstypes.VpcPeeringConnectionStateReasonCodePendingAcceptance { vpcPeeringConnection, err = acceptVPCPeeringConnection(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { diff --git a/internal/service/ec2/vpc_peering_connection_accepter_test.go b/internal/service/ec2/vpc_peering_connection_accepter_test.go index 056458c5f64..cfdf8f7d389 100644 --- a/internal/service/ec2/vpc_peering_connection_accepter_test.go +++ b/internal/service/ec2/vpc_peering_connection_accepter_test.go @@ -7,7 +7,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -18,7 +18,7 @@ import ( func TestAccVPCPeeringConnectionAccepter_sameRegionSameAccount(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection resourceNameMainVpc := "aws_vpc.main" // Requester resourceNamePeerVpc := "aws_vpc.peer" // Accepter resourceNameConnection := "aws_vpc_peering_connection.main" // Requester @@ -72,7 +72,7 @@ func TestAccVPCPeeringConnectionAccepter_sameRegionSameAccount(t *testing.T) { func TestAccVPCPeeringConnectionAccepter_differentRegionSameAccount(t *testing.T) { ctx := acctest.Context(t) - var vMain, vPeer ec2.VpcPeeringConnection + var vMain, vPeer awstypes.VpcPeeringConnection var providers []*schema.Provider resourceNameMainVpc := "aws_vpc.main" // Requester resourceNamePeerVpc := "aws_vpc.peer" // Accepter @@ -118,7 +118,7 @@ func TestAccVPCPeeringConnectionAccepter_differentRegionSameAccount(t *testing.T func TestAccVPCPeeringConnectionAccepter_sameRegionDifferentAccount(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection resourceNameMainVpc := "aws_vpc.main" // Requester resourceNamePeerVpc := "aws_vpc.peer" // Accepter resourceNameConnection := "aws_vpc_peering_connection.main" // Requester @@ -155,7 +155,7 @@ func TestAccVPCPeeringConnectionAccepter_sameRegionDifferentAccount(t *testing.T func TestAccVPCPeeringConnectionAccepter_differentRegionDifferentAccount(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection resourceNameMainVpc := "aws_vpc.main" // Requester resourceNamePeerVpc := "aws_vpc.peer" // Accepter resourceNameConnection := "aws_vpc_peering_connection.main" // Requester diff --git a/internal/service/ec2/vpc_peering_connection_data_source.go b/internal/service/ec2/vpc_peering_connection_data_source.go index 14db17310a6..ab64c58126e 100644 --- a/internal/service/ec2/vpc_peering_connection_data_source.go +++ b/internal/service/ec2/vpc_peering_connection_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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,8 +18,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_vpc_peering_connection") -func DataSourceVPCPeeringConnection() *schema.Resource { +// @SDKDataSource("aws_vpc_peering_connection", name="VPC Peering Connection") +func dataSourceVPCPeeringConnection() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCPeeringConnectionRead, @@ -144,13 +144,13 @@ func DataSourceVPCPeeringConnection() *schema.Resource { func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &ec2.DescribeVpcPeeringConnectionsInput{} if v, ok := d.GetOk(names.AttrID); ok { - input.VpcPeeringConnectionIds = aws.StringSlice([]string{v.(string)}) + input.VpcPeeringConnectionIds = []string{v.(string)} } input.Filters = newAttributeFilterList( @@ -179,13 +179,13 @@ func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceD input.Filters = nil } - vpcPeeringConnection, err := FindVPCPeeringConnection(ctx, conn, input) + vpcPeeringConnection, err := findVPCPeeringConnection(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 VPC Peering Connection", err)) } - d.SetId(aws.StringValue(vpcPeeringConnection.VpcPeeringConnectionId)) + d.SetId(aws.ToString(vpcPeeringConnection.VpcPeeringConnectionId)) d.Set(names.AttrStatus, vpcPeeringConnection.Status.Code) d.Set(names.AttrVPCID, vpcPeeringConnection.RequesterVpcInfo.VpcId) d.Set(names.AttrOwnerID, vpcPeeringConnection.RequesterVpcInfo.OwnerId) @@ -194,7 +194,7 @@ func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceD cidrBlockSet := []interface{}{} for _, v := range vpcPeeringConnection.RequesterVpcInfo.CidrBlockSet { cidrBlockSet = append(cidrBlockSet, map[string]interface{}{ - names.AttrCIDRBlock: aws.StringValue(v.CidrBlock), + names.AttrCIDRBlock: aws.ToString(v.CidrBlock), }) } if err := d.Set("cidr_block_set", cidrBlockSet); err != nil { @@ -204,7 +204,7 @@ func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceD ipv6CidrBlockSet := []interface{}{} for _, v := range vpcPeeringConnection.RequesterVpcInfo.Ipv6CidrBlockSet { ipv6CidrBlockSet = append(ipv6CidrBlockSet, map[string]interface{}{ - "ipv6_cidr_block": aws.StringValue(v.Ipv6CidrBlock), + "ipv6_cidr_block": aws.ToString(v.Ipv6CidrBlock), }) } if err := d.Set("ipv6_cidr_block_set", ipv6CidrBlockSet); err != nil { @@ -219,7 +219,7 @@ func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceD peerCidrBlockSet := []interface{}{} for _, v := range vpcPeeringConnection.AccepterVpcInfo.CidrBlockSet { peerCidrBlockSet = append(peerCidrBlockSet, map[string]interface{}{ - names.AttrCIDRBlock: aws.StringValue(v.CidrBlock), + names.AttrCIDRBlock: aws.ToString(v.CidrBlock), }) } if err := d.Set("peer_cidr_block_set", peerCidrBlockSet); err != nil { @@ -229,7 +229,7 @@ func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceD peerIpv6CidrBlockSet := []interface{}{} for _, v := range vpcPeeringConnection.AccepterVpcInfo.Ipv6CidrBlockSet { peerIpv6CidrBlockSet = append(peerIpv6CidrBlockSet, map[string]interface{}{ - "ipv6_cidr_block": aws.StringValue(v.Ipv6CidrBlock), + "ipv6_cidr_block": aws.ToString(v.Ipv6CidrBlock), }) } if err := d.Set("peer_ipv6_cidr_block_set", peerIpv6CidrBlockSet); err != nil { @@ -238,7 +238,7 @@ func dataSourceVPCPeeringConnectionRead(ctx context.Context, d *schema.ResourceD d.Set("peer_region", vpcPeeringConnection.AccepterVpcInfo.Region) - if err := d.Set(names.AttrTags, KeyValueTags(ctx, vpcPeeringConnection.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, vpcPeeringConnection.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_peering_connection_options.go b/internal/service/ec2/vpc_peering_connection_options.go index cb02993cecc..479c1a8f2ec 100644 --- a/internal/service/ec2/vpc_peering_connection_options.go +++ b/internal/service/ec2/vpc_peering_connection_options.go @@ -14,8 +14,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// @SDKResource("aws_vpc_peering_connection_options") -func ResourceVPCPeeringConnectionOptions() *schema.Resource { +// @SDKResource("aws_vpc_peering_connection_options", name="VPC Peering Connection Options") +func resourceVPCPeeringConnectionOptions() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceVPCPeeringConnectionOptionsCreate, ReadWithoutTimeout: resourceVPCPeeringConnectionOptionsRead, @@ -39,10 +39,10 @@ func ResourceVPCPeeringConnectionOptions() *schema.Resource { func resourceVPCPeeringConnectionOptionsCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) vpcPeeringConnectionID := d.Get("vpc_peering_connection_id").(string) - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, vpcPeeringConnectionID) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, vpcPeeringConnectionID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC Peering Connection (%s): %s", vpcPeeringConnectionID, err) @@ -59,9 +59,9 @@ func resourceVPCPeeringConnectionOptionsCreate(ctx context.Context, d *schema.Re func resourceVPCPeeringConnectionOptionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, d.Id()) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 VPC Peering Connection Options %s not found, removing from state", d.Id()) @@ -96,9 +96,9 @@ func resourceVPCPeeringConnectionOptionsRead(ctx context.Context, d *schema.Reso func resourceVPCPeeringConnectionOptionsUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - vpcPeeringConnection, err := FindVPCPeeringConnectionByID(ctx, conn, d.Id()) + vpcPeeringConnection, err := findVPCPeeringConnectionByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC Peering Connection (%s): %s", d.Id(), err) diff --git a/internal/service/ec2/vpc_peering_connection_options_test.go b/internal/service/ec2/vpc_peering_connection_options_test.go index 8f959014cd2..0b86c643f03 100644 --- a/internal/service/ec2/vpc_peering_connection_options_test.go +++ b/internal/service/ec2/vpc_peering_connection_options_test.go @@ -8,8 +8,8 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -40,7 +40,7 @@ func TestAccVPCPeeringConnectionOptions_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "requester.0.allow_remote_vpc_dns_resolution", acctest.CtFalse), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "requester", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(false), }, ), @@ -49,7 +49,7 @@ func TestAccVPCPeeringConnectionOptions_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "accepter.0.allow_remote_vpc_dns_resolution", acctest.CtTrue), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "accepter", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(true), }, ), @@ -71,7 +71,7 @@ func TestAccVPCPeeringConnectionOptions_basic(t *testing.T) { ), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "requester", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(false), }, ), @@ -83,7 +83,7 @@ func TestAccVPCPeeringConnectionOptions_basic(t *testing.T) { ), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "accepter", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(false), }, ), @@ -119,7 +119,7 @@ func TestAccVPCPeeringConnectionOptions_differentRegionSameAccount(t *testing.T) resource.TestCheckResourceAttr(resourceName, "requester.0.allow_remote_vpc_dns_resolution", acctest.CtTrue), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "requester", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(true), }, ), @@ -128,7 +128,7 @@ func TestAccVPCPeeringConnectionOptions_differentRegionSameAccount(t *testing.T) resource.TestCheckResourceAttr(resourceNamePeer, "accepter.0.allow_remote_vpc_dns_resolution", acctest.CtTrue), testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx, pcxResourceNamePeer, "accepter", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(true), }, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers), @@ -152,7 +152,7 @@ func TestAccVPCPeeringConnectionOptions_differentRegionSameAccount(t *testing.T) ), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "requester", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(false), }, ), @@ -164,7 +164,7 @@ func TestAccVPCPeeringConnectionOptions_differentRegionSameAccount(t *testing.T) ), testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx, pcxResourceNamePeer, "accepter", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(false), }, acctest.RegionProviderFunc(acctest.AlternateRegion(), &providers), @@ -199,7 +199,7 @@ func TestAccVPCPeeringConnectionOptions_sameRegionDifferentAccount(t *testing.T) resource.TestCheckResourceAttr(resourceName, "requester.0.allow_remote_vpc_dns_resolution", acctest.CtTrue), testAccCheckVPCPeeringConnectionOptions(ctx, pcxResourceName, "requester", - &ec2.VpcPeeringConnectionOptionsDescription{ + &awstypes.VpcPeeringConnectionOptionsDescription{ AllowDnsResolutionFromRemoteVpc: aws.Bool(true), }, ), @@ -218,11 +218,11 @@ func TestAccVPCPeeringConnectionOptions_sameRegionDifferentAccount(t *testing.T) }) } -func testAccCheckVPCPeeringConnectionOptions(ctx context.Context, n, block string, options *ec2.VpcPeeringConnectionOptionsDescription) resource.TestCheckFunc { +func testAccCheckVPCPeeringConnectionOptions(ctx context.Context, n, block string, options *awstypes.VpcPeeringConnectionOptionsDescription) resource.TestCheckFunc { return testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx, n, block, options, func() *schema.Provider { return acctest.Provider }) } -func testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx context.Context, n, block string, options *ec2.VpcPeeringConnectionOptionsDescription, providerF func() *schema.Provider) resource.TestCheckFunc { +func testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx context.Context, n, block string, options *awstypes.VpcPeeringConnectionOptionsDescription, providerF func() *schema.Provider) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -233,7 +233,7 @@ func testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx context.Context, n, return fmt.Errorf("No EC2 VPC Peering Connection ID is set.") } - conn := providerF().Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := providerF().Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindVPCPeeringConnectionByID(ctx, conn, rs.Primary.ID) @@ -246,7 +246,7 @@ func testAccCheckVPCPeeringConnectionOptionsWithProvider(ctx context.Context, n, o = output.RequesterVpcInfo } - if got, want := aws.BoolValue(o.PeeringOptions.AllowDnsResolutionFromRemoteVpc), aws.BoolValue(options.AllowDnsResolutionFromRemoteVpc); got != want { + if got, want := aws.ToBool(o.PeeringOptions.AllowDnsResolutionFromRemoteVpc), aws.ToBool(options.AllowDnsResolutionFromRemoteVpc); got != want { return fmt.Errorf("VPC Peering Connection Options AllowDnsResolutionFromRemoteVpc =%v, want = %v", got, want) } diff --git a/internal/service/ec2/vpc_peering_connection_test.go b/internal/service/ec2/vpc_peering_connection_test.go index 4d01af18400..cfd14f83509 100644 --- a/internal/service/ec2/vpc_peering_connection_test.go +++ b/internal/service/ec2/vpc_peering_connection_test.go @@ -10,8 +10,9 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -25,7 +26,7 @@ import ( func TestAccVPCPeeringConnection_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_peering_connection.test" @@ -56,7 +57,7 @@ func TestAccVPCPeeringConnection_basic(t *testing.T) { func TestAccVPCPeeringConnection_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_peering_connection.test" @@ -80,7 +81,7 @@ func TestAccVPCPeeringConnection_disappears(t *testing.T) { func TestAccVPCPeeringConnection_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_peering_connection.test" @@ -129,17 +130,17 @@ func TestAccVPCPeeringConnection_tags(t *testing.T) { func TestAccVPCPeeringConnection_options(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_peering_connection.test" testAccepterChange := func(*terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) log.Printf("[DEBUG] Test change to the VPC Peering Connection Options.") - _, err := conn.ModifyVpcPeeringConnectionOptionsWithContext(ctx, &ec2.ModifyVpcPeeringConnectionOptionsInput{ + _, err := conn.ModifyVpcPeeringConnectionOptions(ctx, &ec2.ModifyVpcPeeringConnectionOptionsInput{ VpcPeeringConnectionId: v.VpcPeeringConnectionId, - AccepterPeeringConnectionOptions: &ec2.PeeringConnectionOptionsRequest{ + AccepterPeeringConnectionOptions: &awstypes.PeeringConnectionOptionsRequest{ AllowDnsResolutionFromRemoteVpc: aws.Bool(false), }, }) @@ -268,7 +269,7 @@ func TestAccVPCPeeringConnection_peerRegionAutoAccept(t *testing.T) { func TestAccVPCPeeringConnection_region(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_peering_connection.test" @@ -301,7 +302,7 @@ func TestAccVPCPeeringConnection_region(t *testing.T) { // Tests the peering connection acceptance functionality for same region, same account. func TestAccVPCPeeringConnection_accept(t *testing.T) { ctx := acctest.Context(t) - var v ec2.VpcPeeringConnection + var v awstypes.VpcPeeringConnection rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_peering_connection.test" @@ -384,7 +385,7 @@ func TestAccVPCPeeringConnection_optionsNoAutoAccept(t *testing.T) { func testAccCheckVPCPeeringConnectionDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_peering_connection" { @@ -408,11 +409,11 @@ func testAccCheckVPCPeeringConnectionDestroy(ctx context.Context) resource.TestC } } -func testAccCheckVPCPeeringConnectionExists(ctx context.Context, n string, v *ec2.VpcPeeringConnection) resource.TestCheckFunc { +func testAccCheckVPCPeeringConnectionExists(ctx context.Context, n string, v *awstypes.VpcPeeringConnection) resource.TestCheckFunc { return testAccCheckVPCPeeringConnectionExistsWithProvider(ctx, n, v, func() *schema.Provider { return acctest.Provider }) } -func testAccCheckVPCPeeringConnectionExistsWithProvider(ctx context.Context, n string, v *ec2.VpcPeeringConnection, providerF func() *schema.Provider) resource.TestCheckFunc { +func testAccCheckVPCPeeringConnectionExistsWithProvider(ctx context.Context, n string, v *awstypes.VpcPeeringConnection, providerF func() *schema.Provider) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -423,7 +424,7 @@ func testAccCheckVPCPeeringConnectionExistsWithProvider(ctx context.Context, n s return fmt.Errorf("No EC2 VPC Peering Connection ID is set.") } - conn := providerF().Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := providerF().Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindVPCPeeringConnectionByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_peering_connections_data_source.go b/internal/service/ec2/vpc_peering_connections_data_source.go index 24e4ea97d7b..4268a62b416 100644 --- a/internal/service/ec2/vpc_peering_connections_data_source.go +++ b/internal/service/ec2/vpc_peering_connections_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_vpc_peering_connections") -func DataSourceVPCPeeringConnections() *schema.Resource { +// @SDKDataSource("aws_vpc_peering_connections", name="VPC Peering Connections") +func dataSourceVPCPeeringConnections() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCPeeringConnectionsRead, @@ -40,7 +40,7 @@ func DataSourceVPCPeeringConnections() *schema.Resource { func dataSourceVPCPeeringConnectionsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeVpcPeeringConnectionsInput{} @@ -54,7 +54,7 @@ func dataSourceVPCPeeringConnectionsRead(ctx context.Context, d *schema.Resource input.Filters = nil } - output, err := FindVPCPeeringConnections(ctx, conn, input) + output, err := findVPCPeeringConnections(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPC Peering Connections: %s", err) @@ -63,7 +63,7 @@ func dataSourceVPCPeeringConnectionsRead(ctx context.Context, d *schema.Resource var vpcPeeringConnectionIDs []string for _, v := range output { - vpcPeeringConnectionIDs = append(vpcPeeringConnectionIDs, aws.StringValue(v.VpcPeeringConnectionId)) + vpcPeeringConnectionIDs = append(vpcPeeringConnectionIDs, aws.ToString(v.VpcPeeringConnectionId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_prefix_list_data_source.go b/internal/service/ec2/vpc_prefix_list_data_source.go index a70ef84f5df..c782dddec96 100644 --- a/internal/service/ec2/vpc_prefix_list_data_source.go +++ b/internal/service/ec2/vpc_prefix_list_data_source.go @@ -17,8 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_prefix_list") -func DataSourcePrefixList() *schema.Resource { +// @SDKDataSource("aws_prefix_list", name="Prefix List") +func dataSourcePrefixList() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourcePrefixListRead, @@ -53,7 +53,7 @@ func dataSourcePrefixListRead(ctx context.Context, d *schema.ResourceData, meta input := &ec2.DescribePrefixListsInput{} if v, ok := d.GetOk(names.AttrName); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2(map[string]string{ + input.Filters = append(input.Filters, newAttributeFilterList(map[string]string{ "prefix-list-name": v.(string), })...) } @@ -62,7 +62,7 @@ func dataSourcePrefixListRead(ctx context.Context, d *schema.ResourceData, meta input.PrefixListIds = []string{v.(string)} } - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/vpc_route.go b/internal/service/ec2/vpc_route.go index bc3653357ee..ee3214f6cf1 100644 --- a/internal/service/ec2/vpc_route.go +++ b/internal/service/ec2/vpc_route.go @@ -270,7 +270,7 @@ func resourceRouteCreate(ctx context.Context, d *schema.ResourceData, meta inter return sdkdiag.AppendErrorf(diags, "creating Route in Route Table (%s) with destination (%s): %s", routeTableID, destination, err) } - d.SetId(RouteCreateID(routeTableID, destination)) + d.SetId(routeCreateID(routeTableID, destination)) if _, err := waitRouteReady(ctx, conn, routeFinder, routeTableID, destination, d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Route in Route Table (%s) with destination (%s) create: %s", routeTableID, destination, err) @@ -501,7 +501,7 @@ func resourceRouteImport(ctx context.Context, d *schema.ResourceData, meta inter d.Set(routeDestinationPrefixListID, destination) } - d.SetId(RouteCreateID(routeTableID, destination)) + d.SetId(routeCreateID(routeTableID, destination)) return []*schema.ResourceData{d}, nil } diff --git a/internal/service/ec2/vpc_route_data_source.go b/internal/service/ec2/vpc_route_data_source.go index 7624f51de96..d8f6b7a0d64 100644 --- a/internal/service/ec2/vpc_route_data_source.go +++ b/internal/service/ec2/vpc_route_data_source.go @@ -17,8 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_route") -func DataSourceRoute() *schema.Resource { +// @SDKDataSource("aws_route", name="Route") +func dataSourceRoute() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceRouteRead, @@ -199,11 +199,11 @@ func dataSourceRouteRead(ctx context.Context, d *schema.ResourceData, meta inter route := routes[0] if destination := aws.ToString(route.DestinationCidrBlock); destination != "" { - d.SetId(RouteCreateID(routeTableID, destination)) + d.SetId(routeCreateID(routeTableID, destination)) } else if destination := aws.ToString(route.DestinationIpv6CidrBlock); destination != "" { - d.SetId(RouteCreateID(routeTableID, destination)) + d.SetId(routeCreateID(routeTableID, destination)) } else if destination := aws.ToString(route.DestinationPrefixListId); destination != "" { - d.SetId(RouteCreateID(routeTableID, destination)) + d.SetId(routeCreateID(routeTableID, destination)) } d.Set("carrier_gateway_id", route.CarrierGatewayId) diff --git a/internal/service/ec2/vpc_route_table.go b/internal/service/ec2/vpc_route_table.go index 31a9396e7aa..75db8524787 100644 --- a/internal/service/ec2/vpc_route_table.go +++ b/internal/service/ec2/vpc_route_table.go @@ -174,7 +174,7 @@ func resourceRouteTableCreate(ctx context.Context, d *schema.ResourceData, meta input := &ec2.CreateRouteTableInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeRouteTable), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeRouteTable), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -255,7 +255,7 @@ func resourceRouteTableRead(ctx context.Context, d *schema.ResourceData, meta in d.Set(names.AttrVPCID, routeTable.VpcId) // Ignore the AmazonFSx service tag in addition to standard ignores. - setTagsOutV2(ctx, TagsV2(keyValueTagsV2(ctx, routeTable.Tags).Ignore(tftags.New(ctx, []string{"AmazonFSx"})))) + setTagsOut(ctx, Tags(keyValueTags(ctx, routeTable.Tags).Ignore(tftags.New(ctx, []string{"AmazonFSx"})))) return diags } diff --git a/internal/service/ec2/vpc_route_table_association.go b/internal/service/ec2/vpc_route_table_association.go index 05832e0fd23..cdcb0f04130 100644 --- a/internal/service/ec2/vpc_route_table_association.go +++ b/internal/service/ec2/vpc_route_table_association.go @@ -22,8 +22,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_route_table_association") -func ResourceRouteTableAssociation() *schema.Resource { +// @SDKResource("aws_route_table_association", name="Route Table Association") +func resourceRouteTableAssociation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceRouteTableAssociationCreate, ReadWithoutTimeout: resourceRouteTableAssociationRead, diff --git a/internal/service/ec2/vpc_route_table_data_source.go b/internal/service/ec2/vpc_route_table_data_source.go index 14acfe0e368..799ddfcd2dc 100644 --- a/internal/service/ec2/vpc_route_table_data_source.go +++ b/internal/service/ec2/vpc_route_table_data_source.go @@ -22,9 +22,9 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_route_table") +// @SDKDataSource("aws_route_table", name="Route Table") // @Testing(tagsTest=true) -func DataSourceRouteTable() *schema.Resource { +func dataSourceRouteTable() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceRouteTableRead, @@ -201,7 +201,7 @@ func dataSourceRouteTableRead(ctx context.Context, d *schema.ResourceData, meta if !rtbOk && !vpcIdOk && !subnetIdOk && !gatewayIdOk && !filterOk && !tagsOk { return sdkdiag.AppendErrorf(diags, "one of route_table_id, vpc_id, subnet_id, gateway_id, filters, or tags must be assigned") } - req.Filters = newAttributeFilterListV2( + req.Filters = newAttributeFilterList( map[string]string{ "route-table-id": rtbId.(string), "vpc-id": vpcId.(string), @@ -209,10 +209,10 @@ func dataSourceRouteTableRead(ctx context.Context, d *schema.ResourceData, meta "association.gateway-id": gatewayId.(string), }, ) - req.Filters = append(req.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, tags.(map[string]interface{}))), + req.Filters = append(req.Filters, newTagFilterList( + Tags(tftags.New(ctx, tags.(map[string]interface{}))), )...) - req.Filters = append(req.Filters, newCustomFilterListV2( + req.Filters = append(req.Filters, newCustomFilterList( filter.(*schema.Set), )...) @@ -246,7 +246,7 @@ func dataSourceRouteTableRead(ctx context.Context, d *schema.ResourceData, meta d.Set(names.AttrVPCID, rt.VpcId) //Ignore the AmazonFSx service tag in addition to standard ignores - if err := d.Set(names.AttrTags, keyValueTagsV2(ctx, rt.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Ignore(tftags.New(ctx, []string{"AmazonFSx"})).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, rt.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Ignore(tftags.New(ctx, []string{"AmazonFSx"})).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_route_table_test.go b/internal/service/ec2/vpc_route_table_test.go index 9ba8891c885..954c7158d3a 100644 --- a/internal/service/ec2/vpc_route_table_test.go +++ b/internal/service/ec2/vpc_route_table_test.go @@ -1001,7 +1001,7 @@ func TestAccVPCRouteTable_localRoute(t *testing.T) { { Config: testAccVPCRouteTableConfig_basic(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), ), @@ -1042,7 +1042,7 @@ func TestAccVPCRouteTable_localRouteAdoptUpdate(t *testing.T) { { Config: testAccVPCRouteTableConfig_ipv4NetworkInterfaceToLocal(rName, vpcCIDR, localGatewayCIDR, subnetCIDR), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ @@ -1054,7 +1054,7 @@ func TestAccVPCRouteTable_localRouteAdoptUpdate(t *testing.T) { { Config: testAccVPCRouteTableConfig_ipv4LocalNetworkInterface(rName, vpcCIDR, subnetCIDR), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), testAccCheckRouteTableRoute(resourceName, names.AttrCIDRBlock, vpcCIDR, names.AttrNetworkInterfaceID, eniResourceName, names.AttrID), @@ -1063,7 +1063,7 @@ func TestAccVPCRouteTable_localRouteAdoptUpdate(t *testing.T) { { Config: testAccVPCRouteTableConfig_ipv4NetworkInterfaceToLocal(rName, vpcCIDR, localGatewayCIDR, subnetCIDR), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ @@ -1105,7 +1105,7 @@ func TestAccVPCRouteTable_localRouteImportUpdate(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4NoRoute(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), ), @@ -1127,7 +1127,7 @@ func TestAccVPCRouteTable_localRouteImportUpdate(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4LocalToNetworkInterface(rName), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), resource.TestCheckResourceAttr(rteResourceName, "gateway_id", ""), @@ -1137,7 +1137,7 @@ func TestAccVPCRouteTable_localRouteImportUpdate(t *testing.T) { { Config: testAccVPCRouteTableConfig_ipv4LocalNetworkInterface(rName, vpcCIDR, subnetCIDR), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), testAccCheckRouteTableRoute(resourceName, names.AttrCIDRBlock, vpcCIDR, names.AttrNetworkInterfaceID, eniResourceName, names.AttrID), @@ -1146,7 +1146,7 @@ func TestAccVPCRouteTable_localRouteImportUpdate(t *testing.T) { { Config: testAccVPCRouteTableConfig_ipv4NetworkInterfaceToLocal(rName, vpcCIDR, localGatewayCIDR, subnetCIDR), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), resource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ @@ -1158,7 +1158,7 @@ func TestAccVPCRouteTable_localRouteImportUpdate(t *testing.T) { { Config: testAccVPCRouteTableConfig_ipv4LocalNetworkInterface(rName, vpcCIDR, subnetCIDR), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, resourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), testAccCheckRouteTableRoute(resourceName, names.AttrCIDRBlock, vpcCIDR, names.AttrNetworkInterfaceID, eniResourceName, names.AttrID), @@ -1284,7 +1284,7 @@ func testAccCheckRouteTableWaitForVPCEndpointRoute(ctx context.Context, routeTab conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) resp, err := conn.DescribePrefixLists(ctx, &ec2.DescribePrefixListsInput{ - Filters: tfec2.NewAttributeFilterListV2(map[string]string{ + Filters: tfec2.NewAttributeFilterList(map[string]string{ "prefix-list-name": aws.ToString(vpce.ServiceName), }), }) diff --git a/internal/service/ec2/vpc_route_tables_data_source.go b/internal/service/ec2/vpc_route_tables_data_source.go index 79f089c88e3..1642bfe23d3 100644 --- a/internal/service/ec2/vpc_route_tables_data_source.go +++ b/internal/service/ec2/vpc_route_tables_data_source.go @@ -17,8 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_route_tables") -func DataSourceRouteTables() *schema.Resource { +// @SDKDataSource("aws_route_tables", name="Route Tables") +func dataSourceRouteTables() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceRouteTablesRead, @@ -49,18 +49,18 @@ func dataSourceRouteTablesRead(ctx context.Context, d *schema.ResourceData, meta input := &ec2.DescribeRouteTablesInput{} if v, ok := d.GetOk(names.AttrVPCID); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2( + input.Filters = append(input.Filters, newAttributeFilterList( map[string]string{ "vpc-id": v.(string), }, )...) } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) diff --git a/internal/service/ec2/vpc_route_test.go b/internal/service/ec2/vpc_route_test.go index 69220077306..0e7e035ed6e 100644 --- a/internal/service/ec2/vpc_route_test.go +++ b/internal/service/ec2/vpc_route_test.go @@ -1590,7 +1590,7 @@ func TestAccVPCRoute_localRouteCreateError(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4NoRoute(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), ), @@ -1622,7 +1622,7 @@ func TestAccVPCRoute_localRouteImport(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4NoRoute(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), ), @@ -1664,7 +1664,7 @@ func TestAccVPCRoute_localRouteImportAndUpdate(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4NoRoute(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), ), @@ -1686,7 +1686,7 @@ func TestAccVPCRoute_localRouteImportAndUpdate(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4LocalToNetworkInterface(rName), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), resource.TestCheckResourceAttr(resourceName, "gateway_id", ""), @@ -1696,7 +1696,7 @@ func TestAccVPCRoute_localRouteImportAndUpdate(t *testing.T) { { Config: testAccVPCRouteConfig_ipv4LocalRestore(rName), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName, &vpc), + acctest.CheckVPCExists(ctx, vpcResourceName, &vpc), testAccCheckRouteTableExists(ctx, rtResourceName, &routeTable), testAccCheckRouteTableNumberOfRoutes(&routeTable, 1), resource.TestCheckResourceAttr(resourceName, "gateway_id", "local"), diff --git a/internal/service/ec2/vpc_security_group.go b/internal/service/ec2/vpc_security_group.go index b47de6df567..6730abbc03a 100644 --- a/internal/service/ec2/vpc_security_group.go +++ b/internal/service/ec2/vpc_security_group.go @@ -14,10 +14,11 @@ import ( "time" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" @@ -35,7 +36,7 @@ import ( // @SDKResource("aws_security_group", name="Security Group") // @Tags(identifierAttribute="id") -// @Testing(existsType="github.com/aws/aws-sdk-go/service/ec2;ec2.SecurityGroup") +// @Testing(existsType="github.com/aws/aws-sdk-go-v2/service/ec2/types;types.SecurityGroup") // @Testing(importIgnore="revoke_rules_on_delete") func resourceSecurityGroup() *schema.Resource { //lintignore:R011 @@ -55,7 +56,7 @@ func resourceSecurityGroup() *schema.Resource { }, SchemaVersion: 1, - MigrateState: SecurityGroupMigrateState, + MigrateState: securityGroupMigrateState, // Keep in sync with aws_default_security_group's schema. // See notes in vpc_default_security_group.go. @@ -127,7 +128,7 @@ var ( Computed: true, ConfigMode: schema.SchemaConfigModeAttr, Elem: securityGroupRuleNestedBlock, - Set: SecurityGroupRuleHash, + Set: securityGroupRuleHash, } securityGroupRuleNestedBlock = &schema.Resource{ @@ -165,7 +166,7 @@ var ( names.AttrProtocol: { Type: schema.TypeString, Required: true, - StateFunc: ProtocolStateFunc, + StateFunc: protocolStateFunc, }, names.AttrSecurityGroups: { Type: schema.TypeSet, @@ -189,12 +190,12 @@ var ( func resourceSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) name := create.Name(d.Get(names.AttrName).(string), d.Get(names.AttrNamePrefix).(string)) inputC := &ec2.CreateSecurityGroupInput{ GroupName: aws.String(name), - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeSecurityGroup), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeSecurityGroup), } if v := d.Get(names.AttrDescription); v != nil { @@ -205,16 +206,16 @@ func resourceSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, me inputC.VpcId = aws.String(v.(string)) } - output, err := conn.CreateSecurityGroupWithContext(ctx, inputC) + output, err := conn.CreateSecurityGroup(ctx, inputC) if err != nil { return sdkdiag.AppendErrorf(diags, "creating Security Group (%s): %s", name, err) } - d.SetId(aws.StringValue(output.GroupId)) + d.SetId(aws.ToString(output.GroupId)) // Wait for the security group to truly exist - if _, err := WaitSecurityGroupCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { + if _, err := waitSecurityGroupCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for Security Group (%s) create: %s", d.Id(), err) } @@ -222,11 +223,11 @@ func resourceSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, me // Here we revoke that rule, so users don't unknowingly have/use it. inputR := &ec2.RevokeSecurityGroupEgressInput{ GroupId: aws.String(d.Id()), - IpPermissions: []*ec2.IpPermission{ + IpPermissions: []awstypes.IpPermission{ { - FromPort: aws.Int64(0), - ToPort: aws.Int64(0), - IpRanges: []*ec2.IpRange{ + FromPort: aws.Int32(0), + ToPort: aws.Int32(0), + IpRanges: []awstypes.IpRange{ { CidrIp: aws.String("0.0.0.0/0"), }, @@ -236,17 +237,17 @@ func resourceSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, me }, } - if _, err := conn.RevokeSecurityGroupEgressWithContext(ctx, inputR); err != nil { + if _, err := conn.RevokeSecurityGroupEgress(ctx, inputR); err != nil { return sdkdiag.AppendErrorf(diags, "revoking default IPv4 egress rule for Security Group (%s): %s", d.Id(), err) } inputR = &ec2.RevokeSecurityGroupEgressInput{ GroupId: aws.String(d.Id()), - IpPermissions: []*ec2.IpPermission{ + IpPermissions: []awstypes.IpPermission{ { - FromPort: aws.Int64(0), - ToPort: aws.Int64(0), - Ipv6Ranges: []*ec2.Ipv6Range{ + FromPort: aws.Int32(0), + ToPort: aws.Int32(0), + Ipv6Ranges: []awstypes.Ipv6Range{ { CidrIpv6: aws.String("::/0"), }, @@ -256,7 +257,7 @@ func resourceSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, me }, } - if _, err := conn.RevokeSecurityGroupEgressWithContext(ctx, inputR); err != nil { + if _, err := conn.RevokeSecurityGroupEgress(ctx, inputR); err != nil { // If we have a NotFound or InvalidParameterValue, then we are trying to remove the default IPv6 egress of a non-IPv6 enabled SG. if !tfawserr.ErrCodeEquals(err, errCodeInvalidPermissionNotFound) && !tfawserr.ErrMessageContains(err, errCodeInvalidParameterValue, "remote-ipv6-range") { return sdkdiag.AppendErrorf(diags, "revoking default IPv6 egress rule for Security Group (%s): %s", d.Id(), err) @@ -269,9 +270,9 @@ func resourceSecurityGroupCreate(ctx context.Context, d *schema.ResourceData, me func resourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - sg, err := FindSecurityGroupByID(ctx, conn, d.Id()) + sg, err := findSecurityGroupByID(ctx, conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Security Group (%s) not found, removing from state", d.Id()) @@ -283,21 +284,21 @@ func resourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "reading Security Group (%s): %s", d.Id(), err) } - remoteIngressRules := SecurityGroupIPPermGather(d.Id(), sg.IpPermissions, sg.OwnerId) - remoteEgressRules := SecurityGroupIPPermGather(d.Id(), sg.IpPermissionsEgress, sg.OwnerId) + remoteIngressRules := securityGroupIPPermGather(d.Id(), sg.IpPermissions, sg.OwnerId) + remoteEgressRules := securityGroupIPPermGather(d.Id(), sg.IpPermissionsEgress, sg.OwnerId) localIngressRules := d.Get("ingress").(*schema.Set).List() localEgressRules := d.Get("egress").(*schema.Set).List() // Loop through the local state of rules, doing a match against the remote // ruleSet we built above. - ingressRules := MatchRules("ingress", localIngressRules, remoteIngressRules) - egressRules := MatchRules("egress", localEgressRules, remoteEgressRules) + ingressRules := matchRules("ingress", localIngressRules, remoteIngressRules) + egressRules := matchRules("egress", localEgressRules, remoteEgressRules) - ownerID := aws.StringValue(sg.OwnerId) + ownerID := aws.ToString(sg.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("security-group/%s", d.Id()), @@ -305,7 +306,7 @@ func resourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, meta d.Set(names.AttrARN, arn.String()) d.Set(names.AttrDescription, sg.Description) d.Set(names.AttrName, sg.GroupName) - d.Set(names.AttrNamePrefix, create.NamePrefixFromName(aws.StringValue(sg.GroupName))) + d.Set(names.AttrNamePrefix, create.NamePrefixFromName(aws.ToString(sg.GroupName))) d.Set(names.AttrOwnerID, ownerID) d.Set(names.AttrVPCID, sg.VpcId) @@ -325,9 +326,9 @@ func resourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, meta func resourceSecurityGroupUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - group, err := FindSecurityGroupByID(ctx, conn, d.Id()) + group, err := findSecurityGroupByID(ctx, conn, d.Id()) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Security Group (%s): %s", d.Id(), err) @@ -350,7 +351,7 @@ func resourceSecurityGroupUpdate(ctx context.Context, d *schema.ResourceData, me func resourceSecurityGroupDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) ctx = tflog.SetField(ctx, names.AttrVPCID, d.Get(names.AttrVPCID)) @@ -380,7 +381,7 @@ func resourceSecurityGroupDelete(ctx context.Context, d *schema.ResourceData, me ctx, firstShortRetry, // short initial attempt followed by full length attempt func() (interface{}, error) { - return conn.DeleteSecurityGroupWithContext(ctx, &ec2.DeleteSecurityGroupInput{ + return conn.DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{ GroupId: aws.String(d.Id()), }) }, @@ -400,7 +401,7 @@ func resourceSecurityGroupDelete(ctx context.Context, d *schema.ResourceData, me ctx, remainingRetry, func() (interface{}, error) { - return conn.DeleteSecurityGroupWithContext(ctx, &ec2.DeleteSecurityGroupInput{ + return conn.DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{ GroupId: aws.String(d.Id()), }) }, @@ -417,7 +418,7 @@ func resourceSecurityGroupDelete(ctx context.Context, d *schema.ResourceData, me } _, err = tfresource.RetryUntilNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindSecurityGroupByID(ctx, conn, d.Id()) + return findSecurityGroupByID(ctx, conn, d.Id()) }) if err != nil { @@ -433,7 +434,7 @@ func resourceSecurityGroupDelete(ctx context.Context, d *schema.ResourceData, me // a DepedencyViolation error. searchAll = true means to search every security group // looking for a rule depending on this security group. Otherwise, it will only look at // groups that this group knows about. -func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.EC2, id string, searchAll bool) error { +func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.Client, id string, searchAll bool) error { conns.GlobalMutexKV.Lock(id) defer conns.GlobalMutexKV.Unlock(id) @@ -445,9 +446,9 @@ func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.EC2, id string for _, rule := range rules { var err error - if rule.IsEgress == nil || !aws.BoolValue(rule.IsEgress) { + if rule.IsEgress == nil || !aws.ToBool(rule.IsEgress) { input := &ec2.RevokeSecurityGroupIngressInput{ - SecurityGroupRuleIds: []*string{rule.SecurityGroupRuleId}, + SecurityGroupRuleIds: []string{aws.ToString(rule.SecurityGroupRuleId)}, } if rule.GroupId != nil { @@ -457,7 +458,7 @@ func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.EC2, id string // However, ec2.SecurityGroupRule doesn't include name so can't // be used. If it affects anything, this would affect default // VPCs. - sg, err := FindSecurityGroupByID(ctx, conn, id) + sg, err := findSecurityGroupByID(ctx, conn, id) if err != nil { return fmt.Errorf("reading Security Group (%s): %w", id, err) } @@ -465,14 +466,14 @@ func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.EC2, id string input.GroupName = sg.GroupName } - _, err = conn.RevokeSecurityGroupIngressWithContext(ctx, input) + _, err = conn.RevokeSecurityGroupIngress(ctx, input) } else { input := &ec2.RevokeSecurityGroupEgressInput{ GroupId: rule.GroupId, - SecurityGroupRuleIds: []*string{rule.SecurityGroupRuleId}, + SecurityGroupRuleIds: []string{aws.ToString(rule.SecurityGroupRuleId)}, } - _, err = conn.RevokeSecurityGroupEgressWithContext(ctx, input) + _, err = conn.RevokeSecurityGroupEgress(ctx, input) } if tfawserr.ErrCodeEquals(err, errCodeInvalidSecurityGroupRuleIdNotFound) { @@ -484,7 +485,7 @@ func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.EC2, id string } if err != nil { - return fmt.Errorf("revoking Security Group (%s) Rule (%s): %w", id, aws.StringValue(rule.SecurityGroupRuleId), err) + return fmt.Errorf("revoking Security Group (%s) Rule (%s): %w", id, aws.ToString(rule.SecurityGroupRuleId), err) } } @@ -495,7 +496,7 @@ func forceRevokeSecurityGroupRules(ctx context.Context, conn *ec2.EC2, id string // other groups. If searchAll = true, this could take a while as it looks through every // security group accessible from the account. This should only be used for troublesome // DependencyViolations. -func rulesInSGsTouchingThis(ctx context.Context, conn *ec2.EC2, id string, searchAll bool) ([]*ec2.SecurityGroupRule, error) { +func rulesInSGsTouchingThis(ctx context.Context, conn *ec2.Client, id string, searchAll bool) ([]awstypes.SecurityGroupRule, error) { var input *ec2.DescribeSecurityGroupRulesInput if searchAll { @@ -507,39 +508,40 @@ func rulesInSGsTouchingThis(ctx context.Context, conn *ec2.EC2, id string, searc } input = &ec2.DescribeSecurityGroupRulesInput{ - Filters: []*ec2.Filter{ + Filters: []awstypes.Filter{ { Name: aws.String("group-id"), - Values: aws.StringSlice(sgs), + Values: sgs, }, }, } } - rules := []*ec2.SecurityGroupRule{} + rules := []awstypes.SecurityGroupRule{} - err := conn.DescribeSecurityGroupRulesPagesWithContext(ctx, input, - func(page *ec2.DescribeSecurityGroupRulesOutput, lastPage bool) bool { - for _, rule := range page.SecurityGroupRules { - if rule == nil || rule.GroupId == nil { - continue - } + pages := ec2.NewDescribeSecurityGroupRulesPaginator(conn, input) + for pages.HasMorePages() { + page, err := pages.NextPage(ctx) - if aws.StringValue(rule.GroupId) == id { - rules = append(rules, rule) - continue - } + if err != nil { + return nil, fmt.Errorf("reading Security Group rules: %w", err) + } - if rule.ReferencedGroupInfo != nil && rule.ReferencedGroupInfo.GroupId != nil && aws.StringValue(rule.ReferencedGroupInfo.GroupId) == id { - rules = append(rules, rule) - continue - } + for _, rule := range page.SecurityGroupRules { + if rule.GroupId == nil { + continue } - return lastPage - }) - if err != nil { - return nil, fmt.Errorf("reading Security Group rules: %w", err) + if aws.ToString(rule.GroupId) == id { + rules = append(rules, rule) + continue + } + + if rule.ReferencedGroupInfo != nil && rule.ReferencedGroupInfo.GroupId != nil && aws.ToString(rule.ReferencedGroupInfo.GroupId) == id { + rules = append(rules, rule) + continue + } + } } return rules, nil @@ -549,10 +551,10 @@ func rulesInSGsTouchingThis(ctx context.Context, conn *ec2.EC2, id string, searc // to this one through a rule that this group knows about. This group can still have // dependent rules beyond those in these groups. However, the majority of the time, // revoking related rules should allow the group to be deleted. -func relatedSGs(ctx context.Context, conn *ec2.EC2, id string) ([]string, error) { +func relatedSGs(ctx context.Context, conn *ec2.Client, id string) ([]string, error) { relatedSGs := []string{id} - sg, err := FindSecurityGroupByID(ctx, conn, id) + sg, err := findSecurityGroupByID(ctx, conn, id) if err != nil { return nil, fmt.Errorf("reading Security Group (%s): %w", id, err) } @@ -560,8 +562,8 @@ func relatedSGs(ctx context.Context, conn *ec2.EC2, id string) ([]string, error) if len(sg.IpPermissions) > 0 { for _, v := range sg.IpPermissions { for _, v := range v.UserIdGroupPairs { - if v.GroupId != nil && aws.StringValue(v.GroupId) != id { - relatedSGs = append(relatedSGs, aws.StringValue(v.GroupId)) + if v.GroupId != nil && aws.ToString(v.GroupId) != id { + relatedSGs = append(relatedSGs, aws.ToString(v.GroupId)) } } } @@ -570,8 +572,8 @@ func relatedSGs(ctx context.Context, conn *ec2.EC2, id string) ([]string, error) if len(sg.IpPermissionsEgress) > 0 { for _, v := range sg.IpPermissionsEgress { for _, v := range v.UserIdGroupPairs { - if v.GroupId != nil && aws.StringValue(v.GroupId) != id { - relatedSGs = append(relatedSGs, aws.StringValue(v.GroupId)) + if v.GroupId != nil && aws.ToString(v.GroupId) != id { + relatedSGs = append(relatedSGs, aws.ToString(v.GroupId)) } } } @@ -580,7 +582,7 @@ func relatedSGs(ctx context.Context, conn *ec2.EC2, id string) ([]string, error) return relatedSGs, nil } -func SecurityGroupRuleHash(v interface{}) int { +func securityGroupRuleHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%d-", m["from_port"].(int))) @@ -646,12 +648,12 @@ func SecurityGroupRuleHash(v interface{}) int { return create.StringHashcode(buf.String()) } -func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, ownerId *string) []map[string]interface{} { +func securityGroupIPPermGather(groupId string, permissions []awstypes.IpPermission, ownerId *string) []map[string]interface{} { ruleMap := make(map[string]map[string]interface{}) for _, perm := range permissions { if len(perm.IpRanges) > 0 { for _, ip := range perm.IpRanges { - desc := aws.StringValue(ip.Description) + desc := aws.ToString(ip.Description) rule := initSecurityGroupRule(ruleMap, perm, desc) @@ -667,7 +669,7 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, if len(perm.Ipv6Ranges) > 0 { for _, ip := range perm.Ipv6Ranges { - desc := aws.StringValue(ip.Description) + desc := aws.ToString(ip.Description) rule := initSecurityGroupRule(ruleMap, perm, desc) @@ -683,7 +685,7 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, if len(perm.PrefixListIds) > 0 { for _, pl := range perm.PrefixListIds { - desc := aws.StringValue(pl.Description) + desc := aws.ToString(pl.Description) rule := initSecurityGroupRule(ruleMap, perm, desc) @@ -697,14 +699,14 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, } } - groups := FlattenSecurityGroups(perm.UserIdGroupPairs, ownerId) + groups := flattenSecurityGroups(perm.UserIdGroupPairs, ownerId) if len(groups) > 0 { for _, g := range groups { - desc := aws.StringValue(g.Description) + desc := aws.ToString(g.Description) rule := initSecurityGroupRule(ruleMap, perm, desc) - if aws.StringValue(g.GroupId) == groupId { + if aws.ToString(g.GroupId) == groupId { rule["self"] = true continue } @@ -733,7 +735,7 @@ func SecurityGroupIPPermGather(groupId string, permissions []*ec2.IpPermission, return rules } -func updateSecurityGroupRules(ctx context.Context, conn *ec2.EC2, d *schema.ResourceData, ruleType string, group *ec2.SecurityGroup) error { +func updateSecurityGroupRules(ctx context.Context, conn *ec2.Client, d *schema.ResourceData, ruleType string, group *awstypes.SecurityGroup) error { if !d.HasChange(ruleType) { return nil } @@ -746,16 +748,16 @@ func updateSecurityGroupRules(ctx context.Context, conn *ec2.EC2, d *schema.Reso n = new(schema.Set) } - os := SecurityGroupExpandRules(o.(*schema.Set)) - ns := SecurityGroupExpandRules(n.(*schema.Set)) + os := securityGroupExpandRules(o.(*schema.Set)) + ns := securityGroupExpandRules(n.(*schema.Set)) - del, err := ExpandIPPerms(group, SecurityGroupCollapseRules(ruleType, os.Difference(ns).List())) + del, err := expandIPPerms(group, securityGroupCollapseRules(ruleType, os.Difference(ns).List())) if err != nil { return fmt.Errorf("updating rules: %w", err) } - add, err := ExpandIPPerms(group, SecurityGroupCollapseRules(ruleType, ns.Difference(os).List())) + add, err := expandIPPerms(group, securityGroupCollapseRules(ruleType, ns.Difference(os).List())) if err != nil { return fmt.Errorf("updating rules: %w", err) @@ -777,14 +779,14 @@ func updateSecurityGroupRules(ctx context.Context, conn *ec2.EC2, d *schema.Reso IpPermissions: del, } - _, err = conn.RevokeSecurityGroupEgressWithContext(ctx, input) + _, err = conn.RevokeSecurityGroupEgress(ctx, input) } else { input := &ec2.RevokeSecurityGroupIngressInput{ GroupId: group.GroupId, IpPermissions: del, } - _, err = conn.RevokeSecurityGroupIngressWithContext(ctx, input) + _, err = conn.RevokeSecurityGroupIngress(ctx, input) } if err != nil { @@ -799,14 +801,14 @@ func updateSecurityGroupRules(ctx context.Context, conn *ec2.EC2, d *schema.Reso IpPermissions: add, } - _, err = conn.AuthorizeSecurityGroupEgressWithContext(ctx, input) + _, err = conn.AuthorizeSecurityGroupEgress(ctx, input) } else { input := &ec2.AuthorizeSecurityGroupIngressInput{ GroupId: group.GroupId, IpPermissions: add, } - _, err = conn.AuthorizeSecurityGroupIngressWithContext(ctx, input) + _, err = conn.AuthorizeSecurityGroupIngress(ctx, input) } if err != nil { @@ -821,17 +823,17 @@ func updateSecurityGroupRules(ctx context.Context, conn *ec2.EC2, d *schema.Reso // group rules and returns EC2 API compatible objects. This function will error // if it finds invalid permissions input, namely a protocol of "-1" with either // to_port or from_port set to a non-zero value. -func ExpandIPPerms(group *ec2.SecurityGroup, configured []interface{}) ([]*ec2.IpPermission, error) { - perms := make([]*ec2.IpPermission, len(configured)) +func expandIPPerms(group *awstypes.SecurityGroup, configured []interface{}) ([]awstypes.IpPermission, error) { + perms := make([]awstypes.IpPermission, len(configured)) for i, mRaw := range configured { - var perm ec2.IpPermission + var perm awstypes.IpPermission m := mRaw.(map[string]interface{}) perm.IpProtocol = aws.String(protocolForValue(m[names.AttrProtocol].(string))) - if protocol, fromPort, toPort := aws.StringValue(perm.IpProtocol), m["from_port"].(int), m["to_port"].(int); protocol != "-1" { - perm.FromPort = aws.Int64(int64(fromPort)) - perm.ToPort = aws.Int64(int64(toPort)) + if protocol, fromPort, toPort := aws.ToString(perm.IpProtocol), m["from_port"].(int), m["to_port"].(int); protocol != "-1" { + perm.FromPort = aws.Int32(int32(fromPort)) + perm.ToPort = aws.Int32(int32(toPort)) } else if fromPort != 0 || toPort != 0 { // When protocol is "-1", AWS won't store any ports for the // rule, but also won't error if the user specifies ports other @@ -851,18 +853,18 @@ func ExpandIPPerms(group *ec2.SecurityGroup, configured []interface{}) ([]*ec2.I } } if v, ok := m["self"]; ok && v.(bool) { - groups = append(groups, aws.StringValue(group.GroupId)) + groups = append(groups, aws.ToString(group.GroupId)) } if len(groups) > 0 { - perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, len(groups)) + perm.UserIdGroupPairs = make([]awstypes.UserIdGroupPair, len(groups)) for i, name := range groups { ownerId, id := "", name if items := strings.Split(id, "/"); len(items) > 1 { ownerId, id = items[0], items[1] } - perm.UserIdGroupPairs[i] = &ec2.UserIdGroupPair{ + perm.UserIdGroupPairs[i] = awstypes.UserIdGroupPair{ GroupId: aws.String(id), } @@ -875,49 +877,49 @@ func ExpandIPPerms(group *ec2.SecurityGroup, configured []interface{}) ([]*ec2.I if raw, ok := m["cidr_blocks"]; ok { list := raw.([]interface{}) for _, v := range list { - perm.IpRanges = append(perm.IpRanges, &ec2.IpRange{CidrIp: aws.String(v.(string))}) + perm.IpRanges = append(perm.IpRanges, awstypes.IpRange{CidrIp: aws.String(v.(string))}) } } if raw, ok := m["ipv6_cidr_blocks"]; ok { list := raw.([]interface{}) for _, v := range list { - perm.Ipv6Ranges = append(perm.Ipv6Ranges, &ec2.Ipv6Range{CidrIpv6: aws.String(v.(string))}) + perm.Ipv6Ranges = append(perm.Ipv6Ranges, awstypes.Ipv6Range{CidrIpv6: aws.String(v.(string))}) } } if raw, ok := m["prefix_list_ids"]; ok { list := raw.([]interface{}) for _, v := range list { - perm.PrefixListIds = append(perm.PrefixListIds, &ec2.PrefixListId{PrefixListId: aws.String(v.(string))}) + perm.PrefixListIds = append(perm.PrefixListIds, awstypes.PrefixListId{PrefixListId: aws.String(v.(string))}) } } if raw, ok := m[names.AttrDescription]; ok { description := raw.(string) if description != "" { - for _, v := range perm.IpRanges { - v.Description = aws.String(description) + for i := range perm.IpRanges { + perm.IpRanges[i].Description = aws.String(description) } - for _, v := range perm.Ipv6Ranges { - v.Description = aws.String(description) + for i := range perm.Ipv6Ranges { + perm.Ipv6Ranges[i].Description = aws.String(description) } - for _, v := range perm.PrefixListIds { - v.Description = aws.String(description) + for i := range perm.PrefixListIds { + perm.PrefixListIds[i].Description = aws.String(description) } - for _, v := range perm.UserIdGroupPairs { - v.Description = aws.String(description) + for i := range perm.UserIdGroupPairs { + perm.UserIdGroupPairs[i].Description = aws.String(description) } } } - perms[i] = &perm + perms[i] = perm } return perms, nil } // Like ec2.GroupIdentifier but with additional rule description. -type GroupIdentifier struct { +type groupIdentifier struct { // The ID of the security group. GroupId *string @@ -928,22 +930,22 @@ type GroupIdentifier struct { } // Flattens an array of UserSecurityGroups into a []*GroupIdentifier -func FlattenSecurityGroups(list []*ec2.UserIdGroupPair, ownerId *string) []*GroupIdentifier { - result := make([]*GroupIdentifier, 0, len(list)) +func flattenSecurityGroups(list []awstypes.UserIdGroupPair, ownerId *string) []*groupIdentifier { + result := make([]*groupIdentifier, 0, len(list)) for _, g := range list { var userID string - if aws.StringValue(g.UserId) != "" && (ownerId == nil || aws.StringValue(ownerId) != aws.StringValue(g.UserId)) { - userID = aws.StringValue(g.UserId) + if aws.ToString(g.UserId) != "" && (ownerId == nil || aws.ToString(ownerId) != aws.ToString(g.UserId)) { + userID = aws.ToString(g.UserId) } // userid nil here for same vpc groups - id := aws.StringValue(g.GroupId) + id := aws.ToString(g.GroupId) if userID != "" { id = userID + "/" + id } - result = append(result, &GroupIdentifier{ + result = append(result, &groupIdentifier{ GroupId: aws.String(id), Description: g.Description, }) @@ -952,7 +954,7 @@ func FlattenSecurityGroups(list []*ec2.UserIdGroupPair, ownerId *string) []*Grou return result } -// MatchRules receives the group id, type of rules, and the local / remote maps +// matchRules receives the group id, type of rules, and the local / remote maps // of rules. We iterate through the local set of rules trying to find a matching // remote rule, which may be structured differently because of how AWS // aggregates the rules under the to, from, and type. @@ -962,7 +964,7 @@ func FlattenSecurityGroups(list []*ec2.UserIdGroupPair, ownerId *string) []*Grou // // If no match is found, we'll write the remote rule to state and let the graph // sort things out -func MatchRules(rType string, local []interface{}, remote []map[string]interface{}) []map[string]interface{} { +func matchRules(rType string, local []interface{}, remote []map[string]interface{}) []map[string]interface{} { // For each local ip or security_group, we need to match against the remote // ruleSet until all ips or security_groups are found @@ -980,7 +982,7 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface // matching against self is required to detect rules that only include self // as the rule. SecurityGroupIPPermGather parses the group out // and replaces it with self if it's ID is found - localHash := idHash(rType, l[names.AttrProtocol].(string), int64(l["to_port"].(int)), int64(l["from_port"].(int)), selfVal) + localHash := idHash(rType, l[names.AttrProtocol].(string), int32(l["to_port"].(int)), int32(l["from_port"].(int)), selfVal) // loop remote rules, looking for a matching hash for _, r := range remote { @@ -991,7 +993,7 @@ func MatchRules(rType string, local []interface{}, remote []map[string]interface // hash this remote rule and compare it for a match consideration with the // local rule we're examining - rHash := idHash(rType, r[names.AttrProtocol].(string), r["to_port"].(int64), r["from_port"].(int64), remoteSelfVal) + rHash := idHash(rType, r[names.AttrProtocol].(string), r["to_port"].(int32), r["from_port"].(int32), remoteSelfVal) if rHash == localHash { var numExpectedCidrs, numExpectedIpv6Cidrs, numExpectedPrefixLists, numExpectedSGs, numRemoteCidrs, numRemoteIpv6Cidrs, numRemotePrefixLists, numRemoteSGs int var matchingCidrs []string @@ -1296,11 +1298,11 @@ func resourceSecurityGroupCopyRule(src map[string]interface{}, self bool, k stri // Given a set of SG rules (ingress/egress blocks), this function // will group the rules by from_port/to_port/protocol/description // tuples. This is inverse operation of -// SecurityGroupExpandRules() +// securityGroupExpandRules() // // For more detail, see comments for -// SecurityGroupExpandRules() -func SecurityGroupCollapseRules(ruleset string, rules []interface{}) []interface{} { +// securityGroupExpandRules() +func securityGroupCollapseRules(ruleset string, rules []interface{}) []interface{} { var keys_to_collapse = []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", names.AttrSecurityGroups} collapsed := make(map[string]map[string]interface{}) @@ -1308,7 +1310,7 @@ func SecurityGroupCollapseRules(ruleset string, rules []interface{}) []interface for _, rule := range rules { r := rule.(map[string]interface{}) - ruleHash := idCollapseHash(ruleset, r[names.AttrProtocol].(string), int64(r["to_port"].(int)), int64(r["from_port"].(int)), r[names.AttrDescription].(string)) + ruleHash := idCollapseHash(ruleset, r[names.AttrProtocol].(string), int32(r["to_port"].(int)), int32(r["from_port"].(int)), r[names.AttrDescription].(string)) if _, ok := collapsed[ruleHash]; ok { if v, ok := r["self"]; ok && v.(bool) { @@ -1341,8 +1343,8 @@ func SecurityGroupCollapseRules(ruleset string, rules []interface{}) []interface return values } -// SecurityGroupExpandRules works in pair with -// SecurityGroupCollapseRules and is used as a +// securityGroupExpandRules works in pair with +// securityGroupCollapseRules and is used as a // workaround for the problem explained in // https://github.com/hashicorp/terraform-provider-aws/pull/4726 // @@ -1382,14 +1384,14 @@ func SecurityGroupCollapseRules(ruleset string, rules []interface{}) []interface // // Then the Difference operation is executed on the new set // to find which rules got modified, and the resulting set -// is then passed to SecurityGroupCollapseRules +// is then passed to securityGroupCollapseRules // to convert the "diff" back to a more compact form for // execution. Such compact form helps reduce the number of // API calls. -func SecurityGroupExpandRules(rules *schema.Set) *schema.Set { +func securityGroupExpandRules(rules *schema.Set) *schema.Set { var keys_to_expand = []string{"cidr_blocks", "ipv6_cidr_blocks", "prefix_list_ids", names.AttrSecurityGroups} - normalized := schema.NewSet(SecurityGroupRuleHash, nil) + normalized := schema.NewSet(securityGroupRuleHash, nil) for _, rawRule := range rules.List() { rule := rawRule.(map[string]interface{}) @@ -1429,7 +1431,7 @@ func SecurityGroupExpandRules(rules *schema.Set) *schema.Set { // Convert type-to_port-from_port-protocol-description tuple // to a hash to use as a key in Set. -func idCollapseHash(rType, protocol string, toPort, fromPort int64, description string) string { +func idCollapseHash(rType, protocol string, toPort, fromPort int32, description string) string { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("%s-", rType)) buf.WriteString(fmt.Sprintf("%d-", toPort)) @@ -1442,7 +1444,7 @@ func idCollapseHash(rType, protocol string, toPort, fromPort int64, description // Creates a unique hash for the type, ports, and protocol, used as a key in // maps -func idHash(rType, protocol string, toPort, fromPort int64, self bool) string { +func idHash(rType, protocol string, toPort, fromPort int32, self bool) string { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("%s-", rType)) buf.WriteString(fmt.Sprintf("%d-", toPort)) @@ -1453,8 +1455,8 @@ func idHash(rType, protocol string, toPort, fromPort int64, self bool) string { return fmt.Sprintf("rule-%d", create.StringHashcode(buf.String())) } -// ProtocolStateFunc ensures we only store a string in any protocol field -func ProtocolStateFunc(v interface{}) string { +// protocolStateFunc ensures we only store a string in any protocol field +func protocolStateFunc(v interface{}) string { switch v := v.(type) { case string: p := protocolForValue(v) @@ -1515,21 +1517,21 @@ var securityGroupProtocolIntegers = map[string]int{ "all": -1, } -func initSecurityGroupRule(ruleMap map[string]map[string]interface{}, perm *ec2.IpPermission, desc string) map[string]interface{} { - var fromPort, toPort int64 +func initSecurityGroupRule(ruleMap map[string]map[string]interface{}, perm awstypes.IpPermission, desc string) map[string]interface{} { + var fromPort, toPort int32 if v := perm.FromPort; v != nil { - fromPort = aws.Int64Value(v) + fromPort = aws.ToInt32(v) } if v := perm.ToPort; v != nil { - toPort = aws.Int64Value(v) + toPort = aws.ToInt32(v) } - k := fmt.Sprintf("%s-%d-%d-%s", *perm.IpProtocol, fromPort, toPort, desc) + k := fmt.Sprintf("%s-%d-%d-%s", aws.ToString(perm.IpProtocol), fromPort, toPort, desc) rule, ok := ruleMap[k] if !ok { rule = make(map[string]interface{}) ruleMap[k] = rule } - rule[names.AttrProtocol] = aws.StringValue(perm.IpProtocol) + rule[names.AttrProtocol] = aws.ToString(perm.IpProtocol) rule["from_port"] = fromPort rule["to_port"] = toPort if desc != "" { diff --git a/internal/service/ec2/vpc_security_group_data_source.go b/internal/service/ec2/vpc_security_group_data_source.go index 17c377677d3..dc604bf9e39 100644 --- a/internal/service/ec2/vpc_security_group_data_source.go +++ b/internal/service/ec2/vpc_security_group_data_source.go @@ -8,9 +8,9 @@ import ( "fmt" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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" @@ -22,7 +22,7 @@ import ( // @SDKDataSource("aws_security_group") // @Tags -func DataSourceSecurityGroup() *schema.Resource { +func dataSourceSecurityGroup() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceSecurityGroupRead, @@ -63,7 +63,7 @@ func DataSourceSecurityGroup() *schema.Resource { func dataSourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSecurityGroupsInput{ Filters: newAttributeFilterList( @@ -75,7 +75,7 @@ func dataSourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, me } if v, ok := d.GetOk(names.AttrID); ok { - input.GroupIds = aws.StringSlice([]string{v.(string)}) + input.GroupIds = []string{v.(string)} } input.Filters = append(input.Filters, newTagFilterList( @@ -91,17 +91,17 @@ func dataSourceSecurityGroupRead(ctx context.Context, d *schema.ResourceData, me input.Filters = nil } - sg, err := FindSecurityGroup(ctx, conn, input) + sg, err := findSecurityGroup(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 Security Group", err)) } - d.SetId(aws.StringValue(sg.GroupId)) + d.SetId(aws.ToString(sg.GroupId)) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: *sg.OwnerId, Resource: fmt.Sprintf("security-group/%s", *sg.GroupId), diff --git a/internal/service/ec2/vpc_security_group_egress_rule.go b/internal/service/ec2/vpc_security_group_egress_rule.go index 920636dc901..c4e109385a4 100644 --- a/internal/service/ec2/vpc_security_group_egress_rule.go +++ b/internal/service/ec2/vpc_security_group_egress_rule.go @@ -6,15 +6,16 @@ package ec2 import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-framework/resource" fwflex "github.com/hashicorp/terraform-provider-aws/internal/framework/flex" ) // @FrameworkResource("aws_vpc_security_group_egress_rule", name="Security Group Egress Rule") // @Tags(identifierAttribute="id") -// @Testing(existsType="github.com/aws/aws-sdk-go/service/ec2;ec2.SecurityGroupRule") +// @Testing(existsType="github.com/aws/aws-sdk-go-v2/service/ec2/types;types.SecurityGroupRule") func newSecurityGroupEgressRuleResource(context.Context) (resource.ResourceWithConfigure, error) { r := &securityGroupEgressRuleResource{} r.securityGroupRule = r @@ -35,35 +36,35 @@ func (*securityGroupEgressRuleResource) MoveState(ctx context.Context) []resourc } func (r *securityGroupEgressRuleResource) create(ctx context.Context, data *securityGroupRuleResourceModel) (string, error) { - conn := r.Meta().EC2Conn(ctx) + conn := r.Meta().EC2Client(ctx) input := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: fwflex.StringFromFramework(ctx, data.SecurityGroupID), - IpPermissions: []*ec2.IpPermission{data.expandIPPermission(ctx)}, + IpPermissions: []awstypes.IpPermission{data.expandIPPermission(ctx)}, } - output, err := conn.AuthorizeSecurityGroupEgressWithContext(ctx, input) + output, err := conn.AuthorizeSecurityGroupEgress(ctx, input) if err != nil { return "", err } - return aws.StringValue(output.SecurityGroupRules[0].SecurityGroupRuleId), nil + return aws.ToString(output.SecurityGroupRules[0].SecurityGroupRuleId), nil } func (r *securityGroupEgressRuleResource) delete(ctx context.Context, data *securityGroupRuleResourceModel) error { - conn := r.Meta().EC2Conn(ctx) + conn := r.Meta().EC2Client(ctx) - _, err := conn.RevokeSecurityGroupEgressWithContext(ctx, &ec2.RevokeSecurityGroupEgressInput{ + _, err := conn.RevokeSecurityGroupEgress(ctx, &ec2.RevokeSecurityGroupEgressInput{ GroupId: fwflex.StringFromFramework(ctx, data.SecurityGroupID), - SecurityGroupRuleIds: fwflex.StringSliceFromFramework(ctx, data.ID), - }) + SecurityGroupRuleIds: fwflex.StringSliceValueFromFramework(ctx, data.ID)}, + ) return err } -func (r *securityGroupEgressRuleResource) findByID(ctx context.Context, id string) (*ec2.SecurityGroupRule, error) { - conn := r.Meta().EC2Conn(ctx) +func (r *securityGroupEgressRuleResource) findByID(ctx context.Context, id string) (*awstypes.SecurityGroupRule, error) { + conn := r.Meta().EC2Client(ctx) - return FindSecurityGroupEgressRuleByID(ctx, conn, id) + return findSecurityGroupEgressRuleByID(ctx, conn, id) } diff --git a/internal/service/ec2/vpc_security_group_egress_rule_tags_gen_test.go b/internal/service/ec2/vpc_security_group_egress_rule_tags_gen_test.go index 688827af18e..3388956a545 100644 --- a/internal/service/ec2/vpc_security_group_egress_rule_tags_gen_test.go +++ b/internal/service/ec2/vpc_security_group_egress_rule_tags_gen_test.go @@ -5,7 +5,7 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-testing/config" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -19,7 +19,7 @@ import ( func TestAccVPCSecurityGroupEgressRule_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -192,7 +192,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_null(t *testing.T) { t.Skip("Tags with null values are not correctly handled with the Plugin Framework") ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -251,7 +251,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_null(t *testing.T) { func TestAccVPCSecurityGroupEgressRule_tags_AddOnUpdate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -327,7 +327,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_AddOnUpdate(t *testing.T) { func TestAccVPCSecurityGroupEgressRule_tags_EmptyTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -413,7 +413,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_EmptyTag_OnCreate(t *testing.T) { func TestAccVPCSecurityGroupEgressRule_tags_EmptyTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -542,7 +542,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_EmptyTag_OnUpdate_Add(t *testing.T) func TestAccVPCSecurityGroupEgressRule_tags_EmptyTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -626,7 +626,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_EmptyTag_OnUpdate_Replace(t *testing func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_providerOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -807,7 +807,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_providerOnly(t *testing. func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_nonOverlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -967,7 +967,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_nonOverlapping(t *testin func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_overlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1143,7 +1143,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_overlapping(t *testing.T func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_updateToProviderOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1233,7 +1233,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_updateToProviderOnly(t * func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_updateToResourceOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1322,7 +1322,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_updateToResourceOnly(t * func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_emptyResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1388,7 +1388,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_emptyResourceTag(t *test func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_emptyProviderOnlyTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1448,7 +1448,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_nullOverlappingResourceT t.Skip("Tags with null values are not correctly handled with the Plugin Framework") ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1512,7 +1512,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_nullNonOverlappingResour t.Skip("Tags with null values are not correctly handled with the Plugin Framework") ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1574,7 +1574,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_DefaultTags_nullNonOverlappingResour func TestAccVPCSecurityGroupEgressRule_tags_ComputedTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1628,7 +1628,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_ComputedTag_OnCreate(t *testing.T) { func TestAccVPCSecurityGroupEgressRule_tags_ComputedTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1718,7 +1718,7 @@ func TestAccVPCSecurityGroupEgressRule_tags_ComputedTag_OnUpdate_Add(t *testing. func TestAccVPCSecurityGroupEgressRule_tags_ComputedTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_egress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) diff --git a/internal/service/ec2/vpc_security_group_egress_rule_test.go b/internal/service/ec2/vpc_security_group_egress_rule_test.go index bb1e296d287..edd2179109e 100644 --- a/internal/service/ec2/vpc_security_group_egress_rule_test.go +++ b/internal/service/ec2/vpc_security_group_egress_rule_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -21,7 +21,7 @@ import ( func TestAccVPCSecurityGroupEgressRule_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_egress_rule.test" @@ -59,7 +59,7 @@ func TestAccVPCSecurityGroupEgressRule_basic(t *testing.T) { func TestAccVPCSecurityGroupEgressRule_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_egress_rule.test" @@ -83,7 +83,7 @@ func TestAccVPCSecurityGroupEgressRule_disappears(t *testing.T) { func testAccCheckSecurityGroupEgressRuleDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_security_group_egress_rule" { @@ -107,7 +107,7 @@ func testAccCheckSecurityGroupEgressRuleDestroy(ctx context.Context) resource.Te } } -func testAccCheckSecurityGroupEgressRuleExists(ctx context.Context, n string, v *ec2.SecurityGroupRule) resource.TestCheckFunc { +func testAccCheckSecurityGroupEgressRuleExists(ctx context.Context, n string, v *awstypes.SecurityGroupRule) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -118,7 +118,7 @@ func testAccCheckSecurityGroupEgressRuleExists(ctx context.Context, n string, v return fmt.Errorf("No VPC Security Group Egress Rule ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindSecurityGroupEgressRuleByID(ctx, conn, rs.Primary.ID) diff --git a/internal/service/ec2/vpc_security_group_ingress_rule.go b/internal/service/ec2/vpc_security_group_ingress_rule.go index 9d5de83433c..318432e2d8e 100644 --- a/internal/service/ec2/vpc_security_group_ingress_rule.go +++ b/internal/service/ec2/vpc_security_group_ingress_rule.go @@ -8,9 +8,10 @@ import ( "fmt" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts" "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" "github.com/hashicorp/terraform-plugin-framework-validators/resourcevalidator" @@ -42,7 +43,7 @@ import ( // @FrameworkResource("aws_vpc_security_group_ingress_rule", name="Security Group Ingress Rule") // @Tags(identifierAttribute="id") -// @Testing(existsType="github.com/aws/aws-sdk-go/service/ec2;ec2.SecurityGroupRule") +// @Testing(existsType="github.com/aws/aws-sdk-go-v2/service/ec2/types;types.SecurityGroupRule") func newSecurityGroupIngressRuleResource(context.Context) (resource.ResourceWithConfigure, error) { r := &securityGroupIngressRuleResource{} r.securityGroupRule = r @@ -68,37 +69,37 @@ func (r *securityGroupIngressRuleResource) MoveState(ctx context.Context) []reso } func (r *securityGroupIngressRuleResource) create(ctx context.Context, data *securityGroupRuleResourceModel) (string, error) { - conn := r.Meta().EC2Conn(ctx) + conn := r.Meta().EC2Client(ctx) input := &ec2.AuthorizeSecurityGroupIngressInput{ GroupId: fwflex.StringFromFramework(ctx, data.SecurityGroupID), - IpPermissions: []*ec2.IpPermission{data.expandIPPermission(ctx)}, + IpPermissions: []awstypes.IpPermission{data.expandIPPermission(ctx)}, } - output, err := conn.AuthorizeSecurityGroupIngressWithContext(ctx, input) + output, err := conn.AuthorizeSecurityGroupIngress(ctx, input) if err != nil { return "", err } - return aws.StringValue(output.SecurityGroupRules[0].SecurityGroupRuleId), nil + return aws.ToString(output.SecurityGroupRules[0].SecurityGroupRuleId), nil } func (r *securityGroupIngressRuleResource) delete(ctx context.Context, data *securityGroupRuleResourceModel) error { - conn := r.Meta().EC2Conn(ctx) + conn := r.Meta().EC2Client(ctx) - _, err := conn.RevokeSecurityGroupIngressWithContext(ctx, &ec2.RevokeSecurityGroupIngressInput{ + _, err := conn.RevokeSecurityGroupIngress(ctx, &ec2.RevokeSecurityGroupIngressInput{ GroupId: fwflex.StringFromFramework(ctx, data.SecurityGroupID), - SecurityGroupRuleIds: fwflex.StringSliceFromFramework(ctx, data.ID), + SecurityGroupRuleIds: fwflex.StringSliceValueFromFramework(ctx, data.ID), }) return err } -func (r *securityGroupIngressRuleResource) findByID(ctx context.Context, id string) (*ec2.SecurityGroupRule, error) { - conn := r.Meta().EC2Conn(ctx) +func (r *securityGroupIngressRuleResource) findByID(ctx context.Context, id string) (*awstypes.SecurityGroupRule, error) { + conn := r.Meta().EC2Client(ctx) - return FindSecurityGroupIngressRuleByID(ctx, conn, id) + return findSecurityGroupIngressRuleByID(ctx, conn, id) } // moveStateResourceSecurityGroupRule transforms the state of an `aws_security_group_rule` resource to this resource's schema. @@ -163,7 +164,7 @@ func (r *securityGroupIngressRuleResource) moveStateResourceSecurityGroupRule(ct type securityGroupRule interface { create(context.Context, *securityGroupRuleResourceModel) (string, error) delete(context.Context, *securityGroupRuleResourceModel) error - findByID(context.Context, string) (*ec2.SecurityGroupRule, error) + findByID(context.Context, string) (*awstypes.SecurityGroupRule, error) } type securityGroupRuleResource struct { @@ -257,7 +258,7 @@ func (r *securityGroupRuleResource) Create(ctx context.Context, request resource data.SecurityGroupRuleID = types.StringValue(securityGroupRuleID) data.setID() - conn := r.Meta().EC2Conn(ctx) + conn := r.Meta().EC2Client(ctx) if err := createTags(ctx, conn, data.ID.ValueString(), getTagsIn(ctx)); err != nil { response.Diagnostics.AddError(fmt.Sprintf("setting VPC Security Group Rule (%s) tags", data.ID.ValueString()), err.Error()) @@ -306,15 +307,15 @@ func (r *securityGroupRuleResource) Read(ctx context.Context, request resource.R data.SecurityGroupRuleID = fwflex.StringToFramework(ctx, output.SecurityGroupRuleId) // If planned from_port or to_port are null and values of -1 are returned, propagate null. - if v := aws.Int64Value(output.FromPort); v == -1 && data.FromPort.IsNull() { + if v := aws.ToInt32(output.FromPort); v == -1 && data.FromPort.IsNull() { data.FromPort = types.Int64Null() } else { - data.FromPort = fwflex.Int64ToFramework(ctx, output.FromPort) + data.FromPort = fwflex.Int32ToFramework(ctx, output.FromPort) } - if v := aws.Int64Value(output.ToPort); v == -1 && data.ToPort.IsNull() { + if v := aws.ToInt32(output.ToPort); v == -1 && data.ToPort.IsNull() { data.ToPort = types.Int64Null() } else { - data.ToPort = fwflex.Int64ToFramework(ctx, output.ToPort) + data.ToPort = fwflex.Int32ToFramework(ctx, output.ToPort) } setTagsOut(ctx, output.Tags) @@ -333,7 +334,7 @@ func (r *securityGroupRuleResource) Update(ctx context.Context, request resource return } - conn := r.Meta().EC2Conn(ctx) + conn := r.Meta().EC2Client(ctx) if !new.CIDRIPv4.Equal(old.CIDRIPv4) || !new.CIDRIPv6.Equal(old.CIDRIPv6) || @@ -345,13 +346,13 @@ func (r *securityGroupRuleResource) Update(ctx context.Context, request resource !new.ToPort.Equal(old.ToPort) { input := &ec2.ModifySecurityGroupRulesInput{ GroupId: fwflex.StringFromFramework(ctx, new.SecurityGroupID), - SecurityGroupRules: []*ec2.SecurityGroupRuleUpdate{{ + SecurityGroupRules: []awstypes.SecurityGroupRuleUpdate{{ SecurityGroupRule: new.expandSecurityGroupRuleRequest(ctx), SecurityGroupRuleId: fwflex.StringFromFramework(ctx, new.ID), }}, } - _, err := conn.ModifySecurityGroupRulesWithContext(ctx, input) + _, err := conn.ModifySecurityGroupRules(ctx, input) if err != nil { response.Diagnostics.AddError(fmt.Sprintf("updating VPC Security Group Rule (%s)", new.ID.ValueString()), err.Error()) @@ -422,17 +423,17 @@ func (r *securityGroupRuleResource) securityGroupRuleARN(_ context.Context, id s return types.StringValue(r.RegionalARN(names.EC2, fmt.Sprintf("security-group-rule/%s", id))) } -func flattenReferencedSecurityGroup(ctx context.Context, apiObject *ec2.ReferencedSecurityGroup, accountID string) types.String { +func flattenReferencedSecurityGroup(ctx context.Context, apiObject *awstypes.ReferencedSecurityGroup, accountID string) types.String { if apiObject == nil { return types.StringNull() } - if apiObject.UserId == nil || aws.StringValue(apiObject.UserId) == accountID { + if apiObject.UserId == nil || aws.ToString(apiObject.UserId) == accountID { return fwflex.StringToFramework(ctx, apiObject.GroupId) } // [UserID/]GroupID. - return types.StringValue(strings.Join([]string{aws.StringValue(apiObject.UserId), aws.StringValue(apiObject.GroupId)}, "/")) + return types.StringValue(strings.Join([]string{aws.ToString(apiObject.UserId), aws.ToString(apiObject.GroupId)}, "/")) } type securityGroupRuleResourceModel struct { @@ -462,36 +463,36 @@ func (model *securityGroupRuleResourceModel) setID() { model.ID = model.SecurityGroupRuleID } -func (model *securityGroupRuleResourceModel) expandIPPermission(ctx context.Context) *ec2.IpPermission { - apiObject := &ec2.IpPermission{ - FromPort: fwflex.Int64FromFramework(ctx, model.FromPort), +func (model *securityGroupRuleResourceModel) expandIPPermission(ctx context.Context) awstypes.IpPermission { + apiObject := awstypes.IpPermission{ + FromPort: fwflex.Int32FromFramework(ctx, model.FromPort), IpProtocol: fwflex.StringFromFramework(ctx, model.IPProtocol), - ToPort: fwflex.Int64FromFramework(ctx, model.ToPort), + ToPort: fwflex.Int32FromFramework(ctx, model.ToPort), } if !model.CIDRIPv4.IsNull() { - apiObject.IpRanges = []*ec2.IpRange{{ + apiObject.IpRanges = []awstypes.IpRange{{ CidrIp: fwflex.StringFromFramework(ctx, model.CIDRIPv4), Description: fwflex.StringFromFramework(ctx, model.Description), }} } if !model.CIDRIPv6.IsNull() { - apiObject.Ipv6Ranges = []*ec2.Ipv6Range{{ + apiObject.Ipv6Ranges = []awstypes.Ipv6Range{{ CidrIpv6: fwflex.StringFromFramework(ctx, model.CIDRIPv6), Description: fwflex.StringFromFramework(ctx, model.Description), }} } if !model.PrefixListID.IsNull() { - apiObject.PrefixListIds = []*ec2.PrefixListId{{ + apiObject.PrefixListIds = []awstypes.PrefixListId{{ PrefixListId: fwflex.StringFromFramework(ctx, model.PrefixListID), Description: fwflex.StringFromFramework(ctx, model.Description), }} } if !model.ReferencedSecurityGroupID.IsNull() { - apiObject.UserIdGroupPairs = []*ec2.UserIdGroupPair{{ + apiObject.UserIdGroupPairs = []awstypes.UserIdGroupPair{{ Description: fwflex.StringFromFramework(ctx, model.Description), }} @@ -507,16 +508,16 @@ func (model *securityGroupRuleResourceModel) expandIPPermission(ctx context.Cont return apiObject } -func (model *securityGroupRuleResourceModel) expandSecurityGroupRuleRequest(ctx context.Context) *ec2.SecurityGroupRuleRequest { - apiObject := &ec2.SecurityGroupRuleRequest{ +func (model *securityGroupRuleResourceModel) expandSecurityGroupRuleRequest(ctx context.Context) *awstypes.SecurityGroupRuleRequest { + apiObject := &awstypes.SecurityGroupRuleRequest{ CidrIpv4: fwflex.StringFromFramework(ctx, model.CIDRIPv4), CidrIpv6: fwflex.StringFromFramework(ctx, model.CIDRIPv6), Description: fwflex.StringFromFramework(ctx, model.Description), - FromPort: fwflex.Int64FromFramework(ctx, model.FromPort), + FromPort: fwflex.Int32FromFramework(ctx, model.FromPort), IpProtocol: fwflex.StringFromFramework(ctx, model.IPProtocol), PrefixListId: fwflex.StringFromFramework(ctx, model.PrefixListID), ReferencedGroupId: fwflex.StringFromFramework(ctx, model.ReferencedSecurityGroupID), - ToPort: fwflex.Int64FromFramework(ctx, model.ToPort), + ToPort: fwflex.Int32FromFramework(ctx, model.ToPort), } return apiObject diff --git a/internal/service/ec2/vpc_security_group_ingress_rule_tags_gen_test.go b/internal/service/ec2/vpc_security_group_ingress_rule_tags_gen_test.go index 5c69a8c4781..57791551ad6 100644 --- a/internal/service/ec2/vpc_security_group_ingress_rule_tags_gen_test.go +++ b/internal/service/ec2/vpc_security_group_ingress_rule_tags_gen_test.go @@ -5,7 +5,7 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-testing/config" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -19,7 +19,7 @@ import ( func TestAccVPCSecurityGroupIngressRule_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -192,7 +192,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_null(t *testing.T) { t.Skip("Tags with null values are not correctly handled with the Plugin Framework") ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -251,7 +251,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_null(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_tags_AddOnUpdate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -327,7 +327,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_AddOnUpdate(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_tags_EmptyTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -413,7 +413,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_EmptyTag_OnCreate(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_tags_EmptyTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -542,7 +542,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_EmptyTag_OnUpdate_Add(t *testing.T) func TestAccVPCSecurityGroupIngressRule_tags_EmptyTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -626,7 +626,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_EmptyTag_OnUpdate_Replace(t *testin func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_providerOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -807,7 +807,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_providerOnly(t *testing func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_nonOverlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -967,7 +967,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_nonOverlapping(t *testi func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_overlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1143,7 +1143,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_overlapping(t *testing. func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_updateToProviderOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1233,7 +1233,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_updateToProviderOnly(t func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_updateToResourceOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1322,7 +1322,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_updateToResourceOnly(t func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_emptyResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1388,7 +1388,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_emptyResourceTag(t *tes func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_emptyProviderOnlyTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1448,7 +1448,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_nullOverlappingResource t.Skip("Tags with null values are not correctly handled with the Plugin Framework") ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1512,7 +1512,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_nullNonOverlappingResou t.Skip("Tags with null values are not correctly handled with the Plugin Framework") ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1574,7 +1574,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_DefaultTags_nullNonOverlappingResou func TestAccVPCSecurityGroupIngressRule_tags_ComputedTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1628,7 +1628,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_ComputedTag_OnCreate(t *testing.T) func TestAccVPCSecurityGroupIngressRule_tags_ComputedTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1718,7 +1718,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_ComputedTag_OnUpdate_Add(t *testing func TestAccVPCSecurityGroupIngressRule_tags_ComputedTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v types.SecurityGroupRule resourceName := "aws_vpc_security_group_ingress_rule.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) diff --git a/internal/service/ec2/vpc_security_group_ingress_rule_test.go b/internal/service/ec2/vpc_security_group_ingress_rule_test.go index f8fe6484783..ba4573bad3d 100644 --- a/internal/service/ec2/vpc_security_group_ingress_rule_test.go +++ b/internal/service/ec2/vpc_security_group_ingress_rule_test.go @@ -10,8 +10,8 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-framework/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -65,7 +65,7 @@ func TestIPProtocol(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -103,7 +103,7 @@ func TestAccVPCSecurityGroupIngressRule_basic(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -127,7 +127,7 @@ func TestAccVPCSecurityGroupIngressRule_disappears(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_tags_defaultAndIgnoreTags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -165,7 +165,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_defaultAndIgnoreTags(t *testing.T) func TestAccVPCSecurityGroupIngressRule_tags_ignoreTags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -203,7 +203,7 @@ func TestAccVPCSecurityGroupIngressRule_tags_ignoreTags(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_cidrIPv4(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.SecurityGroupRule + var v1, v2 awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -259,7 +259,7 @@ func TestAccVPCSecurityGroupIngressRule_cidrIPv4(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_cidrIPv6(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.SecurityGroupRule + var v1, v2 awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -315,7 +315,7 @@ func TestAccVPCSecurityGroupIngressRule_cidrIPv6(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_description(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.SecurityGroupRule + var v1, v2 awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -351,7 +351,7 @@ func TestAccVPCSecurityGroupIngressRule_description(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_prefixListID(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.SecurityGroupRule + var v1, v2 awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" vpcEndpoint1ResourceName := "aws_vpc_endpoint.test1" @@ -409,7 +409,7 @@ func TestAccVPCSecurityGroupIngressRule_prefixListID(t *testing.T) { func TestAccVPCSecurityGroupIngressRule_referencedSecurityGroupID(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.SecurityGroupRule + var v1, v2 awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" securityGroup1ResourceName := "aws_security_group.test" @@ -467,7 +467,7 @@ func TestAccVPCSecurityGroupIngressRule_referencedSecurityGroupID(t *testing.T) func TestAccVPCSecurityGroupIngressRule_ReferencedSecurityGroupID_peerVPC(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroupRule + var v awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -508,7 +508,7 @@ func TestAccVPCSecurityGroupIngressRule_ReferencedSecurityGroupID_peerVPC(t *tes func TestAccVPCSecurityGroupIngressRule_updateSourceType(t *testing.T) { ctx := acctest.Context(t) - var v1, v2 ec2.SecurityGroupRule + var v1, v2 awstypes.SecurityGroupRule rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_vpc_security_group_ingress_rule.test" @@ -562,9 +562,9 @@ func TestAccVPCSecurityGroupIngressRule_updateSourceType(t *testing.T) { }) } -func testAccCheckSecurityGroupRuleNotRecreated(i, j *ec2.SecurityGroupRule) resource.TestCheckFunc { +func testAccCheckSecurityGroupRuleNotRecreated(i, j *awstypes.SecurityGroupRule) resource.TestCheckFunc { return func(s *terraform.State) error { - if aws.StringValue(i.SecurityGroupRuleId) != aws.StringValue(j.SecurityGroupRuleId) { + if aws.ToString(i.SecurityGroupRuleId) != aws.ToString(j.SecurityGroupRuleId) { return errors.New("VPC Security Group Rule was recreated") } @@ -572,9 +572,9 @@ func testAccCheckSecurityGroupRuleNotRecreated(i, j *ec2.SecurityGroupRule) reso } } -func testAccCheckSecurityGroupRuleRecreated(i, j *ec2.SecurityGroupRule) resource.TestCheckFunc { +func testAccCheckSecurityGroupRuleRecreated(i, j *awstypes.SecurityGroupRule) resource.TestCheckFunc { return func(s *terraform.State) error { - if aws.StringValue(i.SecurityGroupRuleId) == aws.StringValue(j.SecurityGroupRuleId) { + if aws.ToString(i.SecurityGroupRuleId) == aws.ToString(j.SecurityGroupRuleId) { return errors.New("VPC Security Group Rule was not recreated") } @@ -584,7 +584,7 @@ func testAccCheckSecurityGroupRuleRecreated(i, j *ec2.SecurityGroupRule) resourc func testAccCheckSecurityGroupIngressRuleDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_vpc_security_group_ingress_rule" { @@ -608,7 +608,7 @@ func testAccCheckSecurityGroupIngressRuleDestroy(ctx context.Context) resource.T } } -func testAccCheckSecurityGroupIngressRuleExists(ctx context.Context, n string, v *ec2.SecurityGroupRule) resource.TestCheckFunc { +func testAccCheckSecurityGroupIngressRuleExists(ctx context.Context, n string, v *awstypes.SecurityGroupRule) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -619,7 +619,7 @@ func testAccCheckSecurityGroupIngressRuleExists(ctx context.Context, n string, v return fmt.Errorf("No VPC Security Group Ingress Rule ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindSecurityGroupIngressRuleByID(ctx, conn, rs.Primary.ID) @@ -633,11 +633,11 @@ func testAccCheckSecurityGroupIngressRuleExists(ctx context.Context, n string, v } } -func testAccCheckSecurityGroupIngressRuleUpdateTags(ctx context.Context, v *ec2.SecurityGroupRule, oldTags, newTags map[string]string) resource.TestCheckFunc { +func testAccCheckSecurityGroupIngressRuleUpdateTags(ctx context.Context, v *awstypes.SecurityGroupRule, oldTags, newTags map[string]string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - return tfec2.UpdateTags(ctx, conn, aws.StringValue(v.SecurityGroupRuleId), oldTags, newTags) + return tfec2.UpdateTags(ctx, conn, aws.ToString(v.SecurityGroupRuleId), oldTags, newTags) } } diff --git a/internal/service/ec2/vpc_security_group_migrate.go b/internal/service/ec2/vpc_security_group_migrate.go index 385baec959e..3551fc9046a 100644 --- a/internal/service/ec2/vpc_security_group_migrate.go +++ b/internal/service/ec2/vpc_security_group_migrate.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func SecurityGroupMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { +func securityGroupMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: log.Println("[INFO] Found Security Group State v0; migrating to v1") diff --git a/internal/service/ec2/vpc_security_group_rule.go b/internal/service/ec2/vpc_security_group_rule.go index f9cab2ac0f8..54f4ed20fa8 100644 --- a/internal/service/ec2/vpc_security_group_rule.go +++ b/internal/service/ec2/vpc_security_group_rule.go @@ -13,9 +13,10 @@ import ( "strings" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -29,8 +30,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_security_group_rule") -func ResourceSecurityGroupRule() *schema.Resource { +// @SDKResource("aws_security_group_rule", name="Security Group Rule") +func resourceSecurityGroupRule() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceSecurityGroupRuleCreate, @@ -47,7 +48,7 @@ func ResourceSecurityGroupRule() *schema.Resource { }, SchemaVersion: 2, - MigrateState: SecurityGroupRuleMigrateState, + MigrateState: securityGroupRuleMigrateState, Schema: map[string]*schema.Schema{ "cidr_blocks": { @@ -104,7 +105,7 @@ func ResourceSecurityGroupRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - StateFunc: ProtocolStateFunc, + StateFunc: protocolStateFunc, }, "security_group_id": { Type: schema.TypeString, @@ -157,13 +158,13 @@ func ResourceSecurityGroupRule() *schema.Resource { func resourceSecurityGroupRuleCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) securityGroupID := d.Get("security_group_id").(string) conns.GlobalMutexKV.Lock(securityGroupID) defer conns.GlobalMutexKV.Unlock(securityGroupID) - sg, err := FindSecurityGroupByID(ctx, conn, securityGroupID) + sg, err := findSecurityGroupByID(ctx, conn, securityGroupID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Security Group (%s): %s", securityGroupID, err) @@ -171,17 +172,17 @@ func resourceSecurityGroupRuleCreate(ctx context.Context, d *schema.ResourceData ipPermission := expandIPPermission(d, sg) ruleType := securityGroupRuleType(d.Get(names.AttrType).(string)) - id := SecurityGroupRuleCreateID(securityGroupID, string(ruleType), ipPermission) + id := securityGroupRuleCreateID(securityGroupID, string(ruleType), &ipPermission) switch ruleType { case securityGroupRuleTypeIngress: input := &ec2.AuthorizeSecurityGroupIngressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{ipPermission}, + IpPermissions: []awstypes.IpPermission{ipPermission}, } var output *ec2.AuthorizeSecurityGroupIngressOutput - output, err = conn.AuthorizeSecurityGroupIngressWithContext(ctx, input) + output, err = conn.AuthorizeSecurityGroupIngress(ctx, input) if err == nil { if len(output.SecurityGroupRules) == 1 { @@ -194,11 +195,11 @@ func resourceSecurityGroupRuleCreate(ctx context.Context, d *schema.ResourceData case securityGroupRuleTypeEgress: input := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{ipPermission}, + IpPermissions: []awstypes.IpPermission{ipPermission}, } var output *ec2.AuthorizeSecurityGroupEgressOutput - output, err = conn.AuthorizeSecurityGroupEgressWithContext(ctx, input) + output, err = conn.AuthorizeSecurityGroupEgress(ctx, input) if err == nil { if len(output.SecurityGroupRules) == 1 { @@ -222,13 +223,13 @@ information and instructions for recovery. Error: %s`, securityGroupID, err) } _, err = tfresource.RetryWhenNotFound(ctx, d.Timeout(schema.TimeoutCreate), func() (interface{}, error) { - sg, err := FindSecurityGroupByID(ctx, conn, securityGroupID) + sg, err := findSecurityGroupByID(ctx, conn, securityGroupID) if err != nil { return nil, err } - var rules []*ec2.IpPermission + var rules []awstypes.IpPermission if ruleType == securityGroupRuleTypeIngress { rules = sg.IpPermissions @@ -257,11 +258,11 @@ information and instructions for recovery. Error: %s`, securityGroupID, err) func resourceSecurityGroupRuleRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) securityGroupID := d.Get("security_group_id").(string) ruleType := securityGroupRuleType(d.Get(names.AttrType).(string)) - sg, err := FindSecurityGroupByID(ctx, conn, securityGroupID) + sg, err := findSecurityGroupByID(ctx, conn, securityGroupID) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Security Group (%s) not found, removing from state", securityGroupID) @@ -275,7 +276,7 @@ func resourceSecurityGroupRuleRead(ctx context.Context, d *schema.ResourceData, ipPermission := expandIPPermission(d, sg) - var rules []*ec2.IpPermission + var rules []awstypes.IpPermission if ruleType == securityGroupRuleTypeIngress { rules = sg.IpPermissions @@ -296,18 +297,21 @@ func resourceSecurityGroupRuleRead(ctx context.Context, d *schema.ResourceData, return sdkdiag.AppendErrorf(diags, "reading Security Group (%s) Rule (%s): %s", securityGroupID, d.Id(), &retry.NotFoundError{}) } - flattenIpPermission(d, ipPermission) - d.Set(names.AttrDescription, description) + flattenIpPermission(d, &ipPermission) + + if description != nil { // nosemgrep: ci.helper-schema-ResourceData-Set-extraneous-nil-check + d.Set(names.AttrDescription, description) + } d.Set(names.AttrType, ruleType) if strings.Contains(d.Id(), securityGroupRuleIDSeparator) { // import so fix the id - id := SecurityGroupRuleCreateID(securityGroupID, string(ruleType), ipPermission) + id := securityGroupRuleCreateID(securityGroupID, string(ruleType), &ipPermission) d.SetId(id) } // Attempt to find the single matching AWS Security Group Rule resource ID. - securityGroupRules, err := FindSecurityGroupRulesBySecurityGroupID(ctx, conn, securityGroupID) + securityGroupRules, err := findSecurityGroupRulesBySecurityGroupID(ctx, conn, securityGroupID) // Ignore UnsupportedOperation errors for AWS China and GovCloud (US). if tfawserr.ErrCodeEquals(err, errCodeUnsupportedOperation) { @@ -326,7 +330,7 @@ func resourceSecurityGroupRuleRead(ctx context.Context, d *schema.ResourceData, func resourceSecurityGroupRuleUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) if d.HasChange(names.AttrDescription) { securityGroupID := d.Get("security_group_id").(string) @@ -334,7 +338,7 @@ func resourceSecurityGroupRuleUpdate(ctx context.Context, d *schema.ResourceData conns.GlobalMutexKV.Lock(securityGroupID) defer conns.GlobalMutexKV.Unlock(securityGroupID) - sg, err := FindSecurityGroupByID(ctx, conn, securityGroupID) + sg, err := findSecurityGroupByID(ctx, conn, securityGroupID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Security Group (%s): %s", securityGroupID, err) @@ -347,18 +351,18 @@ func resourceSecurityGroupRuleUpdate(ctx context.Context, d *schema.ResourceData case securityGroupRuleTypeIngress: input := &ec2.UpdateSecurityGroupRuleDescriptionsIngressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{ipPermission}, + IpPermissions: []awstypes.IpPermission{ipPermission}, } - _, err = conn.UpdateSecurityGroupRuleDescriptionsIngressWithContext(ctx, input) + _, err = conn.UpdateSecurityGroupRuleDescriptionsIngress(ctx, input) case securityGroupRuleTypeEgress: input := &ec2.UpdateSecurityGroupRuleDescriptionsEgressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{ipPermission}, + IpPermissions: []awstypes.IpPermission{ipPermission}, } - _, err = conn.UpdateSecurityGroupRuleDescriptionsEgressWithContext(ctx, input) + _, err = conn.UpdateSecurityGroupRuleDescriptionsEgress(ctx, input) } if err != nil { @@ -372,13 +376,13 @@ func resourceSecurityGroupRuleUpdate(ctx context.Context, d *schema.ResourceData func resourceSecurityGroupRuleDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) securityGroupID := d.Get("security_group_id").(string) conns.GlobalMutexKV.Lock(securityGroupID) defer conns.GlobalMutexKV.Unlock(securityGroupID) - sg, err := FindSecurityGroupByID(ctx, conn, securityGroupID) + sg, err := findSecurityGroupByID(ctx, conn, securityGroupID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading Security Group (%s): %s", securityGroupID, err) @@ -391,18 +395,18 @@ func resourceSecurityGroupRuleDelete(ctx context.Context, d *schema.ResourceData case securityGroupRuleTypeIngress: input := &ec2.RevokeSecurityGroupIngressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{ipPermission}, + IpPermissions: []awstypes.IpPermission{ipPermission}, } - _, err = conn.RevokeSecurityGroupIngressWithContext(ctx, input) + _, err = conn.RevokeSecurityGroupIngress(ctx, input) case securityGroupRuleTypeEgress: input := &ec2.RevokeSecurityGroupEgressInput{ GroupId: sg.GroupId, - IpPermissions: []*ec2.IpPermission{ipPermission}, + IpPermissions: []awstypes.IpPermission{ipPermission}, } - _, err = conn.RevokeSecurityGroupEgressWithContext(ctx, input) + _, err = conn.RevokeSecurityGroupEgress(ctx, input) } if tfawserr.ErrCodeEquals(err, errCodeInvalidPermissionNotFound) { @@ -513,20 +517,20 @@ func resourceSecurityGroupRuleImport(_ context.Context, d *schema.ResourceData, return []*schema.ResourceData{d}, nil } -func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermission, string) { - var rule *ec2.IpPermission - var description string +func findRuleMatch(p awstypes.IpPermission, rules []awstypes.IpPermission) (*awstypes.IpPermission, *string) { + var rule awstypes.IpPermission + var description *string for _, r := range rules { - if p.ToPort != nil && r.ToPort != nil && aws.Int64Value(p.ToPort) != aws.Int64Value(r.ToPort) { + if p.ToPort != nil && r.ToPort != nil && aws.ToInt32(p.ToPort) != aws.ToInt32(r.ToPort) { continue } - if p.FromPort != nil && r.FromPort != nil && aws.Int64Value(p.FromPort) != aws.Int64Value(r.FromPort) { + if p.FromPort != nil && r.FromPort != nil && aws.ToInt32(p.FromPort) != aws.ToInt32(r.FromPort) { continue } - if p.IpProtocol != nil && r.IpProtocol != nil && aws.StringValue(p.IpProtocol) != aws.StringValue(r.IpProtocol) { + if p.IpProtocol != nil && r.IpProtocol != nil && aws.ToString(p.IpProtocol) != aws.ToString(r.IpProtocol) { continue } @@ -536,10 +540,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermi if v1.CidrIp == nil || v2.CidrIp == nil { continue } - if aws.StringValue(v1.CidrIp) == aws.StringValue(v2.CidrIp) { + if aws.ToString(v1.CidrIp) == aws.ToString(v2.CidrIp) { remaining-- - if v := aws.StringValue(v2.Description); v != "" && description == "" { + if v := v2.Description; v != nil && description == nil { description = v } } @@ -556,10 +560,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermi if v1.CidrIpv6 == nil || v2.CidrIpv6 == nil { continue } - if aws.StringValue(v1.CidrIpv6) == aws.StringValue(v2.CidrIpv6) { + if aws.ToString(v1.CidrIpv6) == aws.ToString(v2.CidrIpv6) { remaining-- - if v := aws.StringValue(v2.Description); v != "" && description == "" { + if v := v2.Description; v != nil && description == nil { description = v } } @@ -576,10 +580,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermi if v1.PrefixListId == nil || v2.PrefixListId == nil { continue } - if aws.StringValue(v1.PrefixListId) == aws.StringValue(v2.PrefixListId) { + if aws.ToString(v1.PrefixListId) == aws.ToString(v2.PrefixListId) { remaining-- - if v := aws.StringValue(v2.Description); v != "" && description == "" { + if v := v2.Description; v != nil && description == nil { description = v } } @@ -596,10 +600,10 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermi if v1.GroupId == nil || v2.GroupId == nil { continue } - if aws.StringValue(v1.GroupId) == aws.StringValue(v2.GroupId) { + if aws.ToString(v1.GroupId) == aws.ToString(v2.GroupId) { remaining-- - if v := aws.StringValue(v2.Description); v != "" && description == "" { + if v := v2.Description; v != nil && description == nil { description = v } } @@ -607,7 +611,7 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermi } if remaining > 0 { - description = "" + description = nil continue } @@ -615,50 +619,50 @@ func findRuleMatch(p *ec2.IpPermission, rules []*ec2.IpPermission) (*ec2.IpPermi rule = r } - return rule, description + return &rule, description } -func findSecurityGroupRuleMatch(p *ec2.IpPermission, securityGroupRules []*ec2.SecurityGroupRule, ruleType securityGroupRuleType) string { +func findSecurityGroupRuleMatch(p awstypes.IpPermission, securityGroupRules []awstypes.SecurityGroupRule, ruleType securityGroupRuleType) string { for _, r := range securityGroupRules { - if ruleType == securityGroupRuleTypeIngress && aws.BoolValue(r.IsEgress) { + if ruleType == securityGroupRuleTypeIngress && aws.ToBool(r.IsEgress) { continue } - if p.ToPort != nil && r.ToPort != nil && aws.Int64Value(p.ToPort) != aws.Int64Value(r.ToPort) { + if p.ToPort != nil && r.ToPort != nil && aws.ToInt32(p.ToPort) != aws.ToInt32(r.ToPort) { continue } - if p.FromPort != nil && r.FromPort != nil && aws.Int64Value(p.FromPort) != aws.Int64Value(r.FromPort) { + if p.FromPort != nil && r.FromPort != nil && aws.ToInt32(p.FromPort) != aws.ToInt32(r.FromPort) { continue } - if p.IpProtocol != nil && r.IpProtocol != nil && aws.StringValue(p.IpProtocol) != aws.StringValue(r.IpProtocol) { + if p.IpProtocol != nil && r.IpProtocol != nil && aws.ToString(p.IpProtocol) != aws.ToString(r.IpProtocol) { continue } // SecurityGroupRule has only a single source or destination set. if r.CidrIpv4 != nil { - if len(p.IpRanges) == 1 && aws.StringValue(p.IpRanges[0].CidrIp) == aws.StringValue(r.CidrIpv4) { + if len(p.IpRanges) == 1 && aws.ToString(p.IpRanges[0].CidrIp) == aws.ToString(r.CidrIpv4) { if len(p.Ipv6Ranges) == 0 && len(p.PrefixListIds) == 0 && len(p.UserIdGroupPairs) == 0 { - return aws.StringValue(r.SecurityGroupRuleId) + return aws.ToString(r.SecurityGroupRuleId) } } } else if r.CidrIpv6 != nil { - if len(p.Ipv6Ranges) == 1 && aws.StringValue(p.Ipv6Ranges[0].CidrIpv6) == aws.StringValue(r.CidrIpv6) { + if len(p.Ipv6Ranges) == 1 && aws.ToString(p.Ipv6Ranges[0].CidrIpv6) == aws.ToString(r.CidrIpv6) { if len(p.IpRanges) == 0 && len(p.PrefixListIds) == 0 && len(p.UserIdGroupPairs) == 0 { - return aws.StringValue(r.SecurityGroupRuleId) + return aws.ToString(r.SecurityGroupRuleId) } } } else if r.PrefixListId != nil { - if len(p.PrefixListIds) == 1 && aws.StringValue(p.PrefixListIds[0].PrefixListId) == aws.StringValue(r.PrefixListId) { + if len(p.PrefixListIds) == 1 && aws.ToString(p.PrefixListIds[0].PrefixListId) == aws.ToString(r.PrefixListId) { if len(p.IpRanges) == 0 && len(p.Ipv6Ranges) == 0 && len(p.UserIdGroupPairs) == 0 { - return aws.StringValue(r.SecurityGroupRuleId) + return aws.ToString(r.SecurityGroupRuleId) } } } else if r.ReferencedGroupInfo != nil { - if len(p.UserIdGroupPairs) == 1 && aws.StringValue(p.UserIdGroupPairs[0].GroupId) == aws.StringValue(r.ReferencedGroupInfo.GroupId) { + if len(p.UserIdGroupPairs) == 1 && aws.ToString(p.UserIdGroupPairs[0].GroupId) == aws.ToString(r.ReferencedGroupInfo.GroupId) { if len(p.IpRanges) == 0 && len(p.Ipv6Ranges) == 0 && len(p.PrefixListIds) == 0 { - return aws.StringValue(r.SecurityGroupRuleId) + return aws.ToString(r.SecurityGroupRuleId) } } } @@ -671,30 +675,30 @@ const securityGroupRuleIDSeparator = "_" // byGroupPair implements sort.Interface for []*ec2.UserIDGroupPairs based on // GroupID or GroupName field (only one should be set). -type byGroupPair []*ec2.UserIdGroupPair +type byGroupPair []awstypes.UserIdGroupPair func (b byGroupPair) Len() int { return len(b) } func (b byGroupPair) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byGroupPair) Less(i, j int) bool { if b[i].GroupId != nil && b[j].GroupId != nil { - return aws.StringValue(b[i].GroupId) < aws.StringValue(b[j].GroupId) + return aws.ToString(b[i].GroupId) < aws.ToString(b[j].GroupId) } if b[i].GroupName != nil && b[j].GroupName != nil { - return aws.StringValue(b[i].GroupName) < aws.StringValue(b[j].GroupName) + return aws.ToString(b[i].GroupName) < aws.ToString(b[j].GroupName) } //lintignore:R009 panic("mismatched security group rules, may be a terraform bug") } -func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermission) string { +func securityGroupRuleCreateID(securityGroupID, ruleType string, ip *awstypes.IpPermission) string { var buf bytes.Buffer buf.WriteString(fmt.Sprintf("%s-", securityGroupID)) - if aws.Int64Value(ip.FromPort) > 0 { + if aws.ToInt32(ip.FromPort) > 0 { buf.WriteString(fmt.Sprintf("%d-", *ip.FromPort)) } - if aws.Int64Value(ip.ToPort) > 0 { + if aws.ToInt32(ip.ToPort) > 0 { buf.WriteString(fmt.Sprintf("%d-", *ip.ToPort)) } buf.WriteString(fmt.Sprintf("%s-", *ip.IpProtocol)) @@ -705,7 +709,7 @@ func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermi if len(ip.IpRanges) > 0 { s := make([]string, len(ip.IpRanges)) for i, r := range ip.IpRanges { - s[i] = aws.StringValue(r.CidrIp) + s[i] = aws.ToString(r.CidrIp) } sort.Strings(s) @@ -717,7 +721,7 @@ func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermi if len(ip.Ipv6Ranges) > 0 { s := make([]string, len(ip.Ipv6Ranges)) for i, r := range ip.Ipv6Ranges { - s[i] = aws.StringValue(r.CidrIpv6) + s[i] = aws.ToString(r.CidrIpv6) } sort.Strings(s) @@ -729,7 +733,7 @@ func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermi if len(ip.PrefixListIds) > 0 { s := make([]string, len(ip.PrefixListIds)) for i, pl := range ip.PrefixListIds { - s[i] = aws.StringValue(pl.PrefixListId) + s[i] = aws.ToString(pl.PrefixListId) } sort.Strings(s) @@ -757,20 +761,20 @@ func SecurityGroupRuleCreateID(securityGroupID, ruleType string, ip *ec2.IpPermi return fmt.Sprintf("sgrule-%d", create.StringHashcode(buf.String())) } -func expandIPPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPermission { // nosemgrep:ci.caps5-in-func-name - apiObject := &ec2.IpPermission{ +func expandIPPermission(d *schema.ResourceData, sg *awstypes.SecurityGroup) awstypes.IpPermission { // nosemgrep:ci.caps5-in-func-name + apiObject := awstypes.IpPermission{ IpProtocol: aws.String(protocolForValue(d.Get(names.AttrProtocol).(string))), } // InvalidParameterValue: When protocol is ALL, you cannot specify from-port. - if v := aws.StringValue(apiObject.IpProtocol); v != "-1" { - apiObject.FromPort = aws.Int64(int64(d.Get("from_port").(int))) - apiObject.ToPort = aws.Int64(int64(d.Get("to_port").(int))) + if v := aws.ToString(apiObject.IpProtocol); v != "-1" { + apiObject.FromPort = aws.Int32(int32(d.Get("from_port").(int))) + apiObject.ToPort = aws.Int32(int32(d.Get("to_port").(int))) } if v, ok := d.GetOk("cidr_blocks"); ok && len(v.([]interface{})) > 0 { for _, v := range v.([]interface{}) { - apiObject.IpRanges = append(apiObject.IpRanges, &ec2.IpRange{ + apiObject.IpRanges = append(apiObject.IpRanges, awstypes.IpRange{ CidrIp: aws.String(v.(string)), }) } @@ -778,7 +782,7 @@ func expandIPPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPe if v, ok := d.GetOk("ipv6_cidr_blocks"); ok && len(v.([]interface{})) > 0 { for _, v := range v.([]interface{}) { - apiObject.Ipv6Ranges = append(apiObject.Ipv6Ranges, &ec2.Ipv6Range{ + apiObject.Ipv6Ranges = append(apiObject.Ipv6Ranges, awstypes.Ipv6Range{ CidrIpv6: aws.String(v.(string)), }) } @@ -786,7 +790,7 @@ func expandIPPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPe if v, ok := d.GetOk("prefix_list_ids"); ok && len(v.([]interface{})) > 0 { for _, v := range v.([]interface{}) { - apiObject.PrefixListIds = append(apiObject.PrefixListIds, &ec2.PrefixListId{ + apiObject.PrefixListIds = append(apiObject.PrefixListIds, awstypes.PrefixListId{ PrefixListId: aws.String(v.(string)), }) } @@ -795,8 +799,8 @@ func expandIPPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPe var self string if _, ok := d.GetOk("self"); ok { - self = aws.StringValue(sg.GroupId) - apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + self = aws.ToString(sg.GroupId) + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, awstypes.UserIdGroupPair{ GroupId: aws.String(self), }) } @@ -805,11 +809,11 @@ func expandIPPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPe if v := v.(string); v != self { // [OwnerID/]SecurityGroupID. if parts := strings.Split(v, "/"); len(parts) == 1 { - apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, awstypes.UserIdGroupPair{ GroupId: aws.String(v), }) } else { - apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, &ec2.UserIdGroupPair{ + apiObject.UserIdGroupPairs = append(apiObject.UserIdGroupPairs, awstypes.UserIdGroupPair{ GroupId: aws.String(parts[1]), UserId: aws.String(parts[0]), }) @@ -819,28 +823,27 @@ func expandIPPermission(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IpPe if v, ok := d.GetOk(names.AttrDescription); ok { description := v.(string) - - for _, v := range apiObject.IpRanges { - v.Description = aws.String(description) + for i := range apiObject.IpRanges { + apiObject.IpRanges[i].Description = aws.String(description) } - for _, v := range apiObject.Ipv6Ranges { - v.Description = aws.String(description) + for i := range apiObject.Ipv6Ranges { + apiObject.Ipv6Ranges[i].Description = aws.String(description) } - for _, v := range apiObject.PrefixListIds { - v.Description = aws.String(description) + for i := range apiObject.PrefixListIds { + apiObject.PrefixListIds[i].Description = aws.String(description) } - for _, v := range apiObject.UserIdGroupPairs { - v.Description = aws.String(description) + for i := range apiObject.UserIdGroupPairs { + apiObject.UserIdGroupPairs[i].Description = aws.String(description) } } return apiObject } -func flattenIpPermission(d *schema.ResourceData, apiObject *ec2.IpPermission) { // nosemgrep:ci.caps5-in-func-name +func flattenIpPermission(d *schema.ResourceData, apiObject *awstypes.IpPermission) { // nosemgrep:ci.caps5-in-func-name if apiObject == nil { return } @@ -853,7 +856,7 @@ func flattenIpPermission(d *schema.ResourceData, apiObject *ec2.IpPermission) { var ipRanges []string for _, v := range v { - ipRanges = append(ipRanges, aws.StringValue(v.CidrIp)) + ipRanges = append(ipRanges, aws.ToString(v.CidrIp)) } d.Set("cidr_blocks", ipRanges) @@ -863,7 +866,7 @@ func flattenIpPermission(d *schema.ResourceData, apiObject *ec2.IpPermission) { var ipv6Ranges []string for _, v := range v { - ipv6Ranges = append(ipv6Ranges, aws.StringValue(v.CidrIpv6)) + ipv6Ranges = append(ipv6Ranges, aws.ToString(v.CidrIpv6)) } d.Set("ipv6_cidr_blocks", ipv6Ranges) @@ -873,7 +876,7 @@ func flattenIpPermission(d *schema.ResourceData, apiObject *ec2.IpPermission) { var prefixListIDs []string for _, v := range v { - prefixListIDs = append(prefixListIDs, aws.StringValue(v.PrefixListId)) + prefixListIDs = append(prefixListIDs, aws.ToString(v.PrefixListId)) } d.Set("prefix_list_ids", prefixListIDs) @@ -884,10 +887,10 @@ func flattenIpPermission(d *schema.ResourceData, apiObject *ec2.IpPermission) { if old, ok := d.GetOk("source_security_group_id"); ok { // [OwnerID/]SecurityGroupID. - if parts := strings.Split(old.(string), "/"); len(parts) == 1 || aws.StringValue(v.UserId) == "" { + if parts := strings.Split(old.(string), "/"); len(parts) == 1 || aws.ToString(v.UserId) == "" { d.Set("source_security_group_id", v.GroupId) } else { - d.Set("source_security_group_id", strings.Join([]string{aws.StringValue(v.UserId), aws.StringValue(v.GroupId)}, "/")) + d.Set("source_security_group_id", strings.Join([]string{aws.ToString(v.UserId), aws.ToString(v.GroupId)}, "/")) } } } diff --git a/internal/service/ec2/vpc_security_group_rule_data_source.go b/internal/service/ec2/vpc_security_group_rule_data_source.go index 2cf7141bd8a..a3281cf095e 100644 --- a/internal/service/ec2/vpc_security_group_rule_data_source.go +++ b/internal/service/ec2/vpc_security_group_rule_data_source.go @@ -7,7 +7,7 @@ import ( "context" "fmt" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" @@ -89,7 +89,7 @@ func (d *securityGroupRuleDataSource) Read(ctx context.Context, request datasour return } - conn := d.Meta().EC2Conn(ctx) + conn := d.Meta().EC2Client(ctx) ignoreTagsConfig := d.Meta().IgnoreTagsConfig input := &ec2.DescribeSecurityGroupRulesInput{ @@ -97,7 +97,7 @@ func (d *securityGroupRuleDataSource) Read(ctx context.Context, request datasour } if !data.SecurityGroupRuleID.IsNull() { - input.SecurityGroupRuleIds = []*string{flex.StringFromFramework(ctx, data.SecurityGroupRuleID)} + input.SecurityGroupRuleIds = []string{flex.StringValueFromFramework(ctx, data.SecurityGroupRuleID)} } if len(input.Filters) == 0 { @@ -105,7 +105,7 @@ func (d *securityGroupRuleDataSource) Read(ctx context.Context, request datasour input.Filters = nil } - output, err := FindSecurityGroupRule(ctx, conn, input) + output, err := findSecurityGroupRule(ctx, conn, input) if err != nil { response.Diagnostics.AddError("reading Security Group Rules", tfresource.SingularDataSourceFindError("Security Group Rule", err).Error()) @@ -118,15 +118,15 @@ func (d *securityGroupRuleDataSource) Read(ctx context.Context, request datasour data.CIDRIPv4 = flex.StringToFramework(ctx, output.CidrIpv4) data.CIDRIPv6 = flex.StringToFramework(ctx, output.CidrIpv6) data.Description = flex.StringToFramework(ctx, output.Description) - data.FromPort = flex.Int64ToFramework(ctx, output.FromPort) + data.FromPort = flex.Int32ToFramework(ctx, output.FromPort) data.IPProtocol = flex.StringToFramework(ctx, output.IpProtocol) data.IsEgress = flex.BoolToFramework(ctx, output.IsEgress) data.PrefixListID = flex.StringToFramework(ctx, output.PrefixListId) data.ReferencedSecurityGroupID = flattenReferencedSecurityGroup(ctx, output.ReferencedGroupInfo, d.Meta().AccountID) data.SecurityGroupID = flex.StringToFramework(ctx, output.GroupId) data.SecurityGroupRuleID = flex.StringToFramework(ctx, output.SecurityGroupRuleId) - data.Tags = flex.FlattenFrameworkStringValueMapLegacy(ctx, KeyValueTags(ctx, output.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) - data.ToPort = flex.Int64ToFramework(ctx, output.ToPort) + data.Tags = flex.FlattenFrameworkStringValueMapLegacy(ctx, keyValueTags(ctx, output.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()) + data.ToPort = flex.Int32ToFramework(ctx, output.ToPort) response.Diagnostics.Append(response.State.Set(ctx, &data)...) } diff --git a/internal/service/ec2/vpc_security_group_rule_migrate.go b/internal/service/ec2/vpc_security_group_rule_migrate.go index 2ac6e3dbcb9..eff9e9bccd5 100644 --- a/internal/service/ec2/vpc_security_group_rule_migrate.go +++ b/internal/service/ec2/vpc_security_group_rule_migrate.go @@ -9,13 +9,13 @@ import ( "strconv" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/names" ) -func SecurityGroupRuleMigrateState( +func securityGroupRuleMigrateState( v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: @@ -45,15 +45,15 @@ func migrateSGRuleStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceS } log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) - newID := SecurityGroupRuleCreateID(is.Attributes["security_group_id"], is.Attributes[names.AttrType], perm) + newID := securityGroupRuleCreateID(is.Attributes["security_group_id"], is.Attributes[names.AttrType], perm) is.Attributes[names.AttrID] = newID is.ID = newID log.Printf("[DEBUG] Attributes after migration: %#v, new id: %s", is.Attributes, newID) return is, nil } -func migrateExpandIPPerm(attrs map[string]string) (*ec2.IpPermission, error) { - var perm ec2.IpPermission +func migrateExpandIPPerm(attrs map[string]string) (*awstypes.IpPermission, error) { + var perm awstypes.IpPermission tp, err := strconv.Atoi(attrs["to_port"]) if err != nil { return nil, fmt.Errorf("converting to_port in Security Group migration") @@ -64,8 +64,8 @@ func migrateExpandIPPerm(attrs map[string]string) (*ec2.IpPermission, error) { return nil, fmt.Errorf("converting from_port in Security Group migration") } - perm.ToPort = aws.Int64(int64(tp)) - perm.FromPort = aws.Int64(int64(fp)) + perm.ToPort = aws.Int32(int32(tp)) + perm.FromPort = aws.Int32(int32(fp)) perm.IpProtocol = aws.String(attrs[names.AttrProtocol]) groups := make(map[string]bool) @@ -78,7 +78,7 @@ func migrateExpandIPPerm(attrs map[string]string) (*ec2.IpPermission, error) { } if len(groups) > 0 { - perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, len(groups)) + perm.UserIdGroupPairs = make([]awstypes.UserIdGroupPair, len(groups)) // build string list of group name/ids var gl []string for k := range groups { @@ -86,7 +86,7 @@ func migrateExpandIPPerm(attrs map[string]string) (*ec2.IpPermission, error) { } for i, name := range gl { - perm.UserIdGroupPairs[i] = &ec2.UserIdGroupPair{ + perm.UserIdGroupPairs[i] = awstypes.UserIdGroupPair{ GroupId: aws.String(name), } } @@ -99,9 +99,9 @@ func migrateExpandIPPerm(attrs map[string]string) (*ec2.IpPermission, error) { } } if len(cb) > 0 { - perm.IpRanges = make([]*ec2.IpRange, len(cb)) + perm.IpRanges = make([]awstypes.IpRange, len(cb)) for i, v := range cb { - perm.IpRanges[i] = &ec2.IpRange{CidrIp: aws.String(v)} + perm.IpRanges[i] = awstypes.IpRange{CidrIp: aws.String(v)} } } diff --git a/internal/service/ec2/vpc_security_group_rule_test.go b/internal/service/ec2/vpc_security_group_rule_test.go index 006a14f6c44..8ec6d5ef343 100644 --- a/internal/service/ec2/vpc_security_group_rule_test.go +++ b/internal/service/ec2/vpc_security_group_rule_test.go @@ -10,8 +10,8 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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,42 +23,42 @@ import ( func TestSecurityGroupRuleCreateID(t *testing.T) { t.Parallel() - simple := &ec2.IpPermission{ + simple := awstypes.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpRanges: []*ec2.IpRange{ + FromPort: aws.Int32(80), + ToPort: aws.Int32(8000), + IpRanges: []awstypes.IpRange{ { CidrIp: aws.String("10.0.0.0/8"), }, }, } - egress := &ec2.IpPermission{ + egress := awstypes.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpRanges: []*ec2.IpRange{ + FromPort: aws.Int32(80), + ToPort: aws.Int32(8000), + IpRanges: []awstypes.IpRange{ { CidrIp: aws.String("10.0.0.0/8"), }, }, } - egress_all := &ec2.IpPermission{ + egress_all := awstypes.IpPermission{ IpProtocol: aws.String("-1"), - IpRanges: []*ec2.IpRange{ + IpRanges: []awstypes.IpRange{ { CidrIp: aws.String("10.0.0.0/8"), }, }, } - vpc_security_group_source := &ec2.IpPermission{ + vpc_security_group_source := awstypes.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(80), + ToPort: aws.Int32(8000), + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { UserId: aws.String("987654321"), GroupId: aws.String("sg-12345678"), @@ -74,11 +74,11 @@ func TestSecurityGroupRuleCreateID(t *testing.T) { }, } - security_group_source := &ec2.IpPermission{ + security_group_source := awstypes.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(80), + ToPort: aws.Int32(8000), + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { UserId: aws.String("987654321"), GroupName: aws.String("my-security-group"), @@ -96,7 +96,7 @@ func TestSecurityGroupRuleCreateID(t *testing.T) { // hardcoded hashes, to detect future change cases := []struct { - Input *ec2.IpPermission + Input awstypes.IpPermission Type string Output string }{ @@ -108,16 +108,16 @@ func TestSecurityGroupRuleCreateID(t *testing.T) { } for _, tc := range cases { - actual := tfec2.SecurityGroupRuleCreateID("sg-12345", tc.Type, tc.Input) + actual := tfec2.SecurityGroupRuleCreateID("sg-12345", tc.Type, &tc.Input) if actual != tc.Output { - t.Errorf("input: %s - %s\noutput: %s", tc.Type, tc.Input, actual) + t.Errorf("input: %s - %#v\noutput: %s", tc.Type, tc.Input, actual) } } } func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -159,7 +159,7 @@ func TestAccVPCSecurityGroupRule_Ingress_vpc(t *testing.T) { func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -194,7 +194,7 @@ func TestAccVPCSecurityGroupRule_IngressSourceWithAccount_id(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -236,7 +236,7 @@ func TestAccVPCSecurityGroupRule_Ingress_protocol(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -278,7 +278,7 @@ func TestAccVPCSecurityGroupRule_Ingress_icmpv6(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -320,7 +320,7 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv6(t *testing.T) { func TestAccVPCSecurityGroupRule_egress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -362,7 +362,7 @@ func TestAccVPCSecurityGroupRule_egress(t *testing.T) { func TestAccVPCSecurityGroupRule_selfReference(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -413,7 +413,7 @@ func TestAccVPCSecurityGroupRule_expectInvalidTypeError(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccVPCSecurityGroupRuleConfig_expectInvalidType(rName), - ExpectError: regexache.MustCompile(`expected type to be one of \[egress ingress\]`), + ExpectError: regexache.MustCompile(`expected type to be one of \[\"egress\" \"ingress\"\]`), }, }, }) @@ -534,7 +534,7 @@ func TestAccVPCSecurityGroupRule_PartialMatching_source(t *testing.T) { func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -574,7 +574,7 @@ func TestAccVPCSecurityGroupRule_issue5310(t *testing.T) { func TestAccVPCSecurityGroupRule_race(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) sgResourceName := "aws_security_group.test" n := 50 @@ -598,7 +598,7 @@ func TestAccVPCSecurityGroupRule_race(t *testing.T) { func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -639,7 +639,7 @@ func TestAccVPCSecurityGroupRule_selfSource(t *testing.T) { func TestAccVPCSecurityGroupRule_prefixListEgress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -701,7 +701,7 @@ func TestAccVPCSecurityGroupRule_prefixListEmptyString(t *testing.T) { func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -743,7 +743,7 @@ func TestAccVPCSecurityGroupRule_ingressDescription(t *testing.T) { func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -785,7 +785,7 @@ func TestAccVPCSecurityGroupRule_egressDescription(t *testing.T) { func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -844,7 +844,7 @@ func TestAccVPCSecurityGroupRule_IngressDescription_updates(t *testing.T) { func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -903,7 +903,7 @@ func TestAccVPCSecurityGroupRule_EgressDescription_updates(t *testing.T) { func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -962,7 +962,7 @@ func TestAccVPCSecurityGroupRule_Description_allPorts(t *testing.T) { func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -1022,7 +1022,7 @@ func TestAccVPCSecurityGroupRule_DescriptionAllPorts_nonZeroPorts(t *testing.T) // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/6416 func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource1Name := "aws_security_group_rule.test1" resource2Name := "aws_security_group_rule.test2" @@ -1082,7 +1082,7 @@ func TestAccVPCSecurityGroupRule_MultipleRuleSearching_allProtocolCrash(t *testi func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { ctx := acctest.Context(t) - var group1, group2 ec2.SecurityGroup + var group1, group2 awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resource1Name := "aws_security_group_rule.test1" resource2Name := "aws_security_group_rule.test2" @@ -1249,7 +1249,7 @@ func TestAccVPCSecurityGroupRule_multiDescription(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_multipleIPv6(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -1292,7 +1292,7 @@ func TestAccVPCSecurityGroupRule_Ingress_multipleIPv6(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -1333,7 +1333,7 @@ func TestAccVPCSecurityGroupRule_Ingress_multiplePrefixLists(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_peeredVPC(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -1374,7 +1374,7 @@ func TestAccVPCSecurityGroupRule_Ingress_peeredVPC(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -1417,7 +1417,7 @@ func TestAccVPCSecurityGroupRule_Ingress_ipv4AndIPv6(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sgResourceName := "aws_security_group.test" @@ -1458,7 +1458,7 @@ func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSelf(t *testing.T) { func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" sg1ResourceName := "aws_security_group.test.0" @@ -1500,7 +1500,7 @@ func TestAccVPCSecurityGroupRule_Ingress_prefixListAndSource(t *testing.T) { func TestAccVPCSecurityGroupRule_protocolChange(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group_rule.test" resourceName2 := "aws_security_group_rule.test2" diff --git a/internal/service/ec2/vpc_security_group_rules_data_source.go b/internal/service/ec2/vpc_security_group_rules_data_source.go index 4cc436a877c..6e4723a7c0a 100644 --- a/internal/service/ec2/vpc_security_group_rules_data_source.go +++ b/internal/service/ec2/vpc_security_group_rules_data_source.go @@ -6,8 +6,9 @@ package ec2 import ( "context" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" @@ -56,7 +57,7 @@ func (d *securityGroupRulesDataSource) Read(ctx context.Context, request datasou return } - conn := d.Meta().EC2Conn(ctx) + conn := d.Meta().EC2Client(ctx) input := &ec2.DescribeSecurityGroupRulesInput{ Filters: append(newCustomFilterListFramework(ctx, data.Filters), newTagFilterList(Tags(tftags.New(ctx, data.Tags)))...), @@ -67,7 +68,7 @@ func (d *securityGroupRulesDataSource) Read(ctx context.Context, request datasou input.Filters = nil } - output, err := FindSecurityGroupRules(ctx, conn, input) + output, err := findSecurityGroupRules(ctx, conn, input) if err != nil { response.Diagnostics.AddError("reading Security Group Rules", err.Error()) @@ -76,8 +77,8 @@ func (d *securityGroupRulesDataSource) Read(ctx context.Context, request datasou } data.ID = types.StringValue(d.Meta().Region) - data.IDs = flex.FlattenFrameworkStringValueList(ctx, tfslices.ApplyToAll(output, func(v *ec2.SecurityGroupRule) string { - return aws.StringValue(v.SecurityGroupRuleId) + data.IDs = flex.FlattenFrameworkStringValueList(ctx, tfslices.ApplyToAll(output, func(v awstypes.SecurityGroupRule) string { + return aws.ToString(v.SecurityGroupRuleId) })) response.Diagnostics.Append(response.State.Set(ctx, &data)...) diff --git a/internal/service/ec2/vpc_security_group_rules_matching_test.go b/internal/service/ec2/vpc_security_group_rules_matching_test.go index 78758910b6c..f4e1387ba15 100644 --- a/internal/service/ec2/vpc_security_group_rules_matching_test.go +++ b/internal/service/ec2/vpc_security_group_rules_matching_test.go @@ -33,8 +33,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), @@ -61,8 +61,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), @@ -76,8 +76,8 @@ func TestRulesMixedMatching(t *testing.T) { names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, @@ -94,8 +94,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, @@ -120,8 +120,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, @@ -152,8 +152,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, @@ -177,16 +177,16 @@ func TestRulesMixedMatching(t *testing.T) { local: []interface{}{}, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, }, saves: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "10.0.0.0/16"}, }, @@ -203,8 +203,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", }, }, @@ -228,19 +228,19 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"10.0.0.0/16"}, }, }, - // Because this is the remote rule being saved, we need to check for int64 + // Because this is the remote rule being saved, we need to check for int32 // encoding. We could convert this code, but ultimately Terraform doesn't // care it's for the reflect.DeepEqual in this test saves: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"10.0.0.0/16"}, }, @@ -258,16 +258,16 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, }, saves: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, @@ -298,8 +298,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, @@ -332,8 +332,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16", "10.8.0.0/16", "206.8.0.0/16"}, }, @@ -346,8 +346,8 @@ func TestRulesMixedMatching(t *testing.T) { "cidr_blocks": []string{"172.8.0.0/16", "10.8.0.0/16"}, }, { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"192.168.0.0/16", "206.8.0.0/16"}, }, @@ -358,17 +358,17 @@ func TestRulesMixedMatching(t *testing.T) { local: []interface{}{}, remote: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876"}), }, }, saves: []map[string]interface{}{ { - // we're saving the remote, so it will be int64 encoded - "from_port": int64(22), - "to_port": int64(22), + // we're saving the remote, so it will be int32 encoded + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876"}), }, @@ -392,8 +392,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", names.AttrSecurityGroups: schema.NewSet( schema.HashString, @@ -442,16 +442,16 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", "self": true, }, }, saves: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", "self": true, }, @@ -469,16 +469,16 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", "self": true, }, }, saves: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", "self": true, }, @@ -495,16 +495,16 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", "self": true, }, }, saves: []map[string]interface{}{ { - "from_port": int64(22), - "to_port": int64(22), + "from_port": int32(22), + "to_port": int32(22), names.AttrProtocol: "tcp", "self": true, }, @@ -528,8 +528,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), @@ -537,14 +537,14 @@ func TestRulesMixedMatching(t *testing.T) { }, saves: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, }, { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), }, @@ -567,8 +567,8 @@ func TestRulesMixedMatching(t *testing.T) { }, remote: []map[string]interface{}{ { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, "self": true, @@ -583,8 +583,8 @@ func TestRulesMixedMatching(t *testing.T) { "self": true, }, { - "from_port": int64(80), - "to_port": int64(8000), + "from_port": int32(80), + "to_port": int32(8000), names.AttrProtocol: "tcp", "cidr_blocks": []string{"172.8.0.0/16", "192.168.0.0/16"}, names.AttrSecurityGroups: schema.NewSet(schema.HashString, []interface{}{"sg-9876", "sg-4444"}), diff --git a/internal/service/ec2/vpc_security_group_tags_gen_test.go b/internal/service/ec2/vpc_security_group_tags_gen_test.go index c343d366e04..8cdca7dd9da 100644 --- a/internal/service/ec2/vpc_security_group_tags_gen_test.go +++ b/internal/service/ec2/vpc_security_group_tags_gen_test.go @@ -5,7 +5,7 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-testing/config" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -19,7 +19,7 @@ import ( func TestAccVPCSecurityGroup_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -202,7 +202,7 @@ func TestAccVPCSecurityGroup_tags(t *testing.T) { func TestAccVPCSecurityGroup_tags_null(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -265,7 +265,7 @@ func TestAccVPCSecurityGroup_tags_null(t *testing.T) { func TestAccVPCSecurityGroup_tags_AddOnUpdate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -345,7 +345,7 @@ func TestAccVPCSecurityGroup_tags_AddOnUpdate(t *testing.T) { func TestAccVPCSecurityGroup_tags_EmptyTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -436,7 +436,7 @@ func TestAccVPCSecurityGroup_tags_EmptyTag_OnCreate(t *testing.T) { func TestAccVPCSecurityGroup_tags_EmptyTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -569,7 +569,7 @@ func TestAccVPCSecurityGroup_tags_EmptyTag_OnUpdate_Add(t *testing.T) { func TestAccVPCSecurityGroup_tags_EmptyTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -655,7 +655,7 @@ func TestAccVPCSecurityGroup_tags_EmptyTag_OnUpdate_Replace(t *testing.T) { func TestAccVPCSecurityGroup_tags_DefaultTags_providerOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -848,7 +848,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_providerOnly(t *testing.T) { func TestAccVPCSecurityGroup_tags_DefaultTags_nonOverlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1017,7 +1017,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_nonOverlapping(t *testing.T) { func TestAccVPCSecurityGroup_tags_DefaultTags_overlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1202,7 +1202,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_overlapping(t *testing.T) { func TestAccVPCSecurityGroup_tags_DefaultTags_updateToProviderOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1295,7 +1295,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_updateToProviderOnly(t *testing.T) func TestAccVPCSecurityGroup_tags_DefaultTags_updateToResourceOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1387,7 +1387,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_updateToResourceOnly(t *testing.T) func TestAccVPCSecurityGroup_tags_DefaultTags_emptyResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1455,7 +1455,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_emptyResourceTag(t *testing.T) { func TestAccVPCSecurityGroup_tags_DefaultTags_emptyProviderOnlyTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1515,7 +1515,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_emptyProviderOnlyTag(t *testing.T) func TestAccVPCSecurityGroup_tags_DefaultTags_nullOverlappingResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1580,7 +1580,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_nullOverlappingResourceTag(t *test func TestAccVPCSecurityGroup_tags_DefaultTags_nullNonOverlappingResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1645,7 +1645,7 @@ func TestAccVPCSecurityGroup_tags_DefaultTags_nullNonOverlappingResourceTag(t *t func TestAccVPCSecurityGroup_tags_ComputedTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1702,7 +1702,7 @@ func TestAccVPCSecurityGroup_tags_ComputedTag_OnCreate(t *testing.T) { func TestAccVPCSecurityGroup_tags_ComputedTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1795,7 +1795,7 @@ func TestAccVPCSecurityGroup_tags_ComputedTag_OnUpdate_Add(t *testing.T) { func TestAccVPCSecurityGroup_tags_ComputedTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.SecurityGroup + var v types.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) diff --git a/internal/service/ec2/vpc_security_group_test.go b/internal/service/ec2/vpc_security_group_test.go index 36ebc1e2c3f..613000d8d27 100644 --- a/internal/service/ec2/vpc_security_group_test.go +++ b/internal/service/ec2/vpc_security_group_test.go @@ -12,8 +12,9 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/id" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" @@ -379,13 +380,13 @@ func TestSecurityGroupExpandCollapseRules(t *testing.T) { func TestSecurityGroupIPPermGather(t *testing.T) { t.Parallel() - raw := []*ec2.IpPermission{ + raw := []awstypes.IpPermission{ { IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(1), - ToPort: aws.Int64(int64(-1)), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(1), + ToPort: aws.Int32(int32(-1)), + IpRanges: []awstypes.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { GroupId: aws.String("sg-11111"), Description: aws.String("desc"), @@ -394,9 +395,9 @@ func TestSecurityGroupIPPermGather(t *testing.T) { }, { IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(80), - ToPort: aws.Int64(80), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(80), + ToPort: aws.Int32(80), + UserIdGroupPairs: []awstypes.UserIdGroupPair{ // VPC { GroupId: aws.String("sg-22222"), @@ -405,9 +406,9 @@ func TestSecurityGroupIPPermGather(t *testing.T) { }, { IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(443), - ToPort: aws.Int64(443), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(443), + ToPort: aws.Int32(443), + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { UserId: aws.String("amazon-elb"), GroupId: aws.String("sg-d2c979d3"), @@ -417,15 +418,15 @@ func TestSecurityGroupIPPermGather(t *testing.T) { }, { IpProtocol: aws.String("-1"), - FromPort: aws.Int64(0), - ToPort: aws.Int64(0), - PrefixListIds: []*ec2.PrefixListId{ + FromPort: aws.Int32(0), + ToPort: aws.Int32(0), + PrefixListIds: []awstypes.PrefixListId{ { PrefixListId: aws.String("pl-12345678"), Description: aws.String("desc"), }, }, - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + UserIdGroupPairs: []awstypes.UserIdGroupPair{ // VPC { GroupId: aws.String("sg-22222"), @@ -515,7 +516,7 @@ func TestExpandIPPerms(t *testing.T) { "self": true, }, } - group := &ec2.SecurityGroup{ + group := &awstypes.SecurityGroup{ GroupId: aws.String("foo"), VpcId: aws.String("bar"), } @@ -524,18 +525,18 @@ func TestExpandIPPerms(t *testing.T) { t.Fatalf("error expanding perms: %v", err) } - expected := []ec2.IpPermission{ + expected := []awstypes.IpPermission{ { IpProtocol: aws.String("icmp"), - FromPort: aws.Int64(1), - ToPort: aws.Int64(int64(-1)), - IpRanges: []*ec2.IpRange{ + FromPort: aws.Int32(1), + ToPort: aws.Int32(int32(-1)), + IpRanges: []awstypes.IpRange{ { CidrIp: aws.String("0.0.0.0/0"), Description: aws.String("desc"), }, }, - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { UserId: aws.String("foo"), GroupId: aws.String("sg-22222"), @@ -549,9 +550,9 @@ func TestExpandIPPerms(t *testing.T) { }, { IpProtocol: aws.String("icmp"), - FromPort: aws.Int64(1), - ToPort: aws.Int64(int64(-1)), - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(1), + ToPort: aws.Int32(int32(-1)), + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { GroupId: aws.String("foo"), }, @@ -562,49 +563,49 @@ func TestExpandIPPerms(t *testing.T) { exp := expected[0] perm := perms[0] - if aws.Int64Value(exp.FromPort) != aws.Int64Value(perm.FromPort) { + if aws.ToInt32(exp.FromPort) != aws.ToInt32(perm.FromPort) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.Int64Value(perm.FromPort), - aws.Int64Value(exp.FromPort)) + aws.ToInt32(perm.FromPort), + aws.ToInt32(exp.FromPort)) } - if aws.StringValue(exp.IpRanges[0].CidrIp) != aws.StringValue(perm.IpRanges[0].CidrIp) { + if aws.ToString(exp.IpRanges[0].CidrIp) != aws.ToString(perm.IpRanges[0].CidrIp) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.IpRanges[0].CidrIp), - aws.StringValue(exp.IpRanges[0].CidrIp)) + aws.ToString(perm.IpRanges[0].CidrIp), + aws.ToString(exp.IpRanges[0].CidrIp)) } - if aws.StringValue(exp.UserIdGroupPairs[0].UserId) != aws.StringValue(perm.UserIdGroupPairs[0].UserId) { + if aws.ToString(exp.UserIdGroupPairs[0].UserId) != aws.ToString(perm.UserIdGroupPairs[0].UserId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.UserIdGroupPairs[0].UserId), - aws.StringValue(exp.UserIdGroupPairs[0].UserId)) + aws.ToString(perm.UserIdGroupPairs[0].UserId), + aws.ToString(exp.UserIdGroupPairs[0].UserId)) } - if aws.StringValue(exp.UserIdGroupPairs[0].GroupId) != aws.StringValue(perm.UserIdGroupPairs[0].GroupId) { + if aws.ToString(exp.UserIdGroupPairs[0].GroupId) != aws.ToString(perm.UserIdGroupPairs[0].GroupId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.UserIdGroupPairs[0].GroupId), - aws.StringValue(exp.UserIdGroupPairs[0].GroupId)) + aws.ToString(perm.UserIdGroupPairs[0].GroupId), + aws.ToString(exp.UserIdGroupPairs[0].GroupId)) } - if aws.StringValue(exp.UserIdGroupPairs[1].GroupId) != aws.StringValue(perm.UserIdGroupPairs[1].GroupId) { + if aws.ToString(exp.UserIdGroupPairs[1].GroupId) != aws.ToString(perm.UserIdGroupPairs[1].GroupId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.UserIdGroupPairs[1].GroupId), - aws.StringValue(exp.UserIdGroupPairs[1].GroupId)) + aws.ToString(perm.UserIdGroupPairs[1].GroupId), + aws.ToString(exp.UserIdGroupPairs[1].GroupId)) } exp = expected[1] perm = perms[1] - if aws.StringValue(exp.UserIdGroupPairs[0].GroupId) != aws.StringValue(perm.UserIdGroupPairs[0].GroupId) { + if aws.ToString(exp.UserIdGroupPairs[0].GroupId) != aws.ToString(perm.UserIdGroupPairs[0].GroupId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.UserIdGroupPairs[0].GroupId), - aws.StringValue(exp.UserIdGroupPairs[0].GroupId)) + aws.ToString(perm.UserIdGroupPairs[0].GroupId), + aws.ToString(exp.UserIdGroupPairs[0].GroupId)) } } @@ -625,7 +626,7 @@ func TestExpandIPPerms_NegOneProtocol(t *testing.T) { }), }, } - group := &ec2.SecurityGroup{ + group := &awstypes.SecurityGroup{ GroupId: aws.String("foo"), VpcId: aws.String("bar"), } @@ -635,13 +636,13 @@ func TestExpandIPPerms_NegOneProtocol(t *testing.T) { t.Fatalf("error expanding perms: %v", err) } - expected := []ec2.IpPermission{ + expected := []awstypes.IpPermission{ { IpProtocol: aws.String("-1"), - FromPort: aws.Int64(0), - ToPort: aws.Int64(0), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(0), + ToPort: aws.Int32(0), + IpRanges: []awstypes.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { UserId: aws.String("foo"), GroupId: aws.String("sg-22222"), @@ -656,25 +657,25 @@ func TestExpandIPPerms_NegOneProtocol(t *testing.T) { exp := expected[0] perm := perms[0] - if aws.Int64Value(exp.FromPort) != aws.Int64Value(perm.FromPort) { + if aws.ToInt32(exp.FromPort) != aws.ToInt32(perm.FromPort) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.Int64Value(perm.FromPort), - aws.Int64Value(exp.FromPort)) + aws.ToInt32(perm.FromPort), + aws.ToInt32(exp.FromPort)) } - if aws.StringValue(exp.IpRanges[0].CidrIp) != aws.StringValue(perm.IpRanges[0].CidrIp) { + if aws.ToString(exp.IpRanges[0].CidrIp) != aws.ToString(perm.IpRanges[0].CidrIp) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.IpRanges[0].CidrIp), - aws.StringValue(exp.IpRanges[0].CidrIp)) + aws.ToString(perm.IpRanges[0].CidrIp), + aws.ToString(exp.IpRanges[0].CidrIp)) } - if aws.StringValue(exp.UserIdGroupPairs[0].UserId) != aws.StringValue(perm.UserIdGroupPairs[0].UserId) { + if aws.ToString(exp.UserIdGroupPairs[0].UserId) != aws.ToString(perm.UserIdGroupPairs[0].UserId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.UserIdGroupPairs[0].UserId), - aws.StringValue(exp.UserIdGroupPairs[0].UserId)) + aws.ToString(perm.UserIdGroupPairs[0].UserId), + aws.ToString(exp.UserIdGroupPairs[0].UserId)) } // Now test the error case. This *should* error when either from_port @@ -691,7 +692,7 @@ func TestExpandIPPerms_NegOneProtocol(t *testing.T) { }), }, } - securityGroups := &ec2.SecurityGroup{ + securityGroups := &awstypes.SecurityGroup{ GroupId: aws.String("foo"), VpcId: aws.String("bar"), } @@ -719,7 +720,7 @@ func TestExpandIPPerms_AllProtocol(t *testing.T) { }), }, } - group := &ec2.SecurityGroup{ + group := &awstypes.SecurityGroup{ GroupId: aws.String("foo"), VpcId: aws.String("bar"), } @@ -729,13 +730,13 @@ func TestExpandIPPerms_AllProtocol(t *testing.T) { t.Fatalf("error expanding perms: %v", err) } - expected := []ec2.IpPermission{ + expected := []awstypes.IpPermission{ { IpProtocol: aws.String("-1"), - FromPort: aws.Int64(0), - ToPort: aws.Int64(0), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, - UserIdGroupPairs: []*ec2.UserIdGroupPair{ + FromPort: aws.Int32(0), + ToPort: aws.Int32(0), + IpRanges: []awstypes.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, + UserIdGroupPairs: []awstypes.UserIdGroupPair{ { UserId: aws.String("foo"), GroupId: aws.String("sg-22222"), @@ -750,25 +751,25 @@ func TestExpandIPPerms_AllProtocol(t *testing.T) { exp := expected[0] perm := perms[0] - if aws.Int64Value(exp.FromPort) != aws.Int64Value(perm.FromPort) { + if aws.ToInt32(exp.FromPort) != aws.ToInt32(perm.FromPort) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.Int64Value(perm.FromPort), - aws.Int64Value(exp.FromPort)) + aws.ToInt32(perm.FromPort), + aws.ToInt32(exp.FromPort)) } - if aws.StringValue(exp.IpRanges[0].CidrIp) != aws.StringValue(perm.IpRanges[0].CidrIp) { + if aws.ToString(exp.IpRanges[0].CidrIp) != aws.ToString(perm.IpRanges[0].CidrIp) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.IpRanges[0].CidrIp), - aws.StringValue(exp.IpRanges[0].CidrIp)) + aws.ToString(perm.IpRanges[0].CidrIp), + aws.ToString(exp.IpRanges[0].CidrIp)) } - if aws.StringValue(exp.UserIdGroupPairs[0].UserId) != aws.StringValue(perm.UserIdGroupPairs[0].UserId) { + if aws.ToString(exp.UserIdGroupPairs[0].UserId) != aws.ToString(perm.UserIdGroupPairs[0].UserId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - aws.StringValue(perm.UserIdGroupPairs[0].UserId), - aws.StringValue(exp.UserIdGroupPairs[0].UserId)) + aws.ToString(perm.UserIdGroupPairs[0].UserId), + aws.ToString(exp.UserIdGroupPairs[0].UserId)) } // Now test the error case. This *should* error when either from_port @@ -785,7 +786,7 @@ func TestExpandIPPerms_AllProtocol(t *testing.T) { }), }, } - securityGroups := &ec2.SecurityGroup{ + securityGroups := &awstypes.SecurityGroup{ GroupId: aws.String("foo"), VpcId: aws.String("bar"), } @@ -801,13 +802,13 @@ func TestFlattenSecurityGroups(t *testing.T) { cases := []struct { ownerId *string - pairs []*ec2.UserIdGroupPair + pairs []awstypes.UserIdGroupPair expected []*tfec2.GroupIdentifier }{ // simple, no user id included (we ignore it mostly) { ownerId: aws.String("user1234"), - pairs: []*ec2.UserIdGroupPair{ + pairs: []awstypes.UserIdGroupPair{ { GroupId: aws.String("sg-12345"), }, @@ -820,7 +821,7 @@ func TestFlattenSecurityGroups(t *testing.T) { }, { ownerId: aws.String("user1234"), - pairs: []*ec2.UserIdGroupPair{ + pairs: []awstypes.UserIdGroupPair{ { GroupId: aws.String("sg-12345"), UserId: aws.String("user1234"), @@ -834,7 +835,7 @@ func TestFlattenSecurityGroups(t *testing.T) { }, { ownerId: aws.String("user1234"), - pairs: []*ec2.UserIdGroupPair{ + pairs: []awstypes.UserIdGroupPair{ { GroupId: aws.String("sg-12345"), UserId: aws.String("user4321"), @@ -850,7 +851,7 @@ func TestFlattenSecurityGroups(t *testing.T) { // include description { ownerId: aws.String("user1234"), - pairs: []*ec2.UserIdGroupPair{ + pairs: []awstypes.UserIdGroupPair{ { GroupId: aws.String("sg-12345"), Description: aws.String("desc"), @@ -875,7 +876,7 @@ func TestFlattenSecurityGroups(t *testing.T) { func TestAccVPCSecurityGroup_basic(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -913,7 +914,7 @@ func TestAccVPCSecurityGroup_basic(t *testing.T) { func TestAccVPCSecurityGroup_disappears(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -937,7 +938,7 @@ func TestAccVPCSecurityGroup_disappears(t *testing.T) { func TestAccVPCSecurityGroup_noVPC(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -974,7 +975,7 @@ func TestAccVPCSecurityGroup_noVPC(t *testing.T) { func TestAccVPCSecurityGroup_nameGenerated(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1005,7 +1006,7 @@ func TestAccVPCSecurityGroup_nameGenerated(t *testing.T) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 func TestAccVPCSecurityGroup_nameTerraformPrefix(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix("terraform-test") @@ -1035,7 +1036,7 @@ func TestAccVPCSecurityGroup_nameTerraformPrefix(t *testing.T) { func TestAccVPCSecurityGroup_namePrefix(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1066,7 +1067,7 @@ func TestAccVPCSecurityGroup_namePrefix(t *testing.T) { // Reference: https://github.com/hashicorp/terraform-provider-aws/issues/17017 func TestAccVPCSecurityGroup_namePrefixTerraform(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1096,7 +1097,7 @@ func TestAccVPCSecurityGroup_namePrefixTerraform(t *testing.T) { func TestAccVPCSecurityGroup_allowAll(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1124,7 +1125,7 @@ func TestAccVPCSecurityGroup_allowAll(t *testing.T) { func TestAccVPCSecurityGroup_sourceSecurityGroup(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1152,7 +1153,7 @@ func TestAccVPCSecurityGroup_sourceSecurityGroup(t *testing.T) { func TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1180,7 +1181,7 @@ func TestAccVPCSecurityGroup_ipRangeAndSecurityGroupWithSameRules(t *testing.T) func TestAccVPCSecurityGroup_ipRangesWithSameRules(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1208,7 +1209,7 @@ func TestAccVPCSecurityGroup_ipRangesWithSameRules(t *testing.T) { func TestAccVPCSecurityGroup_egressMode(t *testing.T) { ctx := acctest.Context(t) - var securityGroup1, securityGroup2, securityGroup3 ec2.SecurityGroup + var securityGroup1, securityGroup2, securityGroup3 awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1251,7 +1252,7 @@ func TestAccVPCSecurityGroup_egressMode(t *testing.T) { func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { ctx := acctest.Context(t) - var securityGroup1, securityGroup2, securityGroup3 ec2.SecurityGroup + var securityGroup1, securityGroup2, securityGroup3 awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1294,7 +1295,7 @@ func TestAccVPCSecurityGroup_ingressMode(t *testing.T) { func TestAccVPCSecurityGroup_ruleGathering(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1400,8 +1401,8 @@ func TestAccVPCSecurityGroup_ruleGathering(t *testing.T) { // cyclic rules that were added. func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { ctx := acctest.Context(t) - var primary ec2.SecurityGroup - var secondary ec2.SecurityGroup + var primary awstypes.SecurityGroup + var secondary awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.primary" resourceName2 := "aws_security_group.secondary" @@ -1429,10 +1430,12 @@ func TestAccVPCSecurityGroup_forceRevokeRulesTrue(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + // Because of the cyclic dependency created in testAddCycle, we add data outside of terraform to this resource. + // During an import this cannot be accounted for and should be ignored. + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete", "egress"}, }, // Verify the DependencyViolation error by using a configuration with the // groups removed. Terraform tries to destroy them but cannot. Expect a @@ -1485,8 +1488,8 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var primary ec2.SecurityGroup - var secondary ec2.SecurityGroup + var primary awstypes.SecurityGroup + var secondary awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.primary" resourceName2 := "aws_security_group.secondary" @@ -1516,10 +1519,12 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + // Because of the cyclic dependency created in testAddCycle, we add data outside of terraform to this resource. + // During an import this cannot be accounted for and should be ignored. + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete", "egress"}, }, // Verify the DependencyViolation error by using a configuration with the // groups removed, and the Groups not configured to revoke their ruls. @@ -1549,7 +1554,7 @@ func TestAccVPCSecurityGroup_forceRevokeRulesFalse(t *testing.T) { func TestAccVPCSecurityGroup_change(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1619,7 +1624,7 @@ func TestAccVPCSecurityGroup_change(t *testing.T) { func TestAccVPCSecurityGroup_ipv6(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1672,14 +1677,14 @@ func TestAccVPCSecurityGroup_ipv6(t *testing.T) { func TestAccVPCSecurityGroup_self(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" checkSelf := func(s *terraform.State) (err error) { if len(group.IpPermissions) > 0 && len(group.IpPermissions[0].UserIdGroupPairs) > 0 && - aws.StringValue(group.IpPermissions[0].UserIdGroupPairs[0].GroupId) == aws.StringValue(group.GroupId) { + aws.ToString(group.IpPermissions[0].UserIdGroupPairs[0].GroupId) == aws.ToString(group.GroupId) { return nil } @@ -1718,7 +1723,7 @@ func TestAccVPCSecurityGroup_self(t *testing.T) { func TestAccVPCSecurityGroup_vpc(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1763,7 +1768,7 @@ func TestAccVPCSecurityGroup_vpc(t *testing.T) { func TestAccVPCSecurityGroup_vpcNegOneIngress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1800,7 +1805,7 @@ func TestAccVPCSecurityGroup_vpcNegOneIngress(t *testing.T) { func TestAccVPCSecurityGroup_vpcProtoNumIngress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1837,7 +1842,7 @@ func TestAccVPCSecurityGroup_vpcProtoNumIngress(t *testing.T) { func TestAccVPCSecurityGroup_multiIngress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1865,7 +1870,7 @@ func TestAccVPCSecurityGroup_multiIngress(t *testing.T) { func TestAccVPCSecurityGroup_vpcAllEgress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -1902,7 +1907,7 @@ func TestAccVPCSecurityGroup_vpcAllEgress(t *testing.T) { func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2016,7 +2021,7 @@ func TestAccVPCSecurityGroup_ruleDescription(t *testing.T) { func TestAccVPCSecurityGroup_defaultEgressVPC(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2047,7 +2052,7 @@ func TestAccVPCSecurityGroup_defaultEgressVPC(t *testing.T) { // Testing drift detection with groups containing the same port and types func TestAccVPCSecurityGroup_driftComplex(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2154,7 +2159,7 @@ func TestAccVPCSecurityGroup_invalidCIDRBlock(t *testing.T) { func TestAccVPCSecurityGroup_cidrAndGroups(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2182,7 +2187,7 @@ func TestAccVPCSecurityGroup_cidrAndGroups(t *testing.T) { func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test1" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2235,7 +2240,7 @@ func TestAccVPCSecurityGroup_ingressWithCIDRAndSGsVPC(t *testing.T) { func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2264,7 +2269,7 @@ func TestAccVPCSecurityGroup_egressWithPrefixList(t *testing.T) { func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2293,7 +2298,7 @@ func TestAccVPCSecurityGroup_ingressWithPrefixList(t *testing.T) { func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2347,7 +2352,7 @@ func TestAccVPCSecurityGroup_ipv4AndIPv6Egress(t *testing.T) { func TestAccVPCSecurityGroup_failWithDiffMismatch(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test1" @@ -2400,7 +2405,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededAppend(t *testing.T) { testAccSecurityGroup_ruleLimit(t) } - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -2427,7 +2432,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededAppend(t *testing.T) { { PreConfig: func() { // should have the original rules still - err := testSecurityGroupRuleCount(ctx, aws.StringValue(group.GroupId), 0, ruleLimit) + err := testSecurityGroupRuleCount(ctx, aws.ToString(group.GroupId), 0, ruleLimit) if err != nil { t.Fatalf("PreConfig check failed: %s", err) } @@ -2450,7 +2455,7 @@ func TestAccVPCSecurityGroup_RuleLimit_cidrBlockExceededAppend(t *testing.T) { testAccSecurityGroup_ruleLimit(t) } - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -2476,14 +2481,14 @@ func TestAccVPCSecurityGroup_RuleLimit_cidrBlockExceededAppend(t *testing.T) { { PreConfig: func() { // should have the original cidr blocks still in 1 rule - err := testSecurityGroupRuleCount(ctx, aws.StringValue(group.GroupId), 0, 1) + err := testSecurityGroupRuleCount(ctx, aws.ToString(group.GroupId), 0, 1) if err != nil { t.Fatalf("PreConfig check failed: %s", err) } - id := aws.StringValue(group.GroupId) + id := aws.ToString(group.GroupId) - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) match, err := tfec2.FindSecurityGroupByID(ctx, conn, id) if tfresource.NotFound(err) { @@ -2514,7 +2519,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededPrepend(t *testing.T) { testAccSecurityGroup_ruleLimit(t) } - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -2540,7 +2545,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededPrepend(t *testing.T) { { PreConfig: func() { // should have the original rules still (limit - 1 because of the shift) - err := testSecurityGroupRuleCount(ctx, aws.StringValue(group.GroupId), 0, ruleLimit-1) + err := testSecurityGroupRuleCount(ctx, aws.ToString(group.GroupId), 0, ruleLimit-1) if err != nil { t.Fatalf("PreConfig check failed: %s", err) } @@ -2562,7 +2567,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededAllNew(t *testing.T) { testAccSecurityGroup_ruleLimit(t) } - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -2588,7 +2593,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededAllNew(t *testing.T) { { // all the rules should have been revoked and the add failed PreConfig: func() { - err := testSecurityGroupRuleCount(ctx, aws.StringValue(group.GroupId), 0, 0) + err := testSecurityGroupRuleCount(ctx, aws.ToString(group.GroupId), 0, 0) if err != nil { t.Fatalf("PreConfig check failed: %s", err) } @@ -2606,7 +2611,7 @@ func TestAccVPCSecurityGroup_RuleLimit_exceededAllNew(t *testing.T) { func TestAccVPCSecurityGroup_rulesDropOnError(t *testing.T) { ctx := acctest.Context(t) - var group ec2.SecurityGroup + var group awstypes.SecurityGroup rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_security_group.test" @@ -2648,7 +2653,7 @@ func TestAccVPCSecurityGroup_emrDependencyViolation(t *testing.T) { t.Skip("skipping long-running test in short mode") } - var group ec2.SecurityGroup + var group awstypes.SecurityGroup resourceName := "aws_security_group.allow_access" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -2680,22 +2685,22 @@ func TestAccVPCSecurityGroup_emrDependencyViolation(t *testing.T) { // UserIdGroupPair for the groupid given. Used in // TestAccAWSSecurityGroup_forceRevokeRules_should_fail to create a cyclic rule // between 2 security groups -func cycleIPPermForGroup(groupId string) *ec2.IpPermission { - var perm ec2.IpPermission - perm.FromPort = aws.Int64(0) - perm.ToPort = aws.Int64(0) +func cycleIPPermForGroup(groupId string) awstypes.IpPermission { + var perm awstypes.IpPermission + perm.FromPort = aws.Int32(0) + perm.ToPort = aws.Int32(0) perm.IpProtocol = aws.String("icmp") - perm.UserIdGroupPairs = make([]*ec2.UserIdGroupPair, 1) - perm.UserIdGroupPairs[0] = &ec2.UserIdGroupPair{ + perm.UserIdGroupPairs = make([]awstypes.UserIdGroupPair, 1) + perm.UserIdGroupPairs[0] = awstypes.UserIdGroupPair{ GroupId: aws.String(groupId), } - return &perm + return perm } // testAddRuleCycle returns a TestCheckFunc to use at the end of a test, such // that a Security Group Rule cyclic dependency will be created between the two // Security Groups. A companion function, testRemoveRuleCycle, will undo this. -func testAddRuleCycle(ctx context.Context, primary, secondary *ec2.SecurityGroup) resource.TestCheckFunc { +func testAddRuleCycle(ctx context.Context, primary, secondary *awstypes.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { if primary.GroupId == nil { return fmt.Errorf("Primary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") @@ -2704,30 +2709,30 @@ func testAddRuleCycle(ctx context.Context, primary, secondary *ec2.SecurityGroup return fmt.Errorf("Secondary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) // cycle from primary to secondary - perm1 := cycleIPPermForGroup(aws.StringValue(secondary.GroupId)) + perm1 := cycleIPPermForGroup(aws.ToString(secondary.GroupId)) // cycle from secondary to primary - perm2 := cycleIPPermForGroup(aws.StringValue(primary.GroupId)) + perm2 := cycleIPPermForGroup(aws.ToString(primary.GroupId)) req1 := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: primary.GroupId, - IpPermissions: []*ec2.IpPermission{perm1}, + IpPermissions: []awstypes.IpPermission{perm1}, } req2 := &ec2.AuthorizeSecurityGroupEgressInput{ GroupId: secondary.GroupId, - IpPermissions: []*ec2.IpPermission{perm2}, + IpPermissions: []awstypes.IpPermission{perm2}, } var err error - _, err = conn.AuthorizeSecurityGroupEgressWithContext(ctx, req1) + _, err = conn.AuthorizeSecurityGroupEgress(ctx, req1) if err != nil { - return fmt.Errorf("Error authorizing primary security group %s rules: %w", aws.StringValue(primary.GroupId), err) + return fmt.Errorf("Error authorizing primary security group %s rules: %w", aws.ToString(primary.GroupId), err) } - _, err = conn.AuthorizeSecurityGroupEgressWithContext(ctx, req2) + _, err = conn.AuthorizeSecurityGroupEgress(ctx, req2) if err != nil { - return fmt.Errorf("Error authorizing secondary security group %s rules: %w", aws.StringValue(secondary.GroupId), err) + return fmt.Errorf("Error authorizing secondary security group %s rules: %w", aws.ToString(secondary.GroupId), err) } return nil } @@ -2735,7 +2740,7 @@ func testAddRuleCycle(ctx context.Context, primary, secondary *ec2.SecurityGroup // testRemoveRuleCycle removes the cyclic dependency between two security groups // that was added in testAddRuleCycle -func testRemoveRuleCycle(ctx context.Context, primary, secondary *ec2.SecurityGroup) resource.TestCheckFunc { +func testRemoveRuleCycle(ctx context.Context, primary, secondary *awstypes.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { if primary.GroupId == nil { return fmt.Errorf("Primary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") @@ -2744,28 +2749,28 @@ func testRemoveRuleCycle(ctx context.Context, primary, secondary *ec2.SecurityGr return fmt.Errorf("Secondary SG not set for TestAccAWSSecurityGroup_forceRevokeRules_should_fail") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) - for _, sg := range []*ec2.SecurityGroup{primary, secondary} { + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) + for _, sg := range []*awstypes.SecurityGroup{primary, secondary} { var err error - if sg.IpPermissions != nil { + if sg.IpPermissions != nil && len(sg.IpPermissions) > 0 { req := &ec2.RevokeSecurityGroupIngressInput{ GroupId: sg.GroupId, IpPermissions: sg.IpPermissions, } - if _, err = conn.RevokeSecurityGroupIngressWithContext(ctx, req); err != nil { - return fmt.Errorf("Error revoking default ingress rule for Security Group in testRemoveCycle (%s): %w", aws.StringValue(primary.GroupId), err) + if _, err = conn.RevokeSecurityGroupIngress(ctx, req); err != nil { + return fmt.Errorf("Error revoking default ingress rule for Security Group in testRemoveCycle (%s): %w", aws.ToString(primary.GroupId), err) } } - if sg.IpPermissionsEgress != nil { + if sg.IpPermissionsEgress != nil && len(sg.IpPermissionsEgress) > 0 { req := &ec2.RevokeSecurityGroupEgressInput{ GroupId: sg.GroupId, IpPermissions: sg.IpPermissionsEgress, } - if _, err = conn.RevokeSecurityGroupEgressWithContext(ctx, req); err != nil { - return fmt.Errorf("Error revoking default egress rule for Security Group in testRemoveCycle (%s): %w", aws.StringValue(sg.GroupId), err) + if _, err = conn.RevokeSecurityGroupEgress(ctx, req); err != nil { + return fmt.Errorf("Error revoking default egress rule for Security Group in testRemoveCycle (%s): %w", aws.ToString(sg.GroupId), err) } } } @@ -2775,7 +2780,7 @@ func testRemoveRuleCycle(ctx context.Context, primary, secondary *ec2.SecurityGr func testAccCheckSecurityGroupDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_security_group" { @@ -2799,7 +2804,7 @@ func testAccCheckSecurityGroupDestroy(ctx context.Context) resource.TestCheckFun } } -func testAccCheckSecurityGroupExists(ctx context.Context, n string, v *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckSecurityGroupExists(ctx context.Context, n string, v *awstypes.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -2810,7 +2815,7 @@ func testAccCheckSecurityGroupExists(ctx context.Context, n string, v *ec2.Secur return fmt.Errorf("No VPC Security Group ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindSecurityGroupByID(ctx, conn, rs.Primary.ID) @@ -2846,15 +2851,15 @@ func testAccCheckSecurityGroupRuleLimit(n string, v *int) resource.TestCheckFunc } } -func testAccCheckSecurityGroupRuleCount(ctx context.Context, group *ec2.SecurityGroup, expectedIngressCount, expectedEgressCount int) resource.TestCheckFunc { +func testAccCheckSecurityGroupRuleCount(ctx context.Context, group *awstypes.SecurityGroup, expectedIngressCount, expectedEgressCount int) resource.TestCheckFunc { return func(s *terraform.State) error { - id := aws.StringValue(group.GroupId) + id := aws.ToString(group.GroupId) return testSecurityGroupRuleCount(ctx, id, expectedIngressCount, expectedEgressCount) } } func testSecurityGroupRuleCount(ctx context.Context, id string, expectedIngressCount, expectedEgressCount int) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) group, err := tfec2.FindSecurityGroupByID(ctx, conn, id) if tfresource.NotFound(err) { diff --git a/internal/service/ec2/vpc_security_groups_data_source.go b/internal/service/ec2/vpc_security_groups_data_source.go index 1cc6f477ece..73c71346b8f 100644 --- a/internal/service/ec2/vpc_security_groups_data_source.go +++ b/internal/service/ec2/vpc_security_groups_data_source.go @@ -8,9 +8,9 @@ import ( "fmt" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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" @@ -19,8 +19,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_security_groups") -func DataSourceSecurityGroups() *schema.Resource { +// @SDKDataSource("aws_security_groups", name="Security Groups") +func dataSourceSecurityGroups() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceSecurityGroupsRead, @@ -53,7 +53,7 @@ func DataSourceSecurityGroups() *schema.Resource { func dataSourceSecurityGroupsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSecurityGroupsInput{} @@ -69,7 +69,7 @@ func dataSourceSecurityGroupsRead(ctx context.Context, d *schema.ResourceData, m input.Filters = nil } - output, err := FindSecurityGroups(ctx, conn, input) + output, err := findSecurityGroups(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Security Groups: %s", err) @@ -80,14 +80,14 @@ func dataSourceSecurityGroupsRead(ctx context.Context, d *schema.ResourceData, m for _, v := range output { arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: ec2.ServiceName, + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, - AccountID: aws.StringValue(v.OwnerId), - Resource: fmt.Sprintf("security-group/%s", aws.StringValue(v.GroupId)), + AccountID: aws.ToString(v.OwnerId), + Resource: fmt.Sprintf("security-group/%s", aws.ToString(v.GroupId)), }.String() arns = append(arns, arn) - securityGroupIDs = append(securityGroupIDs, aws.StringValue(v.GroupId)) - vpcIDs = append(vpcIDs, aws.StringValue(v.VpcId)) + securityGroupIDs = append(securityGroupIDs, aws.ToString(v.GroupId)) + vpcIDs = append(vpcIDs, aws.ToString(v.VpcId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_subnet.go b/internal/service/ec2/vpc_subnet.go index afcf66b7252..3ad500cf72a 100644 --- a/internal/service/ec2/vpc_subnet.go +++ b/internal/service/ec2/vpc_subnet.go @@ -9,14 +9,16 @@ import ( "log" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-log/tflog" "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/logging" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" @@ -27,8 +29,8 @@ import ( // @SDKResource("aws_subnet", name="Subnet") // @Tags(identifierAttribute="id") -// @Testing(existsType="github.com/aws/aws-sdk-go/service/ec2;ec2.Subnet") -func ResourceSubnet() *schema.Resource { +// @Testing(existsType="github.com/aws/aws-sdk-go-v2/service/ec2/types;types.Subnet") +func resourceSubnet() *schema.Resource { //lintignore:R011 return &schema.Resource{ CreateWithoutTimeout: resourceSubnetCreate, @@ -47,7 +49,7 @@ func ResourceSubnet() *schema.Resource { }, SchemaVersion: 1, - MigrateState: SubnetMigrateState, + MigrateState: subnetMigrateState, // Keep in sync with aws_default_subnet's schema. // See notes in vpc_default_subnet.go. @@ -142,10 +144,10 @@ func ResourceSubnet() *schema.Resource { Computed: true, }, "private_dns_hostname_type_on_launch": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice(ec2.HostnameType_Values(), false), + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateDiagFunc: enum.Validate[awstypes.HostnameType](), }, names.AttrTags: tftags.TagsSchema(), names.AttrTagsAll: tftags.TagsSchemaComputed(), @@ -160,10 +162,10 @@ func ResourceSubnet() *schema.Resource { func resourceSubnetCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateSubnetInput{ - TagSpecifications: getTagSpecificationsIn(ctx, ec2.ResourceTypeSubnet), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeSubnet), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -191,25 +193,25 @@ func resourceSubnetCreate(ctx context.Context, d *schema.ResourceData, meta inte input.OutpostArn = aws.String(v.(string)) } - output, err := conn.CreateSubnetWithContext(ctx, input) + output, err := conn.CreateSubnet(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Subnet: %s", err) } - d.SetId(aws.StringValue(output.Subnet.SubnetId)) + d.SetId(aws.ToString(output.Subnet.SubnetId)) - subnet, err := WaitSubnetAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) + subnet, err := waitSubnetAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Subnet (%s) create: %s", d.Id(), err) } for i, v := range subnet.Ipv6CidrBlockAssociationSet { - if aws.StringValue(v.Ipv6CidrBlockState.State) == ec2.SubnetCidrBlockStateCodeAssociating { //we can only ever have 1 IPv6 block associated at once - associationID := aws.StringValue(v.AssociationId) + if v.Ipv6CidrBlockState.State == awstypes.SubnetCidrBlockStateCodeAssociating { //we can only ever have 1 IPv6 block associated at once + associationID := aws.ToString(v.AssociationId) - subnetCidrBlockState, err := WaitSubnetIPv6CIDRBlockAssociationCreated(ctx, conn, associationID) + subnetCidrBlockState, err := waitSubnetIPv6CIDRBlockAssociationCreated(ctx, conn, associationID) if err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become associated: %s", d.Id(), associationID, err) @@ -228,10 +230,10 @@ func resourceSubnetCreate(ctx context.Context, d *schema.ResourceData, meta inte func resourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) outputRaw, err := tfresource.RetryWhenNewResourceNotFound(ctx, ec2PropagationTimeout, func() (interface{}, error) { - return FindSubnetByID(ctx, conn, d.Id()) + return findSubnetByID(ctx, conn, d.Id()) }, d.IsNewResource()) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -244,7 +246,7 @@ func resourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta interf return sdkdiag.AppendErrorf(diags, "reading EC2 Subnet (%s): %s", d.Id(), err) } - subnet := outputRaw.(*ec2.Subnet) + subnet := outputRaw.(*awstypes.Subnet) d.Set(names.AttrARN, subnet.SubnetArn) d.Set("assign_ipv6_address_on_creation", subnet.AssignIpv6AddressOnCreation) @@ -266,7 +268,7 @@ func resourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta interf d.Set("ipv6_cidr_block", nil) for _, v := range subnet.Ipv6CidrBlockAssociationSet { - if aws.StringValue(v.Ipv6CidrBlockState.State) == ec2.SubnetCidrBlockStateCodeAssociated { //we can only ever have 1 IPv6 block associated at once + if v.Ipv6CidrBlockState.State == awstypes.SubnetCidrBlockStateCodeAssociated { //we can only ever have 1 IPv6 block associated at once d.Set("ipv6_cidr_block_association_id", v.AssociationId) d.Set("ipv6_cidr_block", v.Ipv6CidrBlock) break @@ -290,7 +292,7 @@ func resourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta interf func resourceSubnetUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) // You cannot modify multiple subnet attributes in the same request, // except CustomerOwnedIpv4Pool and MapCustomerOwnedIpOnLaunch. @@ -323,7 +325,7 @@ func resourceSubnetUpdate(ctx context.Context, d *schema.ResourceData, meta inte } if d.HasChange("enable_lni_at_device_index") { - if err := modifySubnetEnableLniAtDeviceIndex(ctx, conn, d.Id(), int64(d.Get("enable_lni_at_device_index").(int))); err != nil { + if err := modifySubnetEnableLniAtDeviceIndex(ctx, conn, d.Id(), int32(d.Get("enable_lni_at_device_index").(int))); err != nil { return sdkdiag.AppendFromErr(diags, err) } } @@ -364,7 +366,7 @@ func resourceSubnetUpdate(ctx context.Context, d *schema.ResourceData, meta inte func resourceSubnetDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ctx = tflog.SetField(ctx, logging.KeyResourceId, d.Id()) @@ -375,7 +377,7 @@ func resourceSubnetDelete(ctx context.Context, d *schema.ResourceData, meta inte } _, err := tfresource.RetryWhenAWSErrCodeEquals(ctx, d.Timeout(schema.TimeoutDelete), func() (interface{}, error) { - return conn.DeleteSubnetWithContext(ctx, &ec2.DeleteSubnetInput{ + return conn.DeleteSubnet(ctx, &ec2.DeleteSubnetInput{ SubnetId: aws.String(d.Id()), }) }, errCodeDependencyViolation) @@ -393,16 +395,16 @@ func resourceSubnetDelete(ctx context.Context, d *schema.ResourceData, meta inte // modifySubnetAttributesOnCreate sets subnet attributes on resource Create. // Called after new subnet creation or existing default subnet adoption. -func modifySubnetAttributesOnCreate(ctx context.Context, conn *ec2.EC2, d *schema.ResourceData, subnet *ec2.Subnet, computedIPv6CidrBlock bool) error { +func modifySubnetAttributesOnCreate(ctx context.Context, conn *ec2.Client, d *schema.ResourceData, subnet *awstypes.Subnet, computedIPv6CidrBlock bool) error { // If we're disabling IPv6 assignment for new ENIs, do that before modifying the IPv6 CIDR block. - if new, old := d.Get("assign_ipv6_address_on_creation").(bool), aws.BoolValue(subnet.AssignIpv6AddressOnCreation); old != new && !new { + if new, old := d.Get("assign_ipv6_address_on_creation").(bool), aws.ToBool(subnet.AssignIpv6AddressOnCreation); old != new && !new { if err := modifySubnetAssignIPv6AddressOnCreation(ctx, conn, d.Id(), false); err != nil { return err } } // If we're disabling DNS64, do that before modifying the IPv6 CIDR block. - if new, old := d.Get("enable_dns64").(bool), aws.BoolValue(subnet.EnableDns64); old != new && !new { + if new, old := d.Get("enable_dns64").(bool), aws.ToBool(subnet.EnableDns64); old != new && !new { if err := modifySubnetEnableDNS64(ctx, conn, d.Id(), false); err != nil { return err } @@ -413,9 +415,9 @@ func modifySubnetAttributesOnCreate(ctx context.Context, conn *ec2.EC2, d *schem if !computedIPv6CidrBlock { var oldAssociationID, oldIPv6CIDRBlock string for _, v := range subnet.Ipv6CidrBlockAssociationSet { - if aws.StringValue(v.Ipv6CidrBlockState.State) == ec2.SubnetCidrBlockStateCodeAssociated { //we can only ever have 1 IPv6 block associated at once - oldAssociationID = aws.StringValue(v.AssociationId) - oldIPv6CIDRBlock = aws.StringValue(v.Ipv6CidrBlock) + if v.Ipv6CidrBlockState.State == awstypes.SubnetCidrBlockStateCodeAssociated { //we can only ever have 1 IPv6 block associated at once + oldAssociationID = aws.ToString(v.AssociationId) + oldIPv6CIDRBlock = aws.ToString(v.Ipv6CidrBlock) break } @@ -428,54 +430,54 @@ func modifySubnetAttributesOnCreate(ctx context.Context, conn *ec2.EC2, d *schem } // If we're enabling IPv6 assignment for new ENIs, do that after modifying the IPv6 CIDR block. - if new, old := d.Get("assign_ipv6_address_on_creation").(bool), aws.BoolValue(subnet.AssignIpv6AddressOnCreation); old != new && new { + if new, old := d.Get("assign_ipv6_address_on_creation").(bool), aws.ToBool(subnet.AssignIpv6AddressOnCreation); old != new && new { if err := modifySubnetAssignIPv6AddressOnCreation(ctx, conn, d.Id(), true); err != nil { return err } } if newCustomerOwnedIPOnLaunch, oldCustomerOwnedIPOnLaunch, newMapCustomerOwnedIPOnLaunch, oldMapCustomerOwnedIPOnLaunch := - d.Get("customer_owned_ipv4_pool").(string), aws.StringValue(subnet.CustomerOwnedIpv4Pool), d.Get("map_customer_owned_ip_on_launch").(bool), aws.BoolValue(subnet.MapCustomerOwnedIpOnLaunch); oldCustomerOwnedIPOnLaunch != newCustomerOwnedIPOnLaunch || oldMapCustomerOwnedIPOnLaunch != newMapCustomerOwnedIPOnLaunch { + d.Get("customer_owned_ipv4_pool").(string), aws.ToString(subnet.CustomerOwnedIpv4Pool), d.Get("map_customer_owned_ip_on_launch").(bool), aws.ToBool(subnet.MapCustomerOwnedIpOnLaunch); oldCustomerOwnedIPOnLaunch != newCustomerOwnedIPOnLaunch || oldMapCustomerOwnedIPOnLaunch != newMapCustomerOwnedIPOnLaunch { if err := modifySubnetOutpostRackAttributes(ctx, conn, d.Id(), newCustomerOwnedIPOnLaunch, newMapCustomerOwnedIPOnLaunch); err != nil { return err } } // If we're enabling DNS64, do that after modifying the IPv6 CIDR block. - if new, old := d.Get("enable_dns64").(bool), aws.BoolValue(subnet.EnableDns64); old != new && new { + if new, old := d.Get("enable_dns64").(bool), aws.ToBool(subnet.EnableDns64); old != new && new { if err := modifySubnetEnableDNS64(ctx, conn, d.Id(), true); err != nil { return err } } - if new, old := int64(d.Get("enable_lni_at_device_index").(int)), aws.Int64Value(subnet.EnableLniAtDeviceIndex); old != new && new != 0 { + if new, old := int32(d.Get("enable_lni_at_device_index").(int)), aws.ToInt32(subnet.EnableLniAtDeviceIndex); old != new && new != 0 { if err := modifySubnetEnableLniAtDeviceIndex(ctx, conn, d.Id(), new); err != nil { return err } } if subnet.PrivateDnsNameOptionsOnLaunch != nil { - if new, old := d.Get("enable_resource_name_dns_aaaa_record_on_launch").(bool), aws.BoolValue(subnet.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsAAAARecord); old != new { + if new, old := d.Get("enable_resource_name_dns_aaaa_record_on_launch").(bool), aws.ToBool(subnet.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsAAAARecord); old != new { if err := modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx, conn, d.Id(), new); err != nil { return err } } - if new, old := d.Get("enable_resource_name_dns_a_record_on_launch").(bool), aws.BoolValue(subnet.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsARecord); old != new { + if new, old := d.Get("enable_resource_name_dns_a_record_on_launch").(bool), aws.ToBool(subnet.PrivateDnsNameOptionsOnLaunch.EnableResourceNameDnsARecord); old != new { if err := modifySubnetEnableResourceNameDNSARecordOnLaunch(ctx, conn, d.Id(), new); err != nil { return err } } // private_dns_hostname_type_on_launch is Computed, so only modify if the new value is set. - if new, old := d.Get("private_dns_hostname_type_on_launch").(string), aws.StringValue(subnet.PrivateDnsNameOptionsOnLaunch.HostnameType); old != new && new != "" { + if new, old := d.Get("private_dns_hostname_type_on_launch").(string), string(subnet.PrivateDnsNameOptionsOnLaunch.HostnameType); old != new && new != "" { if err := modifySubnetPrivateDNSHostnameTypeOnLaunch(ctx, conn, d.Id(), new); err != nil { return err } } } - if new, old := d.Get("map_public_ip_on_launch").(bool), aws.BoolValue(subnet.MapPublicIpOnLaunch); old != new { + if new, old := d.Get("map_public_ip_on_launch").(bool), aws.ToBool(subnet.MapPublicIpOnLaunch); old != new { if err := modifySubnetMapPublicIPOnLaunch(ctx, conn, d.Id(), new); err != nil { return err } @@ -484,15 +486,15 @@ func modifySubnetAttributesOnCreate(ctx context.Context, conn *ec2.EC2, d *schem return nil } -func modifySubnetAssignIPv6AddressOnCreation(ctx context.Context, conn *ec2.EC2, subnetID string, v bool) error { +func modifySubnetAssignIPv6AddressOnCreation(ctx context.Context, conn *ec2.Client, subnetID string, v bool) error { input := &ec2.ModifySubnetAttributeInput{ - AssignIpv6AddressOnCreation: &ec2.AttributeBooleanValue{ + AssignIpv6AddressOnCreation: &awstypes.AttributeBooleanValue{ Value: aws.Bool(v), }, SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("setting EC2 Subnet (%s) AssignIpv6AddressOnCreation: %w", subnetID, err) } @@ -503,15 +505,15 @@ func modifySubnetAssignIPv6AddressOnCreation(ctx context.Context, conn *ec2.EC2, return nil } -func modifySubnetEnableDNS64(ctx context.Context, conn *ec2.EC2, subnetID string, v bool) error { +func modifySubnetEnableDNS64(ctx context.Context, conn *ec2.Client, subnetID string, v bool) error { input := &ec2.ModifySubnetAttributeInput{ - EnableDns64: &ec2.AttributeBooleanValue{ + EnableDns64: &awstypes.AttributeBooleanValue{ Value: aws.Bool(v), }, SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) EnableDns64: %w", subnetID, err) } @@ -522,13 +524,13 @@ func modifySubnetEnableDNS64(ctx context.Context, conn *ec2.EC2, subnetID string return nil } -func modifySubnetEnableLniAtDeviceIndex(ctx context.Context, conn *ec2.EC2, subnetID string, deviceIndex int64) error { +func modifySubnetEnableLniAtDeviceIndex(ctx context.Context, conn *ec2.Client, subnetID string, deviceIndex int32) error { input := &ec2.ModifySubnetAttributeInput{ - EnableLniAtDeviceIndex: aws.Int64(deviceIndex), + EnableLniAtDeviceIndex: aws.Int32(deviceIndex), SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) EnableLniAtDeviceIndex: %w", subnetID, err) } @@ -539,15 +541,15 @@ func modifySubnetEnableLniAtDeviceIndex(ctx context.Context, conn *ec2.EC2, subn return nil } -func modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx context.Context, conn *ec2.EC2, subnetID string, v bool) error { +func modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx context.Context, conn *ec2.Client, subnetID string, v bool) error { input := &ec2.ModifySubnetAttributeInput{ - EnableResourceNameDnsAAAARecordOnLaunch: &ec2.AttributeBooleanValue{ + EnableResourceNameDnsAAAARecordOnLaunch: &awstypes.AttributeBooleanValue{ Value: aws.Bool(v), }, SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) EnableResourceNameDnsAAAARecordOnLaunch: %w", subnetID, err) } @@ -558,15 +560,15 @@ func modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx context.Context, co return nil } -func modifySubnetEnableResourceNameDNSARecordOnLaunch(ctx context.Context, conn *ec2.EC2, subnetID string, v bool) error { +func modifySubnetEnableResourceNameDNSARecordOnLaunch(ctx context.Context, conn *ec2.Client, subnetID string, v bool) error { input := &ec2.ModifySubnetAttributeInput{ - EnableResourceNameDnsARecordOnLaunch: &ec2.AttributeBooleanValue{ + EnableResourceNameDnsARecordOnLaunch: &awstypes.AttributeBooleanValue{ Value: aws.Bool(v), }, SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) EnableResourceNameDnsARecordOnLaunch: %w", subnetID, err) } @@ -577,7 +579,7 @@ func modifySubnetEnableResourceNameDNSARecordOnLaunch(ctx context.Context, conn return nil } -func modifySubnetIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.EC2, subnetID, associationID, cidrBlock string) error { +func modifySubnetIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.Client, subnetID, associationID, cidrBlock string) error { // We need to handle that we disassociate the IPv6 CIDR block before we try to associate the new one // This could be an issue as, we could error out when we try to add the new one // We may need to roll back the state and reattach the old one if this is the case @@ -586,13 +588,13 @@ func modifySubnetIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.EC2, su AssociationId: aws.String(associationID), } - _, err := conn.DisassociateSubnetCidrBlockWithContext(ctx, input) + _, err := conn.DisassociateSubnetCidrBlock(ctx, input) if err != nil { return fmt.Errorf("disassociating EC2 Subnet (%s) IPv6 CIDR block (%s): %w", subnetID, associationID, err) } - _, err = WaitSubnetIPv6CIDRBlockAssociationDeleted(ctx, conn, associationID) + _, err = waitSubnetIPv6CIDRBlockAssociationDeleted(ctx, conn, associationID) if err != nil { return fmt.Errorf("waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become disassociated: %w", subnetID, associationID, err) @@ -605,7 +607,7 @@ func modifySubnetIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.EC2, su SubnetId: aws.String(subnetID), } - output, err := conn.AssociateSubnetCidrBlockWithContext(ctx, input) + output, err := conn.AssociateSubnetCidrBlock(ctx, input) if err != nil { //The big question here is, do we want to try to reassociate the old one?? @@ -613,9 +615,9 @@ func modifySubnetIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.EC2, su return fmt.Errorf("associating EC2 Subnet (%s) IPv6 CIDR block (%s): %w", subnetID, cidrBlock, err) } - associationID := aws.StringValue(output.Ipv6CidrBlockAssociation.AssociationId) + associationID := aws.ToString(output.Ipv6CidrBlockAssociation.AssociationId) - _, err = WaitSubnetIPv6CIDRBlockAssociationCreated(ctx, conn, associationID) + _, err = waitSubnetIPv6CIDRBlockAssociationCreated(ctx, conn, associationID) if err != nil { return fmt.Errorf("waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become associated: %w", subnetID, associationID, err) @@ -625,28 +627,28 @@ func modifySubnetIPv6CIDRBlockAssociation(ctx context.Context, conn *ec2.EC2, su return nil } -func modifySubnetMapPublicIPOnLaunch(ctx context.Context, conn *ec2.EC2, subnetID string, v bool) error { +func modifySubnetMapPublicIPOnLaunch(ctx context.Context, conn *ec2.Client, subnetID string, v bool) error { input := &ec2.ModifySubnetAttributeInput{ - MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{ + MapPublicIpOnLaunch: &awstypes.AttributeBooleanValue{ Value: aws.Bool(v), }, SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) MapPublicIpOnLaunch: %w", subnetID, err) } - if _, err := WaitSubnetMapPublicIPOnLaunchUpdated(ctx, conn, subnetID, v); err != nil { + if _, err := waitSubnetMapPublicIPOnLaunchUpdated(ctx, conn, subnetID, v); err != nil { return fmt.Errorf("waiting for EC2 Subnet (%s) MapPublicIpOnLaunch update: %w", subnetID, err) } return nil } -func modifySubnetOutpostRackAttributes(ctx context.Context, conn *ec2.EC2, subnetID string, customerOwnedIPv4Pool string, mapCustomerOwnedIPOnLaunch bool) error { +func modifySubnetOutpostRackAttributes(ctx context.Context, conn *ec2.Client, subnetID string, customerOwnedIPv4Pool string, mapCustomerOwnedIPOnLaunch bool) error { input := &ec2.ModifySubnetAttributeInput{ - MapCustomerOwnedIpOnLaunch: &ec2.AttributeBooleanValue{ + MapCustomerOwnedIpOnLaunch: &awstypes.AttributeBooleanValue{ Value: aws.Bool(mapCustomerOwnedIPOnLaunch), }, SubnetId: aws.String(subnetID), @@ -656,28 +658,28 @@ func modifySubnetOutpostRackAttributes(ctx context.Context, conn *ec2.EC2, subne input.CustomerOwnedIpv4Pool = aws.String(customerOwnedIPv4Pool) } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) CustomerOwnedIpv4Pool/MapCustomerOwnedIpOnLaunch: %w", subnetID, err) } - if _, err := WaitSubnetMapCustomerOwnedIPOnLaunchUpdated(ctx, conn, subnetID, mapCustomerOwnedIPOnLaunch); err != nil { + if _, err := waitSubnetMapCustomerOwnedIPOnLaunchUpdated(ctx, conn, subnetID, mapCustomerOwnedIPOnLaunch); err != nil { return fmt.Errorf("waiting for EC2 Subnet (%s) MapCustomerOwnedIpOnLaunch update: %w", subnetID, err) } return nil } -func modifySubnetPrivateDNSHostnameTypeOnLaunch(ctx context.Context, conn *ec2.EC2, subnetID string, v string) error { +func modifySubnetPrivateDNSHostnameTypeOnLaunch(ctx context.Context, conn *ec2.Client, subnetID string, v string) error { input := &ec2.ModifySubnetAttributeInput{ - PrivateDnsHostnameTypeOnLaunch: aws.String(v), + PrivateDnsHostnameTypeOnLaunch: awstypes.HostnameType(v), SubnetId: aws.String(subnetID), } - if _, err := conn.ModifySubnetAttributeWithContext(ctx, input); err != nil { + if _, err := conn.ModifySubnetAttribute(ctx, input); err != nil { return fmt.Errorf("modifying EC2 Subnet (%s) PrivateDnsHostnameTypeOnLaunch: %w", subnetID, err) } - if _, err := WaitSubnetPrivateDNSHostnameTypeOnLaunchUpdated(ctx, conn, subnetID, v); err != nil { + if _, err := waitSubnetPrivateDNSHostnameTypeOnLaunchUpdated(ctx, conn, subnetID, v); err != nil { return fmt.Errorf("waiting for EC2 Subnet (%s) PrivateDnsHostnameTypeOnLaunch update: %w", subnetID, err) } diff --git a/internal/service/ec2/vpc_subnet_cidr_reservation.go b/internal/service/ec2/vpc_subnet_cidr_reservation.go index f4214a09fa5..a3156e95f1b 100644 --- a/internal/service/ec2/vpc_subnet_cidr_reservation.go +++ b/internal/service/ec2/vpc_subnet_cidr_reservation.go @@ -9,21 +9,22 @@ import ( "log" "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "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/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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/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/tfresource" "github.com/hashicorp/terraform-provider-aws/internal/verify" "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKResource("aws_ec2_subnet_cidr_reservation") -func ResourceSubnetCIDRReservation() *schema.Resource { +// @SDKResource("aws_ec2_subnet_cidr_reservation", name="Subnet CIDR Reservation") +func resourceSubnetCIDRReservation() *schema.Resource { return &schema.Resource{ CreateWithoutTimeout: resourceSubnetCIDRReservationCreate, ReadWithoutTimeout: resourceSubnetCIDRReservationRead, @@ -61,10 +62,10 @@ func ResourceSubnetCIDRReservation() *schema.Resource { Computed: true, }, "reservation_type": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice(ec2.SubnetCidrReservationType_Values(), false), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateDiagFunc: enum.Validate[awstypes.SubnetCidrReservationType](), }, names.AttrSubnetID: { Type: schema.TypeString, @@ -77,11 +78,11 @@ func ResourceSubnetCIDRReservation() *schema.Resource { func resourceSubnetCIDRReservationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateSubnetCidrReservationInput{ Cidr: aws.String(d.Get(names.AttrCIDRBlock).(string)), - ReservationType: aws.String(d.Get("reservation_type").(string)), + ReservationType: awstypes.SubnetCidrReservationType(d.Get("reservation_type").(string)), SubnetId: aws.String(d.Get(names.AttrSubnetID).(string)), } @@ -89,23 +90,23 @@ func resourceSubnetCIDRReservationCreate(ctx context.Context, d *schema.Resource input.Description = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating EC2 Subnet CIDR Reservation: %s", input) - output, err := conn.CreateSubnetCidrReservationWithContext(ctx, input) + log.Printf("[DEBUG] Creating EC2 Subnet CIDR Reservation: %s", aws.ToString(input.SubnetId)) + output, err := conn.CreateSubnetCidrReservation(ctx, input) if err != nil { return sdkdiag.AppendErrorf(diags, "creating EC2 Subnet CIDR Reservation: %s", err) } - d.SetId(aws.StringValue(output.SubnetCidrReservation.SubnetCidrReservationId)) + d.SetId(aws.ToString(output.SubnetCidrReservation.SubnetCidrReservationId)) return append(diags, resourceSubnetCIDRReservationRead(ctx, d, meta)...) } func resourceSubnetCIDRReservationRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) - output, err := FindSubnetCIDRReservationBySubnetIDAndReservationID(ctx, conn, d.Get(names.AttrSubnetID).(string), d.Id()) + output, err := findSubnetCIDRReservationBySubnetIDAndReservationID(ctx, conn, d.Get(names.AttrSubnetID).(string), d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] EC2 Subnet CIDR Reservation (%s) not found, removing from state", d.Id()) @@ -128,10 +129,10 @@ func resourceSubnetCIDRReservationRead(ctx context.Context, d *schema.ResourceDa func resourceSubnetCIDRReservationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) log.Printf("[INFO] Deleting EC2 Subnet CIDR Reservation: %s", d.Id()) - _, err := conn.DeleteSubnetCidrReservationWithContext(ctx, &ec2.DeleteSubnetCidrReservationInput{ + _, err := conn.DeleteSubnetCidrReservation(ctx, &ec2.DeleteSubnetCidrReservationInput{ SubnetCidrReservationId: aws.String(d.Id()), }) diff --git a/internal/service/ec2/vpc_subnet_cidr_reservation_test.go b/internal/service/ec2/vpc_subnet_cidr_reservation_test.go index ace2d7ada96..d3d552ad080 100644 --- a/internal/service/ec2/vpc_subnet_cidr_reservation_test.go +++ b/internal/service/ec2/vpc_subnet_cidr_reservation_test.go @@ -8,7 +8,7 @@ import ( "fmt" "testing" - "github.com/aws/aws-sdk-go/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -21,7 +21,7 @@ import ( func TestAccVPCSubnetCIDRReservation_basic(t *testing.T) { ctx := acctest.Context(t) - var res ec2.SubnetCidrReservation + var res awstypes.SubnetCidrReservation resourceName := "aws_ec2_subnet_cidr_reservation.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -53,7 +53,7 @@ func TestAccVPCSubnetCIDRReservation_basic(t *testing.T) { func TestAccVPCSubnetCIDRReservation_ipv6(t *testing.T) { ctx := acctest.Context(t) - var res ec2.SubnetCidrReservation + var res awstypes.SubnetCidrReservation resourceName := "aws_ec2_subnet_cidr_reservation.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -83,7 +83,7 @@ func TestAccVPCSubnetCIDRReservation_ipv6(t *testing.T) { func TestAccVPCSubnetCIDRReservation_disappears(t *testing.T) { ctx := acctest.Context(t) - var res ec2.SubnetCidrReservation + var res awstypes.SubnetCidrReservation resourceName := "aws_ec2_subnet_cidr_reservation.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -105,7 +105,7 @@ func TestAccVPCSubnetCIDRReservation_disappears(t *testing.T) { }) } -func testAccCheckSubnetCIDRReservationExists(ctx context.Context, n string, v *ec2.SubnetCidrReservation) resource.TestCheckFunc { +func testAccCheckSubnetCIDRReservationExists(ctx context.Context, n string, v *awstypes.SubnetCidrReservation) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -116,7 +116,7 @@ func testAccCheckSubnetCIDRReservationExists(ctx context.Context, n string, v *e return fmt.Errorf("No EC2 Subnet CIDR Reservation ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindSubnetCIDRReservationBySubnetIDAndReservationID(ctx, conn, rs.Primary.Attributes[names.AttrSubnetID], rs.Primary.ID) @@ -132,7 +132,7 @@ func testAccCheckSubnetCIDRReservationExists(ctx context.Context, n string, v *e func testAccCheckSubnetCIDRReservationDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_ec2_subnet_cidr_reservation" { diff --git a/internal/service/ec2/vpc_subnet_data_source.go b/internal/service/ec2/vpc_subnet_data_source.go index f6a3f01cba0..65c1dffa753 100644 --- a/internal/service/ec2/vpc_subnet_data_source.go +++ b/internal/service/ec2/vpc_subnet_data_source.go @@ -7,8 +7,9 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/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" @@ -19,7 +20,7 @@ import ( ) // @SDKDataSource("aws_subnet") -func DataSourceSubnet() *schema.Resource { +func dataSourceSubnet() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceSubnetRead, @@ -136,13 +137,13 @@ func DataSourceSubnet() *schema.Resource { func dataSourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig input := &ec2.DescribeSubnetsInput{} if id, ok := d.GetOk(names.AttrID); ok { - input.SubnetIds = []*string{aws.String(id.(string))} + input.SubnetIds = []string{id.(string)} } // We specify default_for_az as boolean, but EC2 filters want @@ -187,13 +188,13 @@ func dataSourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta inte input.Filters = nil } - subnet, err := FindSubnet(ctx, conn, input) + subnet, err := findSubnet(ctx, conn, input) if err != nil { return sdkdiag.AppendFromErr(diags, tfresource.SingularDataSourceFindError("EC2 Subnet", err)) } - d.SetId(aws.StringValue(subnet.SubnetId)) + d.SetId(aws.ToString(subnet.SubnetId)) d.Set(names.AttrARN, subnet.SubnetArn) d.Set("assign_ipv6_address_on_creation", subnet.AssignIpv6AddressOnCreation) @@ -212,7 +213,7 @@ func dataSourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set("ipv6_cidr_block", nil) for _, v := range subnet.Ipv6CidrBlockAssociationSet { - if v.Ipv6CidrBlockState != nil && aws.StringValue(v.Ipv6CidrBlockState.State) == ec2.VpcCidrBlockStateCodeAssociated { //we can only ever have 1 IPv6 block associated at once + if v.Ipv6CidrBlockState != nil && v.Ipv6CidrBlockState.State == awstypes.SubnetCidrBlockStateCodeAssociated { //we can only ever have 1 IPv6 block associated at once d.Set("ipv6_cidr_block_association_id", v.AssociationId) d.Set("ipv6_cidr_block", v.Ipv6CidrBlock) } @@ -234,7 +235,7 @@ func dataSourceSubnetRead(ctx context.Context, d *schema.ResourceData, meta inte d.Set("private_dns_hostname_type_on_launch", nil) } - if err := d.Set(names.AttrTags, KeyValueTags(ctx, subnet.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + if err := d.Set(names.AttrTags, keyValueTags(ctx, subnet.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return sdkdiag.AppendErrorf(diags, "setting tags: %s", err) } diff --git a/internal/service/ec2/vpc_subnet_migrate.go b/internal/service/ec2/vpc_subnet_migrate.go index c5b5575cd21..34b7c53ebd6 100644 --- a/internal/service/ec2/vpc_subnet_migrate.go +++ b/internal/service/ec2/vpc_subnet_migrate.go @@ -10,8 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func SubnetMigrateState( - v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { +func subnetMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { switch v { case 0: log.Println("[INFO] Found AWS Subnet State v0; migrating to v1") diff --git a/internal/service/ec2/vpc_subnet_tags_gen_test.go b/internal/service/ec2/vpc_subnet_tags_gen_test.go index 8abd2e9b0eb..9cdc2c35f8f 100644 --- a/internal/service/ec2/vpc_subnet_tags_gen_test.go +++ b/internal/service/ec2/vpc_subnet_tags_gen_test.go @@ -5,7 +5,7 @@ package ec2_test import ( "testing" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/hashicorp/terraform-plugin-testing/config" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -19,7 +19,7 @@ import ( func TestAccVPCSubnet_tags(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -190,7 +190,7 @@ func TestAccVPCSubnet_tags(t *testing.T) { func TestAccVPCSubnet_tags_null(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -250,7 +250,7 @@ func TestAccVPCSubnet_tags_null(t *testing.T) { func TestAccVPCSubnet_tags_AddOnUpdate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -327,7 +327,7 @@ func TestAccVPCSubnet_tags_AddOnUpdate(t *testing.T) { func TestAccVPCSubnet_tags_EmptyTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -412,7 +412,7 @@ func TestAccVPCSubnet_tags_EmptyTag_OnCreate(t *testing.T) { func TestAccVPCSubnet_tags_EmptyTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -539,7 +539,7 @@ func TestAccVPCSubnet_tags_EmptyTag_OnUpdate_Add(t *testing.T) { func TestAccVPCSubnet_tags_EmptyTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -622,7 +622,7 @@ func TestAccVPCSubnet_tags_EmptyTag_OnUpdate_Replace(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_providerOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -803,7 +803,7 @@ func TestAccVPCSubnet_tags_DefaultTags_providerOnly(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_nonOverlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -963,7 +963,7 @@ func TestAccVPCSubnet_tags_DefaultTags_nonOverlapping(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_overlapping(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1139,7 +1139,7 @@ func TestAccVPCSubnet_tags_DefaultTags_overlapping(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_updateToProviderOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1229,7 +1229,7 @@ func TestAccVPCSubnet_tags_DefaultTags_updateToProviderOnly(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_updateToResourceOnly(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1318,7 +1318,7 @@ func TestAccVPCSubnet_tags_DefaultTags_updateToResourceOnly(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_emptyResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1383,7 +1383,7 @@ func TestAccVPCSubnet_tags_DefaultTags_emptyResourceTag(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_emptyProviderOnlyTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1440,7 +1440,7 @@ func TestAccVPCSubnet_tags_DefaultTags_emptyProviderOnlyTag(t *testing.T) { func TestAccVPCSubnet_tags_DefaultTags_nullOverlappingResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1502,7 +1502,7 @@ func TestAccVPCSubnet_tags_DefaultTags_nullOverlappingResourceTag(t *testing.T) func TestAccVPCSubnet_tags_DefaultTags_nullNonOverlappingResourceTag(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1564,7 +1564,7 @@ func TestAccVPCSubnet_tags_DefaultTags_nullNonOverlappingResourceTag(t *testing. func TestAccVPCSubnet_tags_ComputedTag_OnCreate(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1618,7 +1618,7 @@ func TestAccVPCSubnet_tags_ComputedTag_OnCreate(t *testing.T) { func TestAccVPCSubnet_tags_ComputedTag_OnUpdate_Add(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -1708,7 +1708,7 @@ func TestAccVPCSubnet_tags_ComputedTag_OnUpdate_Add(t *testing.T) { func TestAccVPCSubnet_tags_ComputedTag_OnUpdate_Replace(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v types.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) diff --git a/internal/service/ec2/vpc_subnet_test.go b/internal/service/ec2/vpc_subnet_test.go index ad783d97913..fe6f1e94a0e 100644 --- a/internal/service/ec2/vpc_subnet_test.go +++ b/internal/service/ec2/vpc_subnet_test.go @@ -9,8 +9,8 @@ import ( "testing" "github.com/YakDriver/regexache" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" "github.com/hashicorp/terraform-plugin-testing/terraform" @@ -23,7 +23,7 @@ import ( func TestAccVPCSubnet_basic(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -66,7 +66,7 @@ func TestAccVPCSubnet_basic(t *testing.T) { func TestAccVPCSubnet_tags_defaultAndIgnoreTags(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -104,7 +104,7 @@ func TestAccVPCSubnet_tags_defaultAndIgnoreTags(t *testing.T) { func TestAccVPCSubnet_tags_ignoreTags(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -136,7 +136,7 @@ func TestAccVPCSubnet_tags_ignoreTags(t *testing.T) { func TestAccVPCSubnet_ipv6(t *testing.T) { ctx := acctest.Context(t) - var before, after ec2.Subnet + var before, after awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -178,7 +178,7 @@ func TestAccVPCSubnet_ipv6(t *testing.T) { func TestAccVPCSubnet_enableIPv6(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -223,7 +223,7 @@ func TestAccVPCSubnet_enableIPv6(t *testing.T) { func TestAccVPCSubnet_availabilityZoneID(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -252,7 +252,7 @@ func TestAccVPCSubnet_availabilityZoneID(t *testing.T) { func TestAccVPCSubnet_disappears(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -276,7 +276,7 @@ func TestAccVPCSubnet_disappears(t *testing.T) { func TestAccVPCSubnet_customerOwnedIPv4Pool(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet coipDataSourceName := "data.aws_ec2_coip_pool.test" resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -305,7 +305,7 @@ func TestAccVPCSubnet_customerOwnedIPv4Pool(t *testing.T) { func TestAccVPCSubnet_mapCustomerOwnedIPOnLaunch(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -333,7 +333,7 @@ func TestAccVPCSubnet_mapCustomerOwnedIPOnLaunch(t *testing.T) { func TestAccVPCSubnet_mapPublicIPOnLaunch(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -375,7 +375,7 @@ func TestAccVPCSubnet_mapPublicIPOnLaunch(t *testing.T) { func TestAccVPCSubnet_outpost(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet outpostDataSourceName := "data.aws_outposts_outpost.test" resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -404,7 +404,7 @@ func TestAccVPCSubnet_outpost(t *testing.T) { func TestAccVPCSubnet_enableDNS64(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -446,7 +446,7 @@ func TestAccVPCSubnet_enableDNS64(t *testing.T) { func TestAccVPCSubnet_ipv4ToIPv6(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -482,7 +482,7 @@ func TestAccVPCSubnet_ipv4ToIPv6(t *testing.T) { func TestAccVPCSubnet_enableLNIAtDeviceIndex(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -524,7 +524,7 @@ func TestAccVPCSubnet_enableLNIAtDeviceIndex(t *testing.T) { func TestAccVPCSubnet_privateDNSNameOptionsOnLaunch(t *testing.T) { ctx := acctest.Context(t) - var subnet ec2.Subnet + var subnet awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -572,7 +572,7 @@ func TestAccVPCSubnet_privateDNSNameOptionsOnLaunch(t *testing.T) { func TestAccVPCSubnet_ipv6Native(t *testing.T) { ctx := acctest.Context(t) - var v ec2.Subnet + var v awstypes.Subnet resourceName := "aws_subnet.test" rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) @@ -600,35 +600,35 @@ func TestAccVPCSubnet_ipv6Native(t *testing.T) { }) } -func testAccCheckSubnetIPv6BeforeUpdate(subnet *ec2.Subnet) resource.TestCheckFunc { +func testAccCheckSubnetIPv6BeforeUpdate(subnet *awstypes.Subnet) resource.TestCheckFunc { return func(s *terraform.State) error { if subnet.Ipv6CidrBlockAssociationSet == nil { return fmt.Errorf("Expected IPV6 CIDR Block Association") } - if !aws.BoolValue(subnet.AssignIpv6AddressOnCreation) { - return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", aws.BoolValue(subnet.AssignIpv6AddressOnCreation)) + if !aws.ToBool(subnet.AssignIpv6AddressOnCreation) { + return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", aws.ToBool(subnet.AssignIpv6AddressOnCreation)) } return nil } } -func testAccCheckSubnetIPv6AfterUpdate(subnet *ec2.Subnet) resource.TestCheckFunc { +func testAccCheckSubnetIPv6AfterUpdate(subnet *awstypes.Subnet) resource.TestCheckFunc { return func(s *terraform.State) error { - if aws.BoolValue(subnet.AssignIpv6AddressOnCreation) { - return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", aws.BoolValue(subnet.AssignIpv6AddressOnCreation)) + if aws.ToBool(subnet.AssignIpv6AddressOnCreation) { + return fmt.Errorf("bad AssignIpv6AddressOnCreation: %t", aws.ToBool(subnet.AssignIpv6AddressOnCreation)) } return nil } } -func testAccCheckSubnetNotRecreated(t *testing.T, before, after *ec2.Subnet) resource.TestCheckFunc { +func testAccCheckSubnetNotRecreated(t *testing.T, before, after *awstypes.Subnet) resource.TestCheckFunc { return func(s *terraform.State) error { - if aws.StringValue(before.SubnetId) != aws.StringValue(after.SubnetId) { + if aws.ToString(before.SubnetId) != aws.ToString(after.SubnetId) { t.Fatalf("Expected SubnetIDs not to change, but both got before: %s and after: %s", - aws.StringValue(before.SubnetId), aws.StringValue(after.SubnetId)) + aws.ToString(before.SubnetId), aws.ToString(after.SubnetId)) } return nil } @@ -636,7 +636,7 @@ func testAccCheckSubnetNotRecreated(t *testing.T, before, after *ec2.Subnet) res func testAccCheckSubnetDestroy(ctx context.Context) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) for _, rs := range s.RootModule().Resources { if rs.Type != "aws_subnet" { @@ -660,7 +660,7 @@ func testAccCheckSubnetDestroy(ctx context.Context) resource.TestCheckFunc { } } -func testAccCheckSubnetExists(ctx context.Context, n string, v *ec2.Subnet) resource.TestCheckFunc { +func testAccCheckSubnetExists(ctx context.Context, n string, v *awstypes.Subnet) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -671,7 +671,7 @@ func testAccCheckSubnetExists(ctx context.Context, n string, v *ec2.Subnet) reso return fmt.Errorf("No EC2 Subnet ID is set") } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) output, err := tfec2.FindSubnetByID(ctx, conn, rs.Primary.ID) @@ -685,11 +685,11 @@ func testAccCheckSubnetExists(ctx context.Context, n string, v *ec2.Subnet) reso } } -func testAccCheckSubnetUpdateTags(ctx context.Context, subnet *ec2.Subnet, oldTags, newTags map[string]string) resource.TestCheckFunc { +func testAccCheckSubnetUpdateTags(ctx context.Context, subnet *awstypes.Subnet, oldTags, newTags map[string]string) resource.TestCheckFunc { return func(s *terraform.State) error { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - return tfec2.UpdateTags(ctx, conn, aws.StringValue(subnet.SubnetId), oldTags, newTags) + return tfec2.UpdateTags(ctx, conn, aws.ToString(subnet.SubnetId), oldTags, newTags) } } diff --git a/internal/service/ec2/vpc_subnets_data_source.go b/internal/service/ec2/vpc_subnets_data_source.go index 0bb18ab1e20..677f55817f6 100644 --- a/internal/service/ec2/vpc_subnets_data_source.go +++ b/internal/service/ec2/vpc_subnets_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_subnets") -func DataSourceSubnets() *schema.Resource { +// @SDKDataSource("aws_subnets", name "Subnets") +func dataSourceSubnets() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceSubnetsRead, @@ -40,7 +40,7 @@ func DataSourceSubnets() *schema.Resource { func dataSourceSubnetsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeSubnetsInput{} @@ -59,7 +59,7 @@ func dataSourceSubnetsRead(ctx context.Context, d *schema.ResourceData, meta int input.Filters = nil } - output, err := FindSubnets(ctx, conn, input) + output, err := findSubnets(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Subnets: %s", err) @@ -68,7 +68,7 @@ func dataSourceSubnetsRead(ctx context.Context, d *schema.ResourceData, meta int var subnetIDs []string for _, v := range output { - subnetIDs = append(subnetIDs, aws.StringValue(v.SubnetId)) + subnetIDs = append(subnetIDs, aws.ToString(v.SubnetId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpc_test.go b/internal/service/ec2/vpc_test.go index afcb52e7bc9..81459ab4192 100644 --- a/internal/service/ec2/vpc_test.go +++ b/internal/service/ec2/vpc_test.go @@ -36,7 +36,7 @@ func TestAccVPC_basic(t *testing.T) { { Config: testAccVPCConfig_basic, Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), acctest.MatchResourceAttrRegionalARN(resourceName, names.AttrARN, "ec2", regexache.MustCompile(`vpc/vpc-.+`)), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, names.AttrCIDRBlock, "10.1.0.0/16"), @@ -83,7 +83,7 @@ func TestAccVPC_disappears(t *testing.T) { { Config: testAccVPCConfig_basic, Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), acctest.CheckResourceDisappears(ctx, acctest.Provider, tfec2.ResourceVPC(), resourceName), ), ExpectNonEmptyPlan: true, @@ -111,7 +111,7 @@ func TestAccVPC_DynamicResourceTagsMergedWithLocals_ignoreChanges(t *testing.T) { Config: testAccVPCConfig_ignoreChangesDynamicTagsMergedLocals("localkey", "localvalue"), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct3), resource.TestCheckResourceAttr(resourceName, "tags.localkey", "localvalue"), resource.TestCheckResourceAttrSet(resourceName, "tags.created_at"), @@ -129,7 +129,7 @@ func TestAccVPC_DynamicResourceTagsMergedWithLocals_ignoreChanges(t *testing.T) { Config: testAccVPCConfig_ignoreChangesDynamicTagsMergedLocals("localkey", "localvalue"), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct3), resource.TestCheckResourceAttr(resourceName, "tags.localkey", "localvalue"), resource.TestCheckResourceAttrSet(resourceName, "tags.created_at"), @@ -166,7 +166,7 @@ func TestAccVPC_DynamicResourceTags_ignoreChanges(t *testing.T) { { Config: testAccVPCConfig_ignoreChangesDynamicTags, Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct2), resource.TestCheckResourceAttrSet(resourceName, "tags.created_at"), resource.TestCheckResourceAttrSet(resourceName, "tags.updated_at"), @@ -182,7 +182,7 @@ func TestAccVPC_DynamicResourceTags_ignoreChanges(t *testing.T) { { Config: testAccVPCConfig_ignoreChangesDynamicTags, Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, acctest.CtTagsPercent, acctest.Ct2), resource.TestCheckResourceAttrSet(resourceName, "tags.created_at"), resource.TestCheckResourceAttrSet(resourceName, "tags.updated_at"), @@ -212,7 +212,7 @@ func TestAccVPC_tags_defaultAndIgnoreTags(t *testing.T) { { Config: testAccVPCConfig_tags1(acctest.CtKey1, acctest.CtValue1), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), testAccCheckVPCUpdateTags(ctx, &vpc, nil, map[string]string{"defaultkey1": "defaultvalue1"}), ), ExpectNonEmptyPlan: true, @@ -249,7 +249,7 @@ func TestAccVPC_tags_ignoreTags(t *testing.T) { { Config: testAccVPCConfig_tags1(acctest.CtKey1, acctest.CtValue1), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), testAccCheckVPCUpdateTags(ctx, &vpc, nil, map[string]string{"ignorekey1": "ignorevalue1"}), ), ExpectNonEmptyPlan: true, @@ -282,7 +282,7 @@ func TestAccVPC_tenancy(t *testing.T) { { Config: testAccVPCConfig_dedicatedTenancy(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpcDedicated), + acctest.CheckVPCExists(ctx, resourceName, &vpcDedicated), resource.TestCheckResourceAttr(resourceName, "instance_tenancy", "dedicated"), ), }, @@ -294,7 +294,7 @@ func TestAccVPC_tenancy(t *testing.T) { { Config: testAccVPCConfig_default(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpcDefault), + acctest.CheckVPCExists(ctx, resourceName, &vpcDefault), resource.TestCheckResourceAttr(resourceName, "instance_tenancy", "default"), testAccCheckVPCIDsEqual(&vpcDedicated, &vpcDefault), ), @@ -302,7 +302,7 @@ func TestAccVPC_tenancy(t *testing.T) { { Config: testAccVPCConfig_dedicatedTenancy(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpcDedicated), + acctest.CheckVPCExists(ctx, resourceName, &vpcDedicated), resource.TestCheckResourceAttr(resourceName, "instance_tenancy", "dedicated"), testAccCheckVPCIDsNotEqual(&vpcDedicated, &vpcDefault), ), @@ -326,14 +326,14 @@ func TestAccVPC_updateDNSHostnames(t *testing.T) { { Config: testAccVPCConfig_default(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "enable_dns_hostnames", acctest.CtFalse), ), }, { Config: testAccVPCConfig_enableDNSHostnames(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "enable_dns_hostnames", acctest.CtTrue), ), }, @@ -357,7 +357,7 @@ func TestAccVPC_bothDNSOptionsSet(t *testing.T) { { Config: testAccVPCConfig_bothDNSOptions(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "enable_dns_hostnames", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, "enable_dns_support", acctest.CtTrue), ), @@ -387,7 +387,7 @@ func TestAccVPC_disabledDNSSupport(t *testing.T) { { Config: testAccVPCConfig_disabledDNSSupport(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "enable_dns_support", acctest.CtFalse), ), }, @@ -415,7 +415,7 @@ func TestAccVPC_enableNetworkAddressUsageMetrics(t *testing.T) { { Config: testAccVPCConfig_enableNetworkAddressUsageMetrics(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "enable_network_address_usage_metrics", acctest.CtTrue), ), }, @@ -443,7 +443,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlock(t *testing.T) { { Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlock(rName, true), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, names.AttrCIDRBlock, "10.1.0.0/16"), resource.TestCheckResourceAttrSet(resourceName, "ipv6_association_id"), @@ -458,7 +458,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlock(t *testing.T) { { Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlock(rName, false), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, names.AttrCIDRBlock, "10.1.0.0/16"), resource.TestCheckResourceAttr(resourceName, "ipv6_association_id", ""), @@ -468,7 +468,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlock(t *testing.T) { { Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlock(rName, true), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtTrue), resource.TestCheckResourceAttr(resourceName, names.AttrCIDRBlock, "10.1.0.0/16"), resource.TestCheckResourceAttrSet(resourceName, "ipv6_association_id"), @@ -502,7 +502,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlockWithNetworkBorderGroup(t *testing.T) { Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlockOptionalNetworkBorderGroup(rName, true), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtTrue), resource.TestCheckResourceAttrSet(resourceName, "ipv6_association_id"), resource.TestCheckResourceAttrSet(resourceName, "ipv6_cidr_block"), @@ -519,7 +519,7 @@ func TestAccVPC_assignGeneratedIPv6CIDRBlockWithNetworkBorderGroup(t *testing.T) { Config: testAccVPCConfig_assignGeneratedIPv6CIDRBlockOptionalNetworkBorderGroup(rName, false), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtTrue), resource.TestCheckResourceAttrSet(resourceName, "ipv6_association_id"), resource.TestCheckResourceAttrSet(resourceName, "ipv6_cidr_block"), @@ -551,7 +551,7 @@ func TestAccVPC_IPAMIPv4BasicNetmask(t *testing.T) { { Config: testAccVPCConfig_ipamIPv4(rName, 28), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), testAccCheckVPCCIDRPrefix(&vpc, "28"), ), }, @@ -579,7 +579,7 @@ func TestAccVPC_IPAMIPv4BasicExplicitCIDR(t *testing.T) { { Config: testAccVPCConfig_ipamIPv4ExplicitCIDR(rName, cidr), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, names.AttrCIDRBlock, cidr), ), }, @@ -607,7 +607,7 @@ func TestAccVPC_IPAMIPv6(t *testing.T) { { Config: testAccVPCConfig_ipamIPv6(rName, 28), Check: resource.ComposeAggregateTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, resourceName, &vpc), + acctest.CheckVPCExists(ctx, resourceName, &vpc), resource.TestCheckResourceAttr(resourceName, "assign_generated_ipv6_cidr_block", acctest.CtFalse), resource.TestCheckResourceAttr(resourceName, names.AttrCIDRBlock, "10.1.0.0/16"), resource.TestCheckResourceAttrSet(resourceName, "ipv6_association_id"), @@ -630,7 +630,7 @@ func testAccCheckVPCDestroy(ctx context.Context) resource.TestCheckFunc { continue } - _, err := tfec2.FindVPCByIDV2(ctx, conn, rs.Primary.ID) + _, err := tfec2.FindVPCByID(ctx, conn, rs.Primary.ID) if tfresource.NotFound(err) { continue @@ -651,7 +651,7 @@ func testAccCheckVPCUpdateTags(ctx context.Context, vpc *awstypes.Vpc, oldTags, return func(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - return tfec2.UpdateTagsV2(ctx, conn, aws.ToString(vpc.VpcId), oldTags, newTags) + return tfec2.UpdateTags(ctx, conn, aws.ToString(vpc.VpcId), oldTags, newTags) } } @@ -686,7 +686,7 @@ func testAccCheckVPCIDsNotEqual(vpc1, vpc2 *awstypes.Vpc) resource.TestCheckFunc } func testAccCheckVPCExists(ctx context.Context, n string, v *awstypes.Vpc) resource.TestCheckFunc { - return acctest.CheckVPCExistsV2(ctx, n, v) + return acctest.CheckVPCExists(ctx, n, v) } const testAccVPCConfig_basic = ` diff --git a/internal/service/ec2/vpc_traffic_mirror_filter.go b/internal/service/ec2/vpc_traffic_mirror_filter.go index fcef358a1d0..545f89cb773 100644 --- a/internal/service/ec2/vpc_traffic_mirror_filter.go +++ b/internal/service/ec2/vpc_traffic_mirror_filter.go @@ -75,7 +75,7 @@ func resourceTrafficMirrorFilterCreate(ctx context.Context, d *schema.ResourceDa input := &ec2.CreateTrafficMirrorFilterInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTrafficMirrorFilter), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTrafficMirrorFilter), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -133,7 +133,7 @@ func resourceTrafficMirrorFilterRead(ctx context.Context, d *schema.ResourceData d.Set(names.AttrDescription, trafficMirrorFilter.Description) d.Set("network_services", trafficMirrorFilter.NetworkServices) - setTagsOutV2(ctx, trafficMirrorFilter.Tags) + setTagsOut(ctx, trafficMirrorFilter.Tags) return diags } diff --git a/internal/service/ec2/vpc_traffic_mirror_session.go b/internal/service/ec2/vpc_traffic_mirror_session.go index 64180a61e64..61cafc04b22 100644 --- a/internal/service/ec2/vpc_traffic_mirror_session.go +++ b/internal/service/ec2/vpc_traffic_mirror_session.go @@ -95,7 +95,7 @@ func resourceTrafficMirrorSessionCreate(ctx context.Context, d *schema.ResourceD input := &ec2.CreateTrafficMirrorSessionInput{ ClientToken: aws.String(id.UniqueId()), NetworkInterfaceId: aws.String(d.Get(names.AttrNetworkInterfaceID).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTrafficMirrorSession), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTrafficMirrorSession), TrafficMirrorFilterId: aws.String(d.Get("traffic_mirror_filter_id").(string)), TrafficMirrorTargetId: aws.String(d.Get("traffic_mirror_target_id").(string)), } @@ -161,7 +161,7 @@ func resourceTrafficMirrorSessionRead(ctx context.Context, d *schema.ResourceDat d.Set("traffic_mirror_target_id", session.TrafficMirrorTargetId) d.Set("virtual_network_id", session.VirtualNetworkId) - setTagsOutV2(ctx, session.Tags) + setTagsOut(ctx, session.Tags) return diags } diff --git a/internal/service/ec2/vpc_traffic_mirror_target.go b/internal/service/ec2/vpc_traffic_mirror_target.go index 5c692de035e..402b7b6daeb 100644 --- a/internal/service/ec2/vpc_traffic_mirror_target.go +++ b/internal/service/ec2/vpc_traffic_mirror_target.go @@ -97,7 +97,7 @@ func resourceTrafficMirrorTargetCreate(ctx context.Context, d *schema.ResourceDa input := &ec2.CreateTrafficMirrorTargetInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeTrafficMirrorTarget), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeTrafficMirrorTarget), } if v, ok := d.GetOk(names.AttrDescription); ok { @@ -146,7 +146,7 @@ func resourceTrafficMirrorTargetRead(ctx context.Context, d *schema.ResourceData ownerID := aws.ToString(target.OwnerId) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, - Service: "ec2", + Service: names.EC2, Region: meta.(*conns.AWSClient).Region, AccountID: ownerID, Resource: fmt.Sprintf("traffic-mirror-target/%s", d.Id()), @@ -158,7 +158,7 @@ func resourceTrafficMirrorTargetRead(ctx context.Context, d *schema.ResourceData d.Set("network_load_balancer_arn", target.NetworkLoadBalancerArn) d.Set(names.AttrOwnerID, ownerID) - setTagsOutV2(ctx, target.Tags) + setTagsOut(ctx, target.Tags) return diags } diff --git a/internal/service/ec2/vpc_vpcs_data_source.go b/internal/service/ec2/vpc_vpcs_data_source.go index 6635699245e..0066c7f6811 100644 --- a/internal/service/ec2/vpc_vpcs_data_source.go +++ b/internal/service/ec2/vpc_vpcs_data_source.go @@ -7,8 +7,8 @@ import ( "context" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "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 +17,8 @@ import ( "github.com/hashicorp/terraform-provider-aws/names" ) -// @SDKDataSource("aws_vpcs") -func DataSourceVPCs() *schema.Resource { +// @SDKDataSource("aws_vpcs", name="VPCs") +func dataSourceVPCs() *schema.Resource { return &schema.Resource{ ReadWithoutTimeout: dataSourceVPCsRead, @@ -40,7 +40,7 @@ func DataSourceVPCs() *schema.Resource { func dataSourceVPCsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics - conn := meta.(*conns.AWSClient).EC2Conn(ctx) + conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeVpcsInput{} @@ -59,7 +59,7 @@ func dataSourceVPCsRead(ctx context.Context, d *schema.ResourceData, meta interf input.Filters = nil } - output, err := FindVPCs(ctx, conn, input) + output, err := findVPCs(ctx, conn, input) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 VPCs: %s", err) @@ -68,7 +68,7 @@ func dataSourceVPCsRead(ctx context.Context, d *schema.ResourceData, meta interf var vpcIDs []string for _, v := range output { - vpcIDs = append(vpcIDs, aws.StringValue(v.VpcId)) + vpcIDs = append(vpcIDs, aws.ToString(v.VpcId)) } d.SetId(meta.(*conns.AWSClient).Region) diff --git a/internal/service/ec2/vpnclient_authorization_rule.go b/internal/service/ec2/vpnclient_authorization_rule.go index 3e7e4630c67..5032ed8d476 100644 --- a/internal/service/ec2/vpnclient_authorization_rule.go +++ b/internal/service/ec2/vpnclient_authorization_rule.go @@ -100,7 +100,7 @@ func resourceClientVPNAuthorizationRuleCreate(ctx context.Context, d *schema.Res input.Description = aws.String(v.(string)) } - id := ClientVPNAuthorizationRuleCreateResourceID(endpointID, targetNetworkCIDR, accessGroupID) + id := clientVPNAuthorizationRuleCreateResourceID(endpointID, targetNetworkCIDR, accessGroupID) _, err := conn.AuthorizeClientVpnIngress(ctx, input) if err != nil { @@ -120,7 +120,7 @@ func resourceClientVPNAuthorizationRuleRead(ctx context.Context, d *schema.Resou var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - endpointID, targetNetworkCIDR, accessGroupID, err := ClientVPNAuthorizationRuleParseResourceID(d.Id()) + endpointID, targetNetworkCIDR, accessGroupID, err := clientVPNAuthorizationRuleParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -150,7 +150,7 @@ func resourceClientVPNAuthorizationRuleDelete(ctx context.Context, d *schema.Res var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - endpointID, targetNetworkCIDR, accessGroupID, err := ClientVPNAuthorizationRuleParseResourceID(d.Id()) + endpointID, targetNetworkCIDR, accessGroupID, err := clientVPNAuthorizationRuleParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -176,7 +176,7 @@ func resourceClientVPNAuthorizationRuleDelete(ctx context.Context, d *schema.Res } if _, err := waitClientVPNAuthorizationRuleDeleted(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID, d.Timeout(schema.TimeoutDelete)); err != nil { - return sdkdiag.AppendErrorf(diags, "deleting EC2 Client VPN Authorization Rule (%s): waiting for completion: %s", d.Id(), err) + return sdkdiag.AppendErrorf(diags, "waiting for EC2 Client VPN Authorization Rule (%s) delete: %s", d.Id(), err) } return diags @@ -184,7 +184,7 @@ func resourceClientVPNAuthorizationRuleDelete(ctx context.Context, d *schema.Res const clientVPNAuthorizationRuleIDSeparator = "," -func ClientVPNAuthorizationRuleCreateResourceID(endpointID, targetNetworkCIDR, accessGroupID string) string { +func clientVPNAuthorizationRuleCreateResourceID(endpointID, targetNetworkCIDR, accessGroupID string) string { parts := []string{endpointID, targetNetworkCIDR} if accessGroupID != "" { parts = append(parts, accessGroupID) @@ -194,7 +194,7 @@ func ClientVPNAuthorizationRuleCreateResourceID(endpointID, targetNetworkCIDR, a return id } -func ClientVPNAuthorizationRuleParseResourceID(id string) (string, string, string, error) { +func clientVPNAuthorizationRuleParseResourceID(id string) (string, string, string, error) { parts := strings.Split(id, clientVPNAuthorizationRuleIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/vpnclient_authorization_rule_test.go b/internal/service/ec2/vpnclient_authorization_rule_test.go index 02c312613fd..af2c5b904b6 100644 --- a/internal/service/ec2/vpnclient_authorization_rule_test.go +++ b/internal/service/ec2/vpnclient_authorization_rule_test.go @@ -251,12 +251,7 @@ func testAccCheckClientVPNAuthorizationRuleDestroy(ctx context.Context) resource continue } - endpointID, targetNetworkCIDR, accessGroupID, err := tfec2.ClientVPNAuthorizationRuleParseResourceID(rs.Primary.ID) - if err != nil { - return err - } - - _, err = tfec2.FindClientVPNAuthorizationRuleByThreePartKey(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID) + _, err := tfec2.FindClientVPNAuthorizationRuleByThreePartKey(ctx, conn, rs.Primary.Attributes["client_vpn_endpoint_id"], rs.Primary.Attributes["target_network_cidr"], rs.Primary.Attributes["access_group_id"]) if tfresource.NotFound(err) { continue @@ -280,14 +275,9 @@ func testAccCheckClientVPNAuthorizationRuleExists(ctx context.Context, name stri return fmt.Errorf("Not found: %s", name) } - endpointID, targetNetworkCIDR, accessGroupID, err := tfec2.ClientVPNAuthorizationRuleParseResourceID(rs.Primary.ID) - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindClientVPNAuthorizationRuleByThreePartKey(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID) + output, err := tfec2.FindClientVPNAuthorizationRuleByThreePartKey(ctx, conn, rs.Primary.Attributes["client_vpn_endpoint_id"], rs.Primary.Attributes["target_network_cidr"], rs.Primary.Attributes["access_group_id"]) if err != nil { return err diff --git a/internal/service/ec2/vpnclient_endpoint.go b/internal/service/ec2/vpnclient_endpoint.go index 32c106240a1..52a49d01535 100644 --- a/internal/service/ec2/vpnclient_endpoint.go +++ b/internal/service/ec2/vpnclient_endpoint.go @@ -240,7 +240,7 @@ func resourceClientVPNEndpointCreate(ctx context.Context, d *schema.ResourceData ClientToken: aws.String(id.UniqueId()), ServerCertificateArn: aws.String(d.Get("server_certificate_arn").(string)), SplitTunnel: aws.Bool(d.Get("split_tunnel").(bool)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeClientVpnEndpoint), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeClientVpnEndpoint), TransportProtocol: awstypes.TransportProtocol(d.Get("transport_protocol").(string)), VpnPort: aws.Int32(int32(d.Get("vpn_port").(int))), } @@ -362,7 +362,7 @@ func resourceClientVPNEndpointRead(ctx context.Context, d *schema.ResourceData, d.Set(names.AttrVPCID, ep.VpcId) d.Set("vpn_port", ep.VpnPort) - setTagsOutV2(ctx, ep.Tags) + setTagsOut(ctx, ep.Tags) return diags } @@ -448,7 +448,7 @@ func resourceClientVPNEndpointUpdate(ctx context.Context, d *schema.ResourceData } if waitForClientConnectResponseOptionsUpdate { - if _, err := waitClientVPNEndpointClientConnectResponseOptionsUpdated(ctx, conn, d.Id()); err != nil { + if _, err := waitClientVPNEndpointClientConnectResponseOptionsUpdated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Client VPN Endpoint (%s) ClientConnectResponseOptions update: %s", d.Id(), err) } } @@ -474,7 +474,7 @@ func resourceClientVPNEndpointDelete(ctx context.Context, d *schema.ResourceData return sdkdiag.AppendErrorf(diags, "deleting EC2 Client VPN Endpoint (%s): %s", d.Id(), err) } - if _, err := waitClientVPNEndpointDeleted(ctx, conn, d.Id()); err != nil { + if _, err := waitClientVPNEndpointDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Client VPN Endpoint (%s) delete: %s", d.Id(), err) } diff --git a/internal/service/ec2/vpnclient_endpoint_data_source.go b/internal/service/ec2/vpnclient_endpoint_data_source.go index fe0b5692134..9ca982684ec 100644 --- a/internal/service/ec2/vpnclient_endpoint_data_source.go +++ b/internal/service/ec2/vpnclient_endpoint_data_source.go @@ -192,11 +192,11 @@ func dataSourceClientVPNEndpointRead(ctx context.Context, d *schema.ResourceData input.ClientVpnEndpointIds = []string{v.(string)} } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) @@ -262,7 +262,7 @@ func dataSourceClientVPNEndpointRead(ctx context.Context, d *schema.ResourceData d.Set(names.AttrVPCID, ep.VpcId) d.Set("vpn_port", ep.VpnPort) - setTagsOutV2(ctx, ep.Tags) + setTagsOut(ctx, ep.Tags) return diags } diff --git a/internal/service/ec2/vpnclient_route.go b/internal/service/ec2/vpnclient_route.go index b7d53481ac6..3665992ea9a 100644 --- a/internal/service/ec2/vpnclient_route.go +++ b/internal/service/ec2/vpnclient_route.go @@ -80,7 +80,7 @@ func resourceClientVPNRouteCreate(ctx context.Context, d *schema.ResourceData, m endpointID := d.Get("client_vpn_endpoint_id").(string) targetSubnetID := d.Get("target_vpc_subnet_id").(string) destinationCIDR := d.Get("destination_cidr_block").(string) - id := ClientVPNRouteCreateResourceID(endpointID, targetSubnetID, destinationCIDR) + id := clientVPNRouteCreateResourceID(endpointID, targetSubnetID, destinationCIDR) input := &ec2.CreateClientVpnRouteInput{ ClientToken: aws.String(sdkid.UniqueId()), ClientVpnEndpointId: aws.String(endpointID), @@ -113,7 +113,7 @@ func resourceClientVPNRouteRead(ctx context.Context, d *schema.ResourceData, met var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - endpointID, targetSubnetID, destinationCIDR, err := ClientVPNRouteParseResourceID(d.Id()) + endpointID, targetSubnetID, destinationCIDR, err := clientVPNRouteParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -144,7 +144,7 @@ func resourceClientVPNRouteDelete(ctx context.Context, d *schema.ResourceData, m var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - endpointID, targetSubnetID, destinationCIDR, err := ClientVPNRouteParseResourceID(d.Id()) + endpointID, targetSubnetID, destinationCIDR, err := clientVPNRouteParseResourceID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) } @@ -173,14 +173,14 @@ func resourceClientVPNRouteDelete(ctx context.Context, d *schema.ResourceData, m const clientVPNRouteIDSeparator = "," -func ClientVPNRouteCreateResourceID(endpointID, targetSubnetID, destinationCIDR string) string { +func clientVPNRouteCreateResourceID(endpointID, targetSubnetID, destinationCIDR string) string { parts := []string{endpointID, targetSubnetID, destinationCIDR} id := strings.Join(parts, clientVPNRouteIDSeparator) return id } -func ClientVPNRouteParseResourceID(id string) (string, string, string, error) { +func clientVPNRouteParseResourceID(id string) (string, string, string, error) { parts := strings.Split(id, clientVPNRouteIDSeparator) if len(parts) == 3 && parts[0] != "" && parts[1] != "" && parts[2] != "" { diff --git a/internal/service/ec2/vpnclient_route_test.go b/internal/service/ec2/vpnclient_route_test.go index 3a77a1ce348..4d2b808a57e 100644 --- a/internal/service/ec2/vpnclient_route_test.go +++ b/internal/service/ec2/vpnclient_route_test.go @@ -125,12 +125,7 @@ func testAccCheckClientVPNRouteDestroy(ctx context.Context) resource.TestCheckFu continue } - endpointID, targetSubnetID, destinationCIDR, err := tfec2.ClientVPNRouteParseResourceID(rs.Primary.ID) - if err != nil { - return err - } - - _, err = tfec2.FindClientVPNRouteByThreePartKey(ctx, conn, endpointID, targetSubnetID, destinationCIDR) + _, err := tfec2.FindClientVPNRouteByThreePartKey(ctx, conn, rs.Primary.Attributes["client_vpn_endpoint_id"], rs.Primary.Attributes["target_vpc_subnet_id"], rs.Primary.Attributes["destination_cidr_block"]) if tfresource.NotFound(err) { continue @@ -154,14 +149,9 @@ func testAccCheckClientVPNRouteExists(ctx context.Context, name string, v *awsty return fmt.Errorf("Not found: %s", name) } - endpointID, targetSubnetID, destinationCIDR, err := tfec2.ClientVPNRouteParseResourceID(rs.Primary.ID) - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - output, err := tfec2.FindClientVPNRouteByThreePartKey(ctx, conn, endpointID, targetSubnetID, destinationCIDR) + output, err := tfec2.FindClientVPNRouteByThreePartKey(ctx, conn, rs.Primary.Attributes["client_vpn_endpoint_id"], rs.Primary.Attributes["target_vpc_subnet_id"], rs.Primary.Attributes["destination_cidr_block"]) if err != nil { return err diff --git a/internal/service/ec2/vpnsite_connection.go b/internal/service/ec2/vpnsite_connection.go index 4f40616f311..88b19dd6a3c 100644 --- a/internal/service/ec2/vpnsite_connection.go +++ b/internal/service/ec2/vpnsite_connection.go @@ -684,7 +684,7 @@ func resourceVPNConnectionCreate(ctx context.Context, d *schema.ResourceData, me input := &ec2.CreateVpnConnectionInput{ CustomerGatewayId: aws.String(d.Get("customer_gateway_id").(string)), Options: expandVPNConnectionOptionsSpecification(d), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeVpnConnection), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVpnConnection), Type: aws.String(d.Get(names.AttrType).(string)), } @@ -744,7 +744,7 @@ func resourceVPNConnectionRead(ctx context.Context, d *schema.ResourceData, meta if v := vpnConnection.TransitGatewayId; v != nil { input := &ec2.DescribeTransitGatewayAttachmentsInput{ - Filters: newAttributeFilterListV2(map[string]string{ + Filters: newAttributeFilterList(map[string]string{ "resource-id": d.Id(), "resource-type": string(awstypes.TransitGatewayAttachmentResourceTypeVpn), "transit-gateway-id": aws.ToString(v), @@ -772,7 +772,7 @@ func resourceVPNConnectionRead(ctx context.Context, d *schema.ResourceData, meta return sdkdiag.AppendErrorf(diags, "setting vgw_telemetry: %s", err) } - setTagsOutV2(ctx, vpnConnection.Tags) + setTagsOut(ctx, vpnConnection.Tags) if v := vpnConnection.Options; v != nil { d.Set("enable_acceleration", v.EnableAcceleration) @@ -806,7 +806,7 @@ func resourceVPNConnectionRead(ctx context.Context, d *schema.ResourceData, meta d.Set("customer_gateway_configuration", vpnConnection.CustomerGatewayConfiguration) - tunnelInfo, err := CustomerGatewayConfigurationToTunnelInfo( + tunnelInfo, err := customerGatewayConfigurationToTunnelInfo( aws.ToString(vpnConnection.CustomerGatewayConfiguration), d.Get("tunnel1_preshared_key").(string), // Not currently available during import d.Get("tunnel1_inside_cidr").(string), @@ -1537,11 +1537,11 @@ func flattenVGWTelemetries(apiObjects []awstypes.VgwTelemetry) []interface{} { return tfList } -type XmlVpnConnectionConfig struct { - Tunnels []XmlIpsecTunnel `xml:"ipsec_tunnel"` +type xmlVpnConnectionConfig struct { + Tunnels []xmlIpsecTunnel `xml:"ipsec_tunnel"` } -type XmlIpsecTunnel struct { +type xmlIpsecTunnel struct { BGPASN string `xml:"vpn_gateway>bgp>asn"` BGPHoldTime int `xml:"vpn_gateway>bgp>hold_time"` CgwInsideAddress string `xml:"customer_gateway>tunnel_inside_address>ip_address"` @@ -1550,7 +1550,7 @@ type XmlIpsecTunnel struct { VgwInsideAddress string `xml:"vpn_gateway>tunnel_inside_address>ip_address"` } -type TunnelInfo struct { +type tunnelInfo struct { Tunnel1Address string Tunnel1BGPASN string Tunnel1BGPHoldTime int @@ -1565,23 +1565,23 @@ type TunnelInfo struct { Tunnel2VgwInsideAddress string } -func (slice XmlVpnConnectionConfig) Len() int { +func (slice xmlVpnConnectionConfig) Len() int { return len(slice.Tunnels) } -func (slice XmlVpnConnectionConfig) Less(i, j int) bool { +func (slice xmlVpnConnectionConfig) Less(i, j int) bool { return slice.Tunnels[i].OutsideAddress < slice.Tunnels[j].OutsideAddress } -func (slice XmlVpnConnectionConfig) Swap(i, j int) { +func (slice xmlVpnConnectionConfig) Swap(i, j int) { slice.Tunnels[i], slice.Tunnels[j] = slice.Tunnels[j], slice.Tunnels[i] } -// CustomerGatewayConfigurationToTunnelInfo converts the configuration information for the -// VPN connection's customer gateway (in the native XML format) to a TunnelInfo structure. +// customerGatewayConfigurationToTunnelInfo converts the configuration information for the +// VPN connection's customer gateway (in the native XML format) to a tunnelInfo structure. // The tunnel1 parameters are optionally used to correctly order tunnel configurations. -func CustomerGatewayConfigurationToTunnelInfo(xmlConfig string, tunnel1PreSharedKey string, tunnel1InsideCidr string, tunnel1InsideIpv6Cidr string) (*TunnelInfo, error) { - var vpnConfig XmlVpnConnectionConfig +func customerGatewayConfigurationToTunnelInfo(xmlConfig string, tunnel1PreSharedKey string, tunnel1InsideCidr string, tunnel1InsideIpv6Cidr string) (*tunnelInfo, error) { + var vpnConfig xmlVpnConnectionConfig if err := xml.Unmarshal([]byte(xmlConfig), &vpnConfig); err != nil { return nil, err @@ -1619,7 +1619,7 @@ func CustomerGatewayConfigurationToTunnelInfo(xmlConfig string, tunnel1PreShared sort.Sort(vpnConfig) } - tunnelInfo := &TunnelInfo{ + tunnelInfo := &tunnelInfo{ Tunnel1Address: vpnConfig.Tunnels[0].OutsideAddress, Tunnel1BGPASN: vpnConfig.Tunnels[0].BGPASN, Tunnel1BGPHoldTime: vpnConfig.Tunnels[0].BGPHoldTime, @@ -1674,7 +1674,7 @@ func validVPNConnectionTunnelInsideIPv6CIDR() schema.SchemaValidateFunc { // customizeDiffValidateOutsideIPAddressType validates that if provided `outside_ip_address_type` is `PrivateIpv4` then `transport_transit_gateway_attachment_id` must be provided func customizeDiffValidateOutsideIPAddressType(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { - if v, ok := diff.GetOk("outside_ip_address_type"); !ok || v.(string) == OutsideIPAddressTypePublicIPv4 { + if v, ok := diff.GetOk("outside_ip_address_type"); !ok || v.(string) == outsideIPAddressTypePublicIPv4 { return nil } diff --git a/internal/service/ec2/vpnsite_connection_route.go b/internal/service/ec2/vpnsite_connection_route.go index 8b62ac534c2..b354015e75f 100644 --- a/internal/service/ec2/vpnsite_connection_route.go +++ b/internal/service/ec2/vpnsite_connection_route.go @@ -47,13 +47,12 @@ func resourceVPNConnectionRouteCreate(ctx context.Context, d *schema.ResourceDat cidrBlock := d.Get("destination_cidr_block").(string) vpnConnectionID := d.Get("vpn_connection_id").(string) - id := VPNConnectionRouteCreateResourceID(cidrBlock, vpnConnectionID) + id := vpnConnectionRouteCreateResourceID(cidrBlock, vpnConnectionID) input := &ec2.CreateVpnConnectionRouteInput{ DestinationCidrBlock: aws.String(cidrBlock), VpnConnectionId: aws.String(vpnConnectionID), } - log.Printf("[DEBUG] Creating EC2 VPN Connection Route: %s", id) _, err := conn.CreateVpnConnectionRoute(ctx, input) if err != nil { @@ -73,10 +72,9 @@ func resourceVPNConnectionRouteRead(ctx context.Context, d *schema.ResourceData, var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - cidrBlock, vpnConnectionID, err := VPNConnectionRouteParseResourceID(d.Id()) - + cidrBlock, vpnConnectionID, err := vpnConnectionRouteParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "reading EC2 VPN Connection Route (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } _, err = findVPNConnectionRouteByTwoPartKey(ctx, conn, vpnConnectionID, cidrBlock) @@ -101,10 +99,9 @@ func resourceVPNConnectionRouteDelete(ctx context.Context, d *schema.ResourceDat var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - cidrBlock, vpnConnectionID, err := VPNConnectionRouteParseResourceID(d.Id()) - + cidrBlock, vpnConnectionID, err := vpnConnectionRouteParseResourceID(d.Id()) if err != nil { - return sdkdiag.AppendErrorf(diags, "deleting EC2 VPN Connection Route (%s): %s", d.Id(), err) + return sdkdiag.AppendFromErr(diags, err) } log.Printf("[INFO] Deleting EC2 VPN Connection Route: %s", d.Id()) @@ -130,14 +127,14 @@ func resourceVPNConnectionRouteDelete(ctx context.Context, d *schema.ResourceDat const vpnConnectionRouteResourceIDSeparator = ":" -func VPNConnectionRouteCreateResourceID(cidrBlock, vpcConnectionID string) string { +func vpnConnectionRouteCreateResourceID(cidrBlock, vpcConnectionID string) string { parts := []string{cidrBlock, vpcConnectionID} id := strings.Join(parts, vpnConnectionRouteResourceIDSeparator) return id } -func VPNConnectionRouteParseResourceID(id string) (string, string, error) { +func vpnConnectionRouteParseResourceID(id string) (string, string, error) { parts := strings.Split(id, vpnConnectionRouteResourceIDSeparator) if len(parts) == 2 && parts[0] != "" && parts[1] != "" { diff --git a/internal/service/ec2/vpnsite_connection_route_test.go b/internal/service/ec2/vpnsite_connection_route_test.go index c1fbe5b8742..9c930a54490 100644 --- a/internal/service/ec2/vpnsite_connection_route_test.go +++ b/internal/service/ec2/vpnsite_connection_route_test.go @@ -73,13 +73,7 @@ func testAccCheckVPNConnectionRouteDestroy(ctx context.Context) resource.TestChe continue } - cidrBlock, vpnConnectionID, err := tfec2.VPNConnectionRouteParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - - _, err = tfec2.FindVPNConnectionRouteByTwoPartKey(ctx, conn, vpnConnectionID, cidrBlock) + _, err := tfec2.FindVPNConnectionRouteByTwoPartKey(ctx, conn, rs.Primary.Attributes["vpn_connection_id"], rs.Primary.Attributes["destination_cidr_block"]) if tfresource.NotFound(err) { continue @@ -103,19 +97,9 @@ func testAccVPNConnectionRouteExists(ctx context.Context, n string) resource.Tes return fmt.Errorf("Not found: %s", n) } - if rs.Primary.ID == "" { - return fmt.Errorf("No EC2 VPN Connection Route ID is set") - } - - cidrBlock, vpnConnectionID, err := tfec2.VPNConnectionRouteParseResourceID(rs.Primary.ID) - - if err != nil { - return err - } - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) - _, err = tfec2.FindVPNConnectionRouteByTwoPartKey(ctx, conn, vpnConnectionID, cidrBlock) + _, err := tfec2.FindVPNConnectionRouteByTwoPartKey(ctx, conn, rs.Primary.Attributes["vpn_connection_id"], rs.Primary.Attributes["destination_cidr_block"]) return err } diff --git a/internal/service/ec2/vpnsite_customer_gateway.go b/internal/service/ec2/vpnsite_customer_gateway.go index 6341977c9b0..fa1e7262d42 100644 --- a/internal/service/ec2/vpnsite_customer_gateway.go +++ b/internal/service/ec2/vpnsite_customer_gateway.go @@ -96,7 +96,7 @@ func resourceCustomerGatewayCreate(ctx context.Context, d *schema.ResourceData, conn := meta.(*conns.AWSClient).EC2Client(ctx) input := &ec2.CreateCustomerGatewayInput{ - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeCustomerGateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeCustomerGateway), Type: awstypes.GatewayType(d.Get(names.AttrType).(string)), } @@ -178,7 +178,7 @@ func resourceCustomerGatewayRead(ctx context.Context, d *schema.ResourceData, me d.Set(names.AttrIPAddress, customerGateway.IpAddress) d.Set(names.AttrType, customerGateway.Type) - setTagsOutV2(ctx, customerGateway.Tags) + setTagsOut(ctx, customerGateway.Tags) return diags } diff --git a/internal/service/ec2/vpnsite_customer_gateway_data_source.go b/internal/service/ec2/vpnsite_customer_gateway_data_source.go index f6bd0c0178a..8039df3803b 100644 --- a/internal/service/ec2/vpnsite_customer_gateway_data_source.go +++ b/internal/service/ec2/vpnsite_customer_gateway_data_source.go @@ -79,7 +79,7 @@ func dataSourceCustomerGatewayRead(ctx context.Context, d *schema.ResourceData, input := &ec2.DescribeCustomerGatewaysInput{} if v, ok := d.GetOk(names.AttrFilter); ok { - input.Filters = newCustomFilterListV2(v.(*schema.Set)) + input.Filters = newCustomFilterList(v.(*schema.Set)) } if v, ok := d.GetOk(names.AttrID); ok { @@ -129,7 +129,7 @@ func dataSourceCustomerGatewayRead(ctx context.Context, d *schema.ResourceData, d.Set(names.AttrIPAddress, cgw.IpAddress) d.Set(names.AttrType, cgw.Type) - setTagsOutV2(ctx, cgw.Tags) + setTagsOut(ctx, cgw.Tags) return diags } diff --git a/internal/service/ec2/vpnsite_gateway.go b/internal/service/ec2/vpnsite_gateway.go index b8a07f3ac84..fc115d4a0e2 100644 --- a/internal/service/ec2/vpnsite_gateway.go +++ b/internal/service/ec2/vpnsite_gateway.go @@ -75,7 +75,7 @@ func resourceVPNGatewayCreate(ctx context.Context, d *schema.ResourceData, meta input := &ec2.CreateVpnGatewayInput{ AvailabilityZone: aws.String(d.Get(names.AttrAvailabilityZone).(string)), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeVpnGateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeVpnGateway), Type: awstypes.GatewayTypeIpsec1, } @@ -143,7 +143,7 @@ func resourceVPNGatewayRead(ctx context.Context, d *schema.ResourceData, meta in } } - setTagsOutV2(ctx, vpnGateway.Tags) + setTagsOut(ctx, vpnGateway.Tags) return diags } diff --git a/internal/service/ec2/vpnsite_gateway_attachment.go b/internal/service/ec2/vpnsite_gateway_attachment.go index 7410b95adbc..983bc47cd7d 100644 --- a/internal/service/ec2/vpnsite_gateway_attachment.go +++ b/internal/service/ec2/vpnsite_gateway_attachment.go @@ -58,7 +58,7 @@ func resourceVPNGatewayAttachmentCreate(ctx context.Context, d *schema.ResourceD return sdkdiag.AppendErrorf(diags, "creating EC2 VPN Gateway (%s) Attachment (%s): %s", vpnGatewayID, vpcID, err) } - d.SetId(VPNGatewayVPCAttachmentCreateID(vpnGatewayID, vpcID)) + d.SetId(vpnGatewayVPCAttachmentCreateID(vpnGatewayID, vpcID)) _, err = waitVPNGatewayVPCAttachmentAttached(ctx, conn, vpnGatewayID, vpcID) diff --git a/internal/service/ec2/vpnsite_gateway_data_source.go b/internal/service/ec2/vpnsite_gateway_data_source.go index 7ce1607840d..7967a37cf33 100644 --- a/internal/service/ec2/vpnsite_gateway_data_source.go +++ b/internal/service/ec2/vpnsite_gateway_data_source.go @@ -79,31 +79,31 @@ func dataSourceVPNGatewayRead(ctx context.Context, d *schema.ResourceData, meta input.VpnGatewayIds = []string{id.(string)} } - input.Filters = newAttributeFilterListV2( + input.Filters = newAttributeFilterList( map[string]string{ names.AttrState: d.Get(names.AttrState).(string), "availability-zone": d.Get(names.AttrAvailabilityZone).(string), }, ) if asn, ok := d.GetOk("amazon_side_asn"); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2( + input.Filters = append(input.Filters, newAttributeFilterList( map[string]string{ "amazon-side-asn": asn.(string), }, )...) } if id, ok := d.GetOk("attached_vpc_id"); ok { - input.Filters = append(input.Filters, newAttributeFilterListV2( + input.Filters = append(input.Filters, newAttributeFilterList( map[string]string{ "attachment.state": "attached", "attachment.vpc-id": id.(string), }, )...) } - input.Filters = append(input.Filters, newTagFilterListV2( - TagsV2(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), + input.Filters = append(input.Filters, newTagFilterList( + Tags(tftags.New(ctx, d.Get(names.AttrTags).(map[string]interface{}))), )...) - input.Filters = append(input.Filters, newCustomFilterListV2( + input.Filters = append(input.Filters, newCustomFilterList( d.Get(names.AttrFilter).(*schema.Set), )...) if len(input.Filters) == 0 { @@ -137,7 +137,7 @@ func dataSourceVPNGatewayRead(ctx context.Context, d *schema.ResourceData, meta d.Set(names.AttrAvailabilityZone, vgw.AvailabilityZone) d.Set(names.AttrState, vgw.State) - setTagsOutV2(ctx, vgw.Tags) + setTagsOut(ctx, vgw.Tags) return diags } diff --git a/internal/service/ec2/vpnsite_gateway_route_propagation.go b/internal/service/ec2/vpnsite_gateway_route_propagation.go index e6b62a7c3f6..bc5cc22473d 100644 --- a/internal/service/ec2/vpnsite_gateway_route_propagation.go +++ b/internal/service/ec2/vpnsite_gateway_route_propagation.go @@ -55,7 +55,7 @@ func resourceVPNGatewayRoutePropagationEnable(ctx context.Context, d *schema.Res return sdkdiag.AppendFromErr(diags, err) } - d.SetId(VPNGatewayRoutePropagationCreateID(routeTableID, gatewayID)) + d.SetId(vpnGatewayRoutePropagationCreateID(routeTableID, gatewayID)) return append(diags, resourceVPNGatewayRoutePropagationRead(ctx, d, meta)...) } @@ -64,7 +64,7 @@ func resourceVPNGatewayRoutePropagationDisable(ctx context.Context, d *schema.Re var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - routeTableID, gatewayID, err := VPNGatewayRoutePropagationParseID(d.Id()) + routeTableID, gatewayID, err := vpnGatewayRoutePropagationParseID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) @@ -83,7 +83,7 @@ func resourceVPNGatewayRoutePropagationRead(ctx context.Context, d *schema.Resou var diags diag.Diagnostics conn := meta.(*conns.AWSClient).EC2Client(ctx) - routeTableID, gatewayID, err := VPNGatewayRoutePropagationParseID(d.Id()) + routeTableID, gatewayID, err := vpnGatewayRoutePropagationParseID(d.Id()) if err != nil { return sdkdiag.AppendFromErr(diags, err) diff --git a/internal/service/ec2/vpnsite_gateway_test.go b/internal/service/ec2/vpnsite_gateway_test.go index adc725b30c5..ad558952f79 100644 --- a/internal/service/ec2/vpnsite_gateway_test.go +++ b/internal/service/ec2/vpnsite_gateway_test.go @@ -208,8 +208,8 @@ func TestAccSiteVPNGateway_reattach(t *testing.T) { { Config: testAccSiteVPNGatewayConfig_reattach(rName), Check: resource.ComposeTestCheckFunc( - acctest.CheckVPCExistsV2(ctx, vpcResourceName1, &vpc1), - acctest.CheckVPCExistsV2(ctx, vpcResourceName2, &vpc2), + acctest.CheckVPCExists(ctx, vpcResourceName1, &vpc1), + acctest.CheckVPCExists(ctx, vpcResourceName2, &vpc2), testAccCheckVPNGatewayExists(ctx, resourceName1, &vgw1), testAccCheckVPNGatewayExists(ctx, resourceName2, &vgw2), testAttachmentFunc(&vgw1, &vpc1), diff --git a/internal/service/ec2/wait.go b/internal/service/ec2/wait.go index 5f3d34b1e2f..d9323cda4c1 100644 --- a/internal/service/ec2/wait.go +++ b/internal/service/ec2/wait.go @@ -10,115 +10,2526 @@ import ( "strconv" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-provider-aws/internal/enum" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -// -// Move functions to waitv2.go as they are migrated to AWS SDK for Go v2. -// +const ( + availabilityZoneGroupOptInStatusTimeout = 10 * time.Minute + ebsSnapshotArchivedTimeout = 60 * time.Minute + ec2PropagationTimeout = 5 * time.Minute // nosemgrep:ci.ec2-in-const-name, ci.ec2-in-var-name + iamPropagationTimeout = 2 * time.Minute + instanceReadyTimeout = 10 * time.Minute + instanceStartTimeout = 10 * time.Minute + instanceStopTimeout = 10 * time.Minute + internetGatewayNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. + managedPrefixListEntryCreateTimeout = 5 * time.Minute + managedPrefixListTimeout = 15 * time.Minute + networkInterfaceAttachedTimeout = 5 * time.Minute + networkInterfaceDetachedTimeout = 10 * time.Minute + placementGroupCreatedTimeout = 5 * time.Minute + placementGroupDeletedTimeout = 5 * time.Minute + routeNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. + routeTableNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. + routeTableAssociationCreatedNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. + securityGroupNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. + subnetIPv6CIDRBlockAssociationCreatedTimeout = 3 * time.Minute + subnetIPv6CIDRBlockAssociationDeletedTimeout = 3 * time.Minute + transitGatewayPeeringAttachmentCreatedTimeout = 10 * time.Minute + transitGatewayPeeringAttachmentDeletedTimeout = 10 * time.Minute + transitGatewayPeeringAttachmentUpdatedTimeout = 10 * time.Minute + transitGatewayPolicyTableAssociationCreatedTimeout = 5 * time.Minute + transitGatewayPolicyTableAssociationDeletedTimeout = 10 * time.Minute + transitGatewayRouteTableAssociationCreatedTimeout = 5 * time.Minute + transitGatewayRouteTableAssociationDeletedTimeout = 10 * time.Minute + transitGatewayPrefixListReferenceTimeout = 5 * time.Minute + transitGatewayRouteCreatedTimeout = 2 * time.Minute + transitGatewayRouteDeletedTimeout = 2 * time.Minute + transitGatewayRouteTableCreatedTimeout = 10 * time.Minute + transitGatewayRouteTableDeletedTimeout = 10 * time.Minute + transitGatewayPolicyTableCreatedTimeout = 10 * time.Minute + transitGatewayPolicyTableDeletedTimeout = 10 * time.Minute + transitGatewayRouteTablePropagationCreatedTimeout = 5 * time.Minute + transitGatewayRouteTablePropagationDeletedTimeout = 5 * time.Minute + transitGatewayVPCAttachmentCreatedTimeout = 10 * time.Minute + transitGatewayVPCAttachmentDeletedTimeout = 10 * time.Minute + transitGatewayVPCAttachmentUpdatedTimeout = 10 * time.Minute + vpcCreatedTimeout = 10 * time.Minute + vpcIPv6CIDRBlockAssociationCreatedTimeout = 10 * time.Minute + vpcIPv6CIDRBlockAssociationDeletedTimeout = 5 * time.Minute +) + +func waitAvailabilityZoneGroupNotOptedIn(ctx context.Context, conn *ec2.Client, name string) (*awstypes.AvailabilityZone, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AvailabilityZoneOptInStatusOptedIn), + Target: enum.Slice(awstypes.AvailabilityZoneOptInStatusNotOptedIn), + Refresh: statusAvailabilityZoneGroupOptInStatus(ctx, conn, name), + Timeout: availabilityZoneGroupOptInStatusTimeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.AvailabilityZone); ok { + return output, err + } + + return nil, err +} + +func waitAvailabilityZoneGroupOptedIn(ctx context.Context, conn *ec2.Client, name string) (*awstypes.AvailabilityZone, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AvailabilityZoneOptInStatusNotOptedIn), + Target: enum.Slice(awstypes.AvailabilityZoneOptInStatusOptedIn), + Refresh: statusAvailabilityZoneGroupOptInStatus(ctx, conn, name), + Timeout: availabilityZoneGroupOptInStatusTimeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.AvailabilityZone); ok { + return output, err + } + + return nil, err +} + +func waitCapacityReservationActive(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CapacityReservation, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.CapacityReservationStatePending), + Target: enum.Slice(awstypes.CapacityReservationStateActive), + Refresh: statusCapacityReservation(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CapacityReservation); ok { + return output, err + } + + return nil, err +} + +func waitCapacityReservationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CapacityReservation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.CapacityReservationStateActive), + Target: []string{}, + Refresh: statusCapacityReservation(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CapacityReservation); ok { + return output, err + } + + return nil, err +} + +func waitCapacityBlockReservationActive(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CapacityReservation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.CapacityReservationStatePaymentPending), + Target: enum.Slice(awstypes.CapacityReservationStateActive, awstypes.CapacityReservationStateScheduled), + Refresh: statusCapacityReservation(ctx, conn, id), + Timeout: timeout, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CapacityReservation); ok { + return output, err + } + + return nil, err +} + +func waitCarrierGatewayCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CarrierGateway, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.CarrierGatewayStatePending), + Target: enum.Slice(awstypes.CarrierGatewayStateAvailable), + Refresh: statusCarrierGateway(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CarrierGateway); ok { + return output, err + } + + return nil, err +} + +func waitCarrierGatewayDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CarrierGateway, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.CarrierGatewayStateDeleting), + Target: []string{}, + Refresh: statusCarrierGateway(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CarrierGateway); ok { + return output, err + } + + return nil, err +} + +func waitClientVPNAuthorizationRuleCreated(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string, timeout time.Duration) (*awstypes.AuthorizationRule, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ClientVpnAuthorizationRuleStatusCodeAuthorizing), + Target: enum.Slice(awstypes.ClientVpnAuthorizationRuleStatusCodeActive), + Refresh: statusClientVPNAuthorizationRule(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.AuthorizationRule); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNAuthorizationRuleDeleted(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string, timeout time.Duration) (*awstypes.AuthorizationRule, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ClientVpnAuthorizationRuleStatusCodeRevoking), + Target: []string{}, + Refresh: statusClientVPNAuthorizationRule(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.AuthorizationRule); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNEndpointClientConnectResponseOptionsUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.ClientConnectResponseOptions, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ClientVpnEndpointAttributeStatusCodeApplying), + Target: enum.Slice(awstypes.ClientVpnEndpointAttributeStatusCodeApplied), + Refresh: statusClientVPNEndpointClientConnectResponseOptions(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ClientConnectResponseOptions); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNEndpointDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.ClientVpnEndpoint, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ClientVpnEndpointStatusCodeDeleting), + Target: []string{}, + Refresh: statusClientVPNEndpoint(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ClientVpnEndpoint); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNNetworkAssociationCreated(ctx context.Context, conn *ec2.Client, associationID, endpointID string, timeout time.Duration) (*awstypes.TargetNetwork, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AssociationStatusCodeAssociating), + Target: enum.Slice(awstypes.AssociationStatusCodeAssociated), + Refresh: statusClientVPNNetworkAssociation(ctx, conn, associationID, endpointID), + Timeout: timeout, + Delay: 4 * time.Minute, + PollInterval: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TargetNetwork); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNNetworkAssociationDeleted(ctx context.Context, conn *ec2.Client, associationID, endpointID string, timeout time.Duration) (*awstypes.TargetNetwork, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AssociationStatusCodeDisassociating), + Target: []string{}, + Refresh: statusClientVPNNetworkAssociation(ctx, conn, associationID, endpointID), + Timeout: timeout, + Delay: 4 * time.Minute, + PollInterval: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TargetNetwork); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNRouteCreated(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string, timeout time.Duration) (*awstypes.ClientVpnRoute, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ClientVpnRouteStatusCodeCreating), + Target: enum.Slice(awstypes.ClientVpnRouteStatusCodeActive), + Refresh: statusClientVPNRoute(ctx, conn, endpointID, targetSubnetID, destinationCIDR), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ClientVpnRoute); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitClientVPNRouteDeleted(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string, timeout time.Duration) (*awstypes.ClientVpnRoute, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ClientVpnRouteStatusCodeActive, awstypes.ClientVpnRouteStatusCodeDeleting), + Target: []string{}, + Refresh: statusClientVPNRoute(ctx, conn, endpointID, targetSubnetID, destinationCIDR), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ClientVpnRoute); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + + return output, err + } + + return nil, err +} + +func waitCustomerGatewayCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CustomerGateway, error) { + const ( + timeout = 10 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(customerGatewayStatePending), + Target: enum.Slice(customerGatewayStateAvailable), + Refresh: statusCustomerGateway(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CustomerGateway); ok { + return output, err + } + + return nil, err +} + +func waitCustomerGatewayDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CustomerGateway, error) { + const ( + timeout = 5 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(customerGatewayStateAvailable, customerGatewayStateDeleting), + Target: []string{}, + Refresh: statusCustomerGateway(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.CustomerGateway); ok { + return output, err + } + + return nil, err +} + +func waitEBSSnapshotImportComplete(ctx context.Context, conn *ec2.Client, importTaskID string, timeout time.Duration) (*awstypes.SnapshotTaskDetail, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{ + ebsSnapshotImportStateActive, + ebsSnapshotImportStateUpdating, + ebsSnapshotImportStateValidating, + ebsSnapshotImportStateValidated, + ebsSnapshotImportStateConverting, + }, + Target: []string{ebsSnapshotImportStateCompleted}, + Refresh: statusEBSSnapshotImport(ctx, conn, importTaskID), + Timeout: timeout, + Delay: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SnapshotTaskDetail); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + + return output, err + } + + return nil, err +} + +func waitEBSSnapshotTierArchive(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SnapshotTierStatus, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(targetStorageTierStandard), + Target: enum.Slice(awstypes.TargetStorageTierArchive), + Refresh: statusSnapshotStorageTier(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SnapshotTierStatus); ok { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", string(output.LastTieringOperationStatus), aws.ToString(output.LastTieringOperationStatusDetail))) + + return output, err + } + + return nil, err +} + +func waitEIPDomainNameAttributeDeleted(ctx context.Context, conn *ec2.Client, allocationID string, timeout time.Duration) (*awstypes.AddressAttribute, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{ptrUpdateStatusPending}, + Target: []string{}, + Timeout: timeout, + Refresh: statusEIPDomainNameAttribute(ctx, conn, allocationID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.AddressAttribute); ok { + if v := output.PtrRecordUpdate; v != nil { + tfresource.SetLastError(err, errors.New(aws.ToString(v.Reason))) + } + + return output, err + } + + return nil, err +} + +func waitEIPDomainNameAttributeUpdated(ctx context.Context, conn *ec2.Client, allocationID string, timeout time.Duration) (*awstypes.AddressAttribute, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{ptrUpdateStatusPending}, + Target: []string{""}, + Timeout: timeout, + Refresh: statusEIPDomainNameAttribute(ctx, conn, allocationID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.AddressAttribute); ok { + if v := output.PtrRecordUpdate; v != nil { + tfresource.SetLastError(err, errors.New(aws.ToString(v.Reason))) + } + + return output, err + } + + return nil, err +} + +func waitFastSnapshotRestoreCreated(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string, timeout time.Duration) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.FastSnapshotRestoreStateCodeEnabling, awstypes.FastSnapshotRestoreStateCodeOptimizing), + Target: enum.Slice(awstypes.FastSnapshotRestoreStateCodeEnabled), + Refresh: statusFastSnapshotRestore(ctx, conn, availabilityZone, snapshotID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.DescribeFastSnapshotRestoreSuccessItem); ok { + return output, err + } + + return nil, err +} + +func waitFastSnapshotRestoreDeleted(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string, timeout time.Duration) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.FastSnapshotRestoreStateCodeDisabling, awstypes.FastSnapshotRestoreStateCodeOptimizing, awstypes.FastSnapshotRestoreStateCodeEnabled), + Target: []string{}, + Refresh: statusFastSnapshotRestore(ctx, conn, availabilityZone, snapshotID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.DescribeFastSnapshotRestoreSuccessItem); ok { + return output, err + } + + return nil, err +} + +func waitFleet(ctx context.Context, conn *ec2.Client, id string, pending, target []string, timeout, delay time.Duration) error { + stateConf := &retry.StateChangeConf{ + Pending: pending, + Target: target, + Refresh: statusFleet(ctx, conn, id), + Timeout: timeout, + Delay: delay, + MinTimeout: 1 * time.Second, + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitHostCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Host, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AllocationStatePending), + Target: enum.Slice(awstypes.AllocationStateAvailable), + Timeout: timeout, + Refresh: statusHost(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Host); ok { + return output, err + } + + return nil, err +} + +func waitHostDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Host, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AllocationStateAvailable), + Target: []string{}, + Timeout: timeout, + Refresh: statusHost(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Host); ok { + return output, err + } + + return nil, err +} + +func waitHostUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Host, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AllocationStatePending), + Target: enum.Slice(awstypes.AllocationStateAvailable), + Timeout: timeout, + Refresh: statusHost(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Host); ok { + return output, err + } + + return nil, err +} + +func waitImageAvailable(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Image, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ImageStatePending), + Target: enum.Slice(awstypes.ImageStateAvailable), + Refresh: statusImage(ctx, conn, id), + Timeout: timeout, + Delay: amiRetryDelay, + MinTimeout: amiRetryMinTimeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Image); ok { + if stateReason := output.StateReason; stateReason != nil { + tfresource.SetLastError(err, errors.New(aws.ToString(stateReason.Message))) + } + + return output, err + } + + return nil, err +} + +func waitImageBlockPublicAccessState(ctx context.Context, conn *ec2.Client, target string, timeout time.Duration) error { + stateConf := &retry.StateChangeConf{ + Target: []string{target}, + Refresh: statusImageBlockPublicAccess(ctx, conn), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitImageDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Image, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ImageStateAvailable, awstypes.ImageStateFailed, awstypes.ImageStatePending), + Target: []string{}, + Refresh: statusImage(ctx, conn, id), + Timeout: timeout, + Delay: amiRetryDelay, + MinTimeout: amiRetryMinTimeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Image); ok { + if stateReason := output.StateReason; stateReason != nil { + tfresource.SetLastError(err, errors.New(aws.ToString(stateReason.Message))) + } + + return output, err + } + + return nil, err +} + +func waitInstanceCapacityReservationSpecificationUpdated(ctx context.Context, conn *ec2.Client, instanceID string, expectedValue *awstypes.CapacityReservationSpecification) (*awstypes.Instance, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(true)), + Refresh: statusInstanceCapacityReservationSpecificationEquals(ctx, conn, instanceID, expectedValue), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Instance); ok { + return output, err + } + + return nil, err +} + +func waitInstanceConnectEndpointCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ec2InstanceConnectEndpoint, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.Ec2InstanceConnectEndpointStateCreateInProgress), + Target: enum.Slice(awstypes.Ec2InstanceConnectEndpointStateCreateComplete), + Refresh: statusInstanceConnectEndpoint(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Ec2InstanceConnectEndpoint); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + + return output, err + } + + return nil, err +} + +func waitInstanceConnectEndpointDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ec2InstanceConnectEndpoint, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.Ec2InstanceConnectEndpointStateDeleteInProgress), + Target: []string{}, + Refresh: statusInstanceConnectEndpoint(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Ec2InstanceConnectEndpoint); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + + return output, err + } + + return nil, err +} + +func waitInstanceIAMInstanceProfileUpdated(ctx context.Context, conn *ec2.Client, instanceID string, expectedValue string) (*awstypes.Instance, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(expectedValue), + Refresh: statusInstanceIAMInstanceProfile(ctx, conn, instanceID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Instance); ok { + return output, err + } + + return nil, err +} + +func waitInstanceMaintenanceOptionsAutoRecoveryUpdated(ctx context.Context, conn *ec2.Client, id, expectedValue string, timeout time.Duration) (*awstypes.InstanceMaintenanceOptions, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(expectedValue), + Refresh: statusInstanceMaintenanceOptionsAutoRecovery(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.InstanceMaintenanceOptions); ok { + return output, err + } + + return nil, err +} + +func waitInstanceMetadataOptionsApplied(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.InstanceMetadataOptionsResponse, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.InstanceMetadataOptionsStatePending), + Target: enum.Slice(awstypes.InstanceMetadataOptionsStateApplied), + Refresh: statusInstanceMetadataOptions(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.InstanceMetadataOptionsResponse); ok { + return output, err + } + + return nil, err +} + +func waitInstanceRootBlockDeviceDeleteOnTerminationUpdated(ctx context.Context, conn *ec2.Client, id string, expectedValue bool, timeout time.Duration) (*awstypes.EbsInstanceBlockDevice, error) { + stateConf := &retry.StateChangeConf{ + Target: []string{strconv.FormatBool(expectedValue)}, + Refresh: statusInstanceRootBlockDeviceDeleteOnTermination(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.EbsInstanceBlockDevice); ok { + return output, err + } + + return nil, err +} + +func waitInternetGatewayAttached(ctx context.Context, conn *ec2.Client, internetGatewayID, vpcID string, timeout time.Duration) (*awstypes.InternetGatewayAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AttachmentStatusAttaching), + Target: enum.Slice(internetGatewayAttachmentStateAvailable), + Timeout: timeout, + NotFoundChecks: internetGatewayNotFoundChecks, + Refresh: statusInternetGatewayAttachmentState(ctx, conn, internetGatewayID, vpcID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.InternetGatewayAttachment); ok { + return output, err + } + + return nil, err +} + +func waitInternetGatewayDetached(ctx context.Context, conn *ec2.Client, internetGatewayID, vpcID string, timeout time.Duration) (*awstypes.InternetGatewayAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(internetGatewayAttachmentStateAvailable, awstypes.AttachmentStatusDetaching), + Target: []string{}, + Timeout: timeout, + Refresh: statusInternetGatewayAttachmentState(ctx, conn, internetGatewayID, vpcID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.InternetGatewayAttachment); ok { + return output, err + } + + return nil, err +} + +func waitIPAMCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ipam, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamStateCreateInProgress), + Target: enum.Slice(awstypes.IpamStateCreateComplete), + Refresh: statusIPAM(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Ipam); ok { + return output, err + } + + return nil, err +} + +func waitIPAMDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ipam, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamStateCreateComplete, awstypes.IpamStateModifyComplete, awstypes.IpamStateDeleteInProgress), + Target: []string{}, + Refresh: statusIPAM(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Ipam); ok { + return output, err + } + + return nil, err +} + +func waitIPAMPoolCIDRCreated(ctx context.Context, conn *ec2.Client, poolCIDRID, poolID, cidrBlock string, timeout time.Duration) (*awstypes.IpamPoolCidr, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamPoolCidrStatePendingProvision), + Target: enum.Slice(awstypes.IpamPoolCidrStateProvisioned), + Refresh: statusIPAMPoolCIDR(ctx, conn, cidrBlock, poolID, poolCIDRID), + Timeout: timeout, + Delay: 5 * time.Second, + NotFoundChecks: 1000, // Should exceed any reasonable custom timeout value. + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamPoolCidr); ok { + if state, failureReason := output.State, output.FailureReason; state == awstypes.IpamPoolCidrStateFailedProvision && failureReason != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", string(failureReason.Code), aws.ToString(failureReason.Message))) + } + + return output, err + } + + return nil, err +} + +func waitIPAMPoolCIDRDeleted(ctx context.Context, conn *ec2.Client, poolCIDRID, poolID, cidrBlock string, timeout time.Duration) (*awstypes.IpamPoolCidr, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamPoolCidrStatePendingDeprovision, awstypes.IpamPoolCidrStateProvisioned), + Target: []string{}, + Refresh: statusIPAMPoolCIDR(ctx, conn, cidrBlock, poolID, poolCIDRID), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamPoolCidr); ok { + if state, failureReason := output.State, output.FailureReason; state == awstypes.IpamPoolCidrStateFailedDeprovision && failureReason != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", string(failureReason.Code), aws.ToString(failureReason.Message))) + } + + return output, err + } + + return nil, err +} + +func waitIPAMPoolCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamPool, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamPoolStateCreateInProgress), + Target: enum.Slice(awstypes.IpamPoolStateCreateComplete), + Refresh: statusIPAMPool(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamPool); ok { + if state := output.State; state == awstypes.IpamPoolStateCreateFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + } + + return output, err + } + + return nil, err +} + +func waitIPAMPoolDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamPool, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamPoolStateDeleteInProgress), + Target: []string{}, + Refresh: statusIPAMPool(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamPool); ok { + if state := output.State; state == awstypes.IpamPoolStateDeleteFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + } + + return output, err + } + + return nil, err +} + +func waitIPAMPoolUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamPool, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamPoolStateModifyInProgress), + Target: enum.Slice(awstypes.IpamPoolStateModifyComplete), + Refresh: statusIPAMPool(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamPool); ok { + if state := output.State; state == awstypes.IpamPoolStateModifyFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + } + + return output, err + } + + return nil, err +} + +func waitIPAMResourceDiscoveryAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscoveryAssociation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamResourceDiscoveryAssociationStateAssociateInProgress), + Target: enum.Slice(awstypes.IpamResourceDiscoveryAssociationStateAssociateComplete), + Refresh: statusIPAMResourceDiscoveryAssociation(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamResourceDiscoveryAssociation); ok { + return output, err + } + + return nil, err +} + +func waitIPAMResourceDiscoveryAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscoveryAssociation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamResourceDiscoveryAssociationStateAssociateComplete, awstypes.IpamResourceDiscoveryAssociationStateDisassociateInProgress), + Target: []string{}, + Refresh: statusIPAMResourceDiscoveryAssociation(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamResourceDiscoveryAssociation); ok { + return output, err + } + + return nil, err +} + +func waitIPAMResourceDiscoveryCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscovery, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamResourceDiscoveryStateCreateInProgress), + Target: enum.Slice(awstypes.IpamResourceDiscoveryStateCreateComplete), + Refresh: statusIPAMResourceDiscovery(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamResourceDiscovery); ok { + return output, err + } + + return nil, err +} + +func waitIPAMResourceDiscoveryDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscovery, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamResourceDiscoveryStateCreateComplete, awstypes.IpamResourceDiscoveryStateModifyComplete, awstypes.IpamResourceDiscoveryStateDeleteInProgress), + Target: []string{}, + Refresh: statusIPAMResourceDiscovery(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamResourceDiscovery); ok { + return output, err + } + + return nil, err +} + +func waitIPAMResourceDiscoveryUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscovery, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamResourceDiscoveryStateModifyInProgress), + Target: enum.Slice(awstypes.IpamResourceDiscoveryStateModifyComplete), + Refresh: statusIPAMResourceDiscovery(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamResourceDiscovery); ok { + return output, err + } + + return nil, err +} + +func waitIPAMScopeCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamScope, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamScopeStateCreateInProgress), + Target: enum.Slice(awstypes.IpamScopeStateCreateComplete), + Refresh: statusIPAMScope(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamScope); ok { + return output, err + } + + return nil, err +} + +func waitIPAMScopeDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamScope, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamScopeStateCreateComplete, awstypes.IpamScopeStateModifyComplete, awstypes.IpamScopeStateDeleteInProgress), + Target: []string{}, + Refresh: statusIPAMScope(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamScope); ok { + return output, err + } + + return nil, err +} + +func waitIPAMScopeUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamScope, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamScopeStateModifyInProgress), + Target: enum.Slice(awstypes.IpamScopeStateModifyComplete), + Refresh: statusIPAMScope(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.IpamScope); ok { + return output, err + } + + return nil, err +} + +func waitIPAMUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ipam, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.IpamStateModifyInProgress), + Target: enum.Slice(awstypes.IpamStateModifyComplete), + Refresh: statusIPAM(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Ipam); ok { + return output, err + } + + return nil, err +} + +func waitLocalGatewayRouteDeleted(ctx context.Context, conn *ec2.Client, localGatewayRouteTableID, destinationCIDRBlock string) (*awstypes.LocalGatewayRoute, error) { + const ( + timeout = 5 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.LocalGatewayRouteStateDeleting), + Target: []string{}, + Refresh: statusLocalGatewayRoute(ctx, conn, localGatewayRouteTableID, destinationCIDRBlock), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.LocalGatewayRoute); ok { + return output, err + } + + return nil, err +} + +func waitLocalGatewayRouteTableVPCAssociationAssociated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { + const ( + timeout = 5 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociating), + Target: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociated), + Refresh: statusLocalGatewayRouteTableVPCAssociation(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.LocalGatewayRouteTableVpcAssociation); ok { + return output, err + } + + return nil, err +} + +func waitLocalGatewayRouteTableVPCAssociationDisassociated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { + const ( + timeout = 5 * time.Minute + ) + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeDisassociating), + Target: []string{}, + Refresh: statusLocalGatewayRouteTableVPCAssociation(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.LocalGatewayRouteTableVpcAssociation); ok { + return output, err + } + + return nil, err +} + +func waitManagedPrefixListCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ManagedPrefixList, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.PrefixListStateCreateInProgress), + Target: enum.Slice(awstypes.PrefixListStateCreateComplete), + Timeout: managedPrefixListTimeout, + Refresh: statusManagedPrefixListState(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ManagedPrefixList); ok { + if output.State == awstypes.PrefixListStateCreateFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + } + + return output, err + } + + return nil, err +} + +func waitManagedPrefixListDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ManagedPrefixList, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.PrefixListStateDeleteInProgress), + Target: []string{}, + Timeout: managedPrefixListTimeout, + Refresh: statusManagedPrefixListState(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ManagedPrefixList); ok { + if output.State == awstypes.PrefixListStateDeleteFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + } + + return output, err + } + + return nil, err +} + +func waitManagedPrefixListModified(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ManagedPrefixList, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.PrefixListStateModifyInProgress), + Target: enum.Slice(awstypes.PrefixListStateModifyComplete), + Timeout: managedPrefixListTimeout, + Refresh: statusManagedPrefixListState(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ManagedPrefixList); ok { + if output.State == awstypes.PrefixListStateModifyFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNATGatewayAddressAssigned(ctx context.Context, conn *ec2.Client, natGatewayID, privateIP string, timeout time.Duration) (*awstypes.NatGatewayAddress, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NatGatewayAddressStatusAssigning), + Target: enum.Slice(awstypes.NatGatewayAddressStatusSucceeded), + Refresh: statusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx, conn, natGatewayID, privateIP), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NatGatewayAddress); ok { + if output.Status == awstypes.NatGatewayAddressStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.FailureMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNATGatewayAddressAssociated(ctx context.Context, conn *ec2.Client, natGatewayID, allocationID string, timeout time.Duration) (*awstypes.NatGatewayAddress, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NatGatewayAddressStatusAssociating), + Target: enum.Slice(awstypes.NatGatewayAddressStatusSucceeded), + Refresh: statusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx, conn, natGatewayID, allocationID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NatGatewayAddress); ok { + if output.Status == awstypes.NatGatewayAddressStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.FailureMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNATGatewayAddressDisassociated(ctx context.Context, conn *ec2.Client, natGatewayID, allocationID string, timeout time.Duration) (*awstypes.NatGatewayAddress, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NatGatewayAddressStatusSucceeded, awstypes.NatGatewayAddressStatusDisassociating), + Target: []string{}, + Refresh: statusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx, conn, natGatewayID, allocationID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NatGatewayAddress); ok { + if output.Status == awstypes.NatGatewayAddressStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.FailureMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNATGatewayAddressUnassigned(ctx context.Context, conn *ec2.Client, natGatewayID, privateIP string, timeout time.Duration) (*awstypes.NatGatewayAddress, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NatGatewayAddressStatusUnassigning), + Target: []string{}, + Refresh: statusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx, conn, natGatewayID, privateIP), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NatGatewayAddress); ok { + if output.Status == awstypes.NatGatewayAddressStatusFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.FailureMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNATGatewayCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NatGateway, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NatGatewayStatePending), + Target: enum.Slice(awstypes.NatGatewayStateAvailable), + Refresh: statusNATGatewayState(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NatGateway); ok { + if output.State == awstypes.NatGatewayStateFailed { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(output.FailureCode), aws.ToString(output.FailureMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNATGatewayDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NatGateway, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NatGatewayStateDeleting), + Target: []string{}, + Refresh: statusNATGatewayState(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NatGateway); ok { + if output.State == awstypes.NatGatewayStateFailed { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(output.FailureCode), aws.ToString(output.FailureMessage))) + } + + return output, err + } + + return nil, err +} + +func waitNetworkInsightsAnalysisCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInsightsAnalysis, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AnalysisStatusRunning), + Target: enum.Slice(awstypes.AnalysisStatusSucceeded), + Timeout: timeout, + Refresh: statusNetworkInsightsAnalysis(ctx, conn, id), + Delay: 10 * time.Second, + MinTimeout: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NetworkInsightsAnalysis); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + + return output, err + } + + return nil, err +} + +func waitNetworkInterfaceAvailableAfterUse(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterface, error) { + // Hyperplane attached ENI. + // Wait for it to be moved into a removable state. + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.NetworkInterfaceStatusInUse), + Target: enum.Slice(awstypes.NetworkInterfaceStatusAvailable), + Timeout: timeout, + Refresh: statusNetworkInterface(ctx, conn, id), + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, + // Handle EC2 ENI eventual consistency. It can take up to 3 minutes. + ContinuousTargetOccurence: 18, + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NetworkInterface); ok { + return output, err + } + + return nil, err +} + +func waitNetworkInterfaceCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterface, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{networkInterfaceStatusPending}, + Target: enum.Slice(awstypes.NetworkInterfaceStatusAvailable), + Timeout: timeout, + Refresh: statusNetworkInterface(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NetworkInterface); ok { + return output, err + } + + return nil, err +} + +func waitNetworkInterfaceAttached(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterfaceAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AttachmentStatusAttaching), + Target: enum.Slice(awstypes.AttachmentStatusAttached), + Timeout: timeout, + Refresh: statusNetworkInterfaceAttachment(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NetworkInterfaceAttachment); ok { + return output, err + } + + return nil, err +} + +func waitNetworkInterfaceDetached(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterfaceAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AttachmentStatusAttached, awstypes.AttachmentStatusDetaching), + Target: enum.Slice(awstypes.AttachmentStatusDetached), + Timeout: timeout, + Refresh: statusNetworkInterfaceAttachment(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.NetworkInterfaceAttachment); ok { + return output, err + } + + return nil, err +} + +func waitPlacementGroupCreated(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PlacementGroup, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.PlacementGroupStatePending), + Target: enum.Slice(awstypes.PlacementGroupStateAvailable), + Timeout: placementGroupCreatedTimeout, + Refresh: statusPlacementGroup(ctx, conn, name), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.PlacementGroup); ok { + return output, err + } + + return nil, err +} + +func waitPlacementGroupDeleted(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PlacementGroup, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.PlacementGroupStateDeleting), + Target: []string{}, + Timeout: placementGroupDeletedTimeout, + Refresh: statusPlacementGroup(ctx, conn, name), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.PlacementGroup); ok { + return output, err + } + + return nil, err +} + +func waitRouteDeleted(ctx context.Context, conn *ec2.Client, routeFinder routeFinder, routeTableID, destination string, timeout time.Duration) (*awstypes.Route, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: []string{routeStatusReady}, + Target: []string{}, + Refresh: statusRoute(ctx, conn, routeFinder, routeTableID, destination), + Timeout: timeout, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Route); ok { + return output, err + } + + return nil, err +} + +func waitRouteReady(ctx context.Context, conn *ec2.Client, routeFinder routeFinder, routeTableID, destination string, timeout time.Duration) (*awstypes.Route, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: []string{}, + Target: []string{routeStatusReady}, + Refresh: statusRoute(ctx, conn, routeFinder, routeTableID, destination), + Timeout: timeout, + NotFoundChecks: routeNotFoundChecks, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Route); ok { + return output, err + } + + return nil, err +} + +func waitRouteTableAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTableAssociationState, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociating), + Target: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociated), + Refresh: statusRouteTableAssociation(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: routeTableAssociationCreatedNotFoundChecks, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.RouteTableAssociationState); ok { + if output.State == awstypes.RouteTableAssociationStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + } + + return output, err + } + + return nil, err +} + +func waitRouteTableAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTableAssociationState, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeDisassociating, awstypes.RouteTableAssociationStateCodeAssociated), + Target: []string{}, + Refresh: statusRouteTableAssociation(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.RouteTableAssociationState); ok { + if output.State == awstypes.RouteTableAssociationStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + } + + return output, err + } + + return nil, err +} + +func waitRouteTableAssociationUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTableAssociationState, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociating), + Target: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociated), + Refresh: statusRouteTableAssociation(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.RouteTableAssociationState); ok { + if output.State == awstypes.RouteTableAssociationStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + } + + return output, err + } + + return nil, err +} + +func waitRouteTableDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTable, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{routeTableStatusReady}, + Target: []string{}, + Refresh: statusRouteTable(ctx, conn, id), + Timeout: timeout, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.RouteTable); ok { + return output, err + } + + return nil, err +} + +func waitRouteTableReady(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTable, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{}, + Target: []string{routeTableStatusReady}, + Refresh: statusRouteTable(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: routeTableNotFoundChecks, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.RouteTable); ok { + return output, err + } + + return nil, err +} + +func waitSecurityGroupCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SecurityGroup, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{}, + Target: []string{securityGroupStatusCreated}, + Refresh: statusSecurityGroup(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: securityGroupNotFoundChecks, + ContinuousTargetOccurence: 3, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SecurityGroup); ok { + return output, err + } + + return nil, err +} + +func waitSpotFleetRequestCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotFleetRequestConfig, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.BatchStateSubmitted), + Target: enum.Slice(awstypes.BatchStateActive), + Refresh: statusSpotFleetRequest(ctx, conn, id), + Timeout: timeout, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SpotFleetRequestConfig); ok { + return output, err + } + + return nil, err +} + +func waitSpotFleetRequestFulfilled(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotFleetRequestConfig, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ActivityStatusPendingFulfillment), + Target: enum.Slice(awstypes.ActivityStatusFulfilled), + Refresh: statusSpotFleetActivityStatus(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SpotFleetRequestConfig); ok { + if output.ActivityStatus == awstypes.ActivityStatusError { + var errs []error + + input := &ec2.DescribeSpotFleetRequestHistoryInput{ + SpotFleetRequestId: aws.String(id), + StartTime: aws.Time(time.UnixMilli(0)), + } + + if output, err := findSpotFleetRequestHistoryRecords(ctx, conn, input); err == nil { + for _, v := range output { + if eventType := v.EventType; eventType == awstypes.EventTypeError || eventType == awstypes.EventTypeInformation { + errs = append(errs, errors.New(aws.ToString(v.EventInformation.EventDescription))) + } + } + } + + tfresource.SetLastError(err, errors.Join(errs...)) + } + + return output, err + } + + return nil, err +} + +func waitSpotFleetRequestUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotFleetRequestConfig, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.BatchStateModifying), + Target: enum.Slice(awstypes.BatchStateActive), + Refresh: statusSpotFleetRequest(ctx, conn, id), + Timeout: timeout, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SpotFleetRequestConfig); ok { + return output, err + } + + return nil, err +} + +func waitSpotInstanceRequestFulfilled(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotInstanceRequest, error) { + stateConf := &retry.StateChangeConf{ + Pending: []string{spotInstanceRequestStatusCodePendingEvaluation, spotInstanceRequestStatusCodePendingFulfillment}, + Target: []string{spotInstanceRequestStatusCodeFulfilled}, + Refresh: statusSpotInstanceRequest(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SpotInstanceRequest); ok { + if fault := output.Fault; fault != nil { + errFault := fmt.Errorf("%s: %s", aws.ToString(fault.Code), aws.ToString(fault.Message)) + tfresource.SetLastError(err, fmt.Errorf("%s %w", aws.ToString(output.Status.Message), errFault)) + } else { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + } + + return output, err + } + + return nil, err +} + +func waitSubnetAssignIPv6AddressOnCreationUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue bool) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(expectedValue)), + Refresh: statusSubnetAssignIPv6AddressOnCreation(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetAvailable(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.SubnetStatePending), + Target: enum.Slice(awstypes.SubnetStateAvailable), + Refresh: statusSubnetState(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetEnableDNS64Updated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue bool) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(expectedValue)), + Refresh: statusSubnetEnableDNS64(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetEnableLniAtDeviceIndexUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue int32) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatInt(int64(expectedValue), 10)), + Refresh: statusSubnetEnableLniAtDeviceIndex(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetEnableResourceNameDNSAAAARecordOnLaunchUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue bool) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(expectedValue)), + Refresh: statusSubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetEnableResourceNameDNSARecordOnLaunchUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue bool) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(expectedValue)), + Refresh: statusSubnetEnableResourceNameDNSARecordOnLaunch(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetIPv6CIDRBlockAssociationCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SubnetCidrBlockState, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.SubnetCidrBlockStateCodeAssociating, awstypes.SubnetCidrBlockStateCodeDisassociated, awstypes.SubnetCidrBlockStateCodeFailing), + Target: enum.Slice(awstypes.SubnetCidrBlockStateCodeAssociated), + Refresh: statusSubnetIPv6CIDRBlockAssociationState(ctx, conn, id), + Timeout: subnetIPv6CIDRBlockAssociationCreatedTimeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SubnetCidrBlockState); ok { + if output.State == awstypes.SubnetCidrBlockStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + } + + return output, err + } + + return nil, err +} + +func waitSubnetIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.SubnetCidrBlockState, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.SubnetCidrBlockStateCodeAssociated, awstypes.SubnetCidrBlockStateCodeDisassociating, awstypes.SubnetCidrBlockStateCodeFailing), + Target: []string{}, + Refresh: statusSubnetIPv6CIDRBlockAssociationState(ctx, conn, id), + Timeout: subnetIPv6CIDRBlockAssociationDeletedTimeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.SubnetCidrBlockState); ok { + if output.State == awstypes.SubnetCidrBlockStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + } + + return output, err + } + + return nil, err +} + +func waitSubnetMapCustomerOwnedIPOnLaunchUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue bool) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(expectedValue)), + Refresh: statusSubnetMapCustomerOwnedIPOnLaunch(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetMapPublicIPOnLaunchUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue bool) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(strconv.FormatBool(expectedValue)), + Refresh: statusSubnetMapPublicIPOnLaunch(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitSubnetPrivateDNSHostnameTypeOnLaunchUpdated(ctx context.Context, conn *ec2.Client, subnetID string, expectedValue string) (*awstypes.Subnet, error) { + stateConf := &retry.StateChangeConf{ + Target: enum.Slice(expectedValue), + Refresh: statusSubnetPrivateDNSHostnameTypeOnLaunch(ctx, conn, subnetID), + Timeout: ec2PropagationTimeout, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Subnet); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayConnectCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnect, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStatePending), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), + Refresh: statusTransitGatewayConnect(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayConnect); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayConnectDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnect, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable, awstypes.TransitGatewayAttachmentStateDeleting), + Target: []string{}, + Refresh: statusTransitGatewayConnect(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayConnect); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayConnectPeerCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnectPeer, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayConnectPeerStatePending), + Target: enum.Slice(awstypes.TransitGatewayConnectPeerStateAvailable), + Refresh: statusTransitGatewayConnectPeer(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayConnectPeer); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayConnectPeerDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnectPeer, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayConnectPeerStateAvailable, awstypes.TransitGatewayConnectPeerStateDeleting), + Target: []string{}, + Refresh: statusTransitGatewayConnectPeer(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayConnectPeer); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGateway, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayStatePending), + Target: enum.Slice(awstypes.TransitGatewayStateAvailable), + Refresh: statusTransitGateway(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGateway); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGateway, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayStateAvailable, awstypes.TransitGatewayStateDeleting), + Target: []string{}, + Refresh: statusTransitGateway(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGateway); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayMulticastDomainCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomain, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayMulticastDomainStatePending), + Target: enum.Slice(awstypes.TransitGatewayMulticastDomainStateAvailable), + Refresh: statusTransitGatewayMulticastDomain(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomain); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayMulticastDomainDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomain, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayMulticastDomainStateAvailable, awstypes.TransitGatewayMulticastDomainStateDeleting), + Target: []string{}, + Refresh: statusTransitGatewayMulticastDomain(ctx, conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomain); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayMulticastDomainAssociationCreated(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AssociationStatusCodeAssociating), + Target: enum.Slice(awstypes.AssociationStatusCodeAssociated), + Refresh: statusTransitGatewayMulticastDomainAssociation(ctx, conn, multicastDomainID, attachmentID, subnetID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomainAssociation); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayMulticastDomainAssociationDeleted(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.AssociationStatusCodeAssociated, awstypes.AssociationStatusCodeDisassociating), + Target: []string{}, + Refresh: statusTransitGatewayMulticastDomainAssociation(ctx, conn, multicastDomainID, attachmentID, subnetID), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomainAssociation); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayPeeringAttachmentAccepted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPeeringAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStatePending, awstypes.TransitGatewayAttachmentStatePendingAcceptance), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), + Timeout: transitGatewayPeeringAttachmentUpdatedTimeout, + Refresh: statusTransitGatewayPeeringAttachment(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPeeringAttachment); ok { + if status := output.Status; status != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(status.Code), aws.ToString(status.Message))) + } + + return output, err + } + + return nil, err +} + +func waitTransitGatewayPeeringAttachmentCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPeeringAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateFailing, awstypes.TransitGatewayAttachmentStateInitiatingRequest, awstypes.TransitGatewayAttachmentStatePending), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable, awstypes.TransitGatewayAttachmentStatePendingAcceptance), + Timeout: transitGatewayPeeringAttachmentCreatedTimeout, + Refresh: statusTransitGatewayPeeringAttachment(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPeeringAttachment); ok { + if status := output.Status; status != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(status.Code), aws.ToString(status.Message))) + } + + return output, err + } + + return nil, err +} + +func waitTransitGatewayPeeringAttachmentDeleted(ctx context.Context, conn *ec2.Client, id string) error { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice( + awstypes.TransitGatewayAttachmentStateAvailable, + awstypes.TransitGatewayAttachmentStateDeleting, + awstypes.TransitGatewayAttachmentStatePendingAcceptance, + awstypes.TransitGatewayAttachmentStateRejecting, + ), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateDeleted), + Timeout: transitGatewayPeeringAttachmentDeletedTimeout, + Refresh: statusTransitGatewayPeeringAttachment(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPeeringAttachment); ok { + if status := output.Status; status != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(status.Code), aws.ToString(status.Message))) + } + } + + return err +} + +func waitTransitGatewayPrefixListReferenceStateCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStatePending), + Target: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateAvailable), + Timeout: transitGatewayPrefixListReferenceTimeout, + Refresh: statusTransitGatewayPrefixListReference(ctx, conn, transitGatewayRouteTableID, prefixListID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPrefixListReference); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayPrefixListReferenceStateDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateDeleting), + Target: []string{}, + Timeout: transitGatewayPrefixListReferenceTimeout, + Refresh: statusTransitGatewayPrefixListReference(ctx, conn, transitGatewayRouteTableID, prefixListID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPrefixListReference); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayPrefixListReferenceStateUpdated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateModifying), + Target: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateAvailable), + Timeout: transitGatewayPrefixListReferenceTimeout, + Refresh: statusTransitGatewayPrefixListReference(ctx, conn, transitGatewayRouteTableID, prefixListID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPrefixListReference); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayRouteCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) (*awstypes.TransitGatewayRoute, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayRouteStatePending), + Target: enum.Slice(awstypes.TransitGatewayRouteStateActive, awstypes.TransitGatewayRouteStateBlackhole), + Timeout: transitGatewayRouteCreatedTimeout, + Refresh: statusTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayRoute); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayRouteDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) (*awstypes.TransitGatewayRoute, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayRouteStateActive, awstypes.TransitGatewayRouteStateBlackhole, awstypes.TransitGatewayRouteStateDeleting), + Target: []string{}, + Timeout: transitGatewayRouteDeletedTimeout, + Refresh: statusTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayRoute); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayPolicyTableCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPolicyTable, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayPolicyTableStatePending), + Target: enum.Slice(awstypes.TransitGatewayPolicyTableStateAvailable), + Timeout: transitGatewayPolicyTableCreatedTimeout, + Refresh: statusTransitGatewayPolicyTable(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTable); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayRouteTableCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayRouteTable, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayRouteTableStatePending), + Target: enum.Slice(awstypes.TransitGatewayRouteTableStateAvailable), + Timeout: transitGatewayRouteTableCreatedTimeout, + Refresh: statusTransitGatewayRouteTable(ctx, conn, id), + } -const ( - InstanceReadyTimeout = 10 * time.Minute - InstanceStartTimeout = 10 * time.Minute - InstanceStopTimeout = 10 * time.Minute - - // General timeout for IAM resource change to propagate. - // See https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_eventual-consistency. - // We have settled on 2 minutes as the best timeout value. - iamPropagationTimeout = 2 * time.Minute - - // General timeout for EC2 resource changes to propagate. - // See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#eventual-consistency. - ec2PropagationTimeout = 5 * time.Minute // nosemgrep:ci.ec2-in-const-name, ci.ec2-in-var-name - - RouteNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. - RouteTableNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. - RouteTableAssociationCreatedNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. - SecurityGroupNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. - InternetGatewayNotFoundChecks = 1000 // Should exceed any reasonable custom timeout value. -) + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayRouteTable); ok { + return output, err + } -const ManagedPrefixListEntryCreateTimeout = 5 * time.Minute + return nil, err +} -func WaitSecurityGroupCreated(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.SecurityGroup, error) { +func waitTransitGatewayPolicyTableDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPolicyTable, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{}, - Target: []string{SecurityGroupStatusCreated}, - Refresh: StatusSecurityGroup(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: SecurityGroupNotFoundChecks, - ContinuousTargetOccurence: 3, + Pending: enum.Slice(awstypes.TransitGatewayPolicyTableStateAvailable, awstypes.TransitGatewayPolicyTableStateDeleting), + Target: []string{}, + Timeout: transitGatewayPolicyTableDeletedTimeout, + Refresh: statusTransitGatewayPolicyTable(ctx, conn, id), } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.SecurityGroup); ok { + if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTable); ok { return output, err } return nil, err } -const ( - SubnetIPv6CIDRBlockAssociationCreatedTimeout = 3 * time.Minute - SubnetIPv6CIDRBlockAssociationDeletedTimeout = 3 * time.Minute -) +func waitTransitGatewayRouteTableDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayRouteTable, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayRouteTableStateAvailable, awstypes.TransitGatewayRouteTableStateDeleting), + Target: []string{}, + Timeout: transitGatewayRouteTableDeletedTimeout, + Refresh: statusTransitGatewayRouteTable(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayRouteTable); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayPolicyTableAssociationCreated(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayPolicyTableAssociation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociating), + Target: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated), + Timeout: transitGatewayPolicyTableAssociationCreatedTimeout, + Refresh: statusTransitGatewayPolicyTableAssociation(ctx, conn, transitGatewayPolicyTableID, transitGatewayAttachmentID), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTableAssociation); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayPolicyTableAssociationDeleted(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayPolicyTableAssociation, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated, awstypes.TransitGatewayAssociationStateDisassociating), + Target: []string{}, + Timeout: transitGatewayPolicyTableAssociationDeletedTimeout, + Refresh: statusTransitGatewayPolicyTableAssociation(ctx, conn, transitGatewayPolicyTableID, transitGatewayAttachmentID), + NotFoundChecks: 1, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTableAssociation); ok { + return output, err + } + + return nil, err +} + +func waitTransitGatewayRouteTableAssociationCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) error { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociating), + Target: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated), + Timeout: transitGatewayRouteTableAssociationCreatedTimeout, + Refresh: statusTransitGatewayRouteTableAssociation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitTransitGatewayRouteTableAssociationDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) error { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated, awstypes.TransitGatewayAssociationStateDisassociating), + Target: []string{}, + Timeout: transitGatewayRouteTableAssociationDeletedTimeout, + Refresh: statusTransitGatewayRouteTableAssociation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), + NotFoundChecks: 1, + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitTransitGatewayRouteTablePropagationCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) error { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayPropagationStateEnabling), + Target: enum.Slice(awstypes.TransitGatewayPropagationStateEnabled), + Timeout: transitGatewayRouteTablePropagationCreatedTimeout, + Refresh: statusTransitGatewayRouteTablePropagation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitTransitGatewayRouteTablePropagationDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) error { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayPropagationStateDisabling), + Target: []string{}, + Timeout: transitGatewayRouteTablePropagationDeletedTimeout, + Refresh: statusTransitGatewayRouteTablePropagation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), + } + + _, err := stateConf.WaitForStateContext(ctx) + + if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { + return nil + } -func WaitSubnetAvailable(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.Subnet, error) { + return err +} + +func waitTransitGatewayUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGateway, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.SubnetStatePending}, - Target: []string{ec2.SubnetStateAvailable}, - Refresh: StatusSubnetState(ctx, conn, id), + Pending: enum.Slice(awstypes.TransitGatewayStateModifying), + Target: enum.Slice(awstypes.TransitGatewayStateAvailable), + Refresh: statusTransitGateway(ctx, conn, id), Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.TransitGateway); ok { return output, err } return nil, err } -func WaitSubnetIPv6CIDRBlockAssociationCreated(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SubnetCidrBlockState, error) { +func waitTransitGatewayVPCAttachmentAccepted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.SubnetCidrBlockStateCodeAssociating, ec2.SubnetCidrBlockStateCodeDisassociated, ec2.SubnetCidrBlockStateCodeFailing}, - Target: []string{ec2.SubnetCidrBlockStateCodeAssociated}, - Refresh: StatusSubnetIPv6CIDRBlockAssociationState(ctx, conn, id), - Timeout: SubnetIPv6CIDRBlockAssociationCreatedTimeout, + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStatePending, awstypes.TransitGatewayAttachmentStatePendingAcceptance), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), + Timeout: transitGatewayVPCAttachmentUpdatedTimeout, + Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.SubnetCidrBlockState); ok { - if state := aws.StringValue(output.State); state == ec2.SubnetCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StatusMessage))) - } + if output, ok := outputRaw.(*awstypes.TransitGatewayVpcAttachment); ok { + return output, err + } + + return nil, err +} +func waitTransitGatewayVPCAttachmentCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateFailing, awstypes.TransitGatewayAttachmentStatePending), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable, awstypes.TransitGatewayAttachmentStatePendingAcceptance), + Timeout: transitGatewayVPCAttachmentCreatedTimeout, + Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.TransitGatewayVpcAttachment); ok { return output, err } return nil, err } -func WaitSubnetIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC2, id string) (*ec2.SubnetCidrBlockState, error) { +func waitTransitGatewayVPCAttachmentDeleted(ctx context.Context, conn *ec2.Client, id string) error { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.SubnetCidrBlockStateCodeAssociated, ec2.SubnetCidrBlockStateCodeDisassociating, ec2.SubnetCidrBlockStateCodeFailing}, - Target: []string{}, - Refresh: StatusSubnetIPv6CIDRBlockAssociationState(ctx, conn, id), - Timeout: SubnetIPv6CIDRBlockAssociationDeletedTimeout, + Pending: enum.Slice( + awstypes.TransitGatewayAttachmentStateAvailable, + awstypes.TransitGatewayAttachmentStateDeleting, + awstypes.TransitGatewayAttachmentStatePendingAcceptance, + awstypes.TransitGatewayAttachmentStateRejecting, + ), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateDeleted), + Timeout: transitGatewayVPCAttachmentDeletedTimeout, + Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitTransitGatewayVPCAttachmentUpdated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateModifying), + Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), + Timeout: transitGatewayVPCAttachmentUpdatedTimeout, + Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.SubnetCidrBlockState); ok { - if state := aws.StringValue(output.State); state == ec2.SubnetCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StatusMessage))) - } + if output, ok := outputRaw.(*awstypes.TransitGatewayVpcAttachment); ok { + return output, err + } + + return nil, err +} + +func waitVerifiedAccessEndpointCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VerifiedAccessEndpoint, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodePending), + Target: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeActive), + Refresh: statusVerifiedAccessEndpoint(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.VerifiedAccessEndpoint); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) return output, err } @@ -126,136 +2537,150 @@ func WaitSubnetIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC return nil, err } -func waitSubnetAssignIPv6AddressOnCreationUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue bool) (*ec2.Subnet, error) { +func waitVerifiedAccessEndpointDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VerifiedAccessEndpoint, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: StatusSubnetAssignIPv6AddressOnCreation(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, + Pending: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeDeleting, awstypes.VerifiedAccessEndpointStatusCodeActive, awstypes.VerifiedAccessEndpointStatusCodeDeleted), + Target: []string{}, + Refresh: statusVerifiedAccessEndpoint(ctx, conn, id), + Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.VerifiedAccessEndpoint); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + return output, err } return nil, err } -func waitSubnetEnableLniAtDeviceIndexUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue int64) (*ec2.Subnet, error) { +func waitVerifiedAccessEndpointUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VerifiedAccessEndpoint, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatInt(expectedValue, 10)}, - Refresh: StatusSubnetEnableLniAtDeviceIndex(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, + Pending: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeUpdating), + Target: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeActive), + Refresh: statusVerifiedAccessEndpoint(ctx, conn, id), + Timeout: timeout, + NotFoundChecks: 20, + ContinuousTargetOccurence: 2, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.VerifiedAccessEndpoint); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) + return output, err } return nil, err } -func waitSubnetEnableDNS64Updated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue bool) (*ec2.Subnet, error) { +func waitVolumeAttachmentCreated(ctx context.Context, conn *ec2.Client, volumeID, instanceID, deviceName string, timeout time.Duration) (*awstypes.VolumeAttachment, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: StatusSubnetEnableDNS64(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, + Pending: enum.Slice(awstypes.VolumeAttachmentStateAttaching), + Target: enum.Slice(awstypes.VolumeAttachmentStateAttached), + Refresh: statusVolumeAttachment(ctx, conn, volumeID, instanceID, deviceName), + Timeout: timeout, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.VolumeAttachment); ok { return output, err } return nil, err } -func waitSubnetEnableResourceNameDNSAAAARecordOnLaunchUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue bool) (*ec2.Subnet, error) { +func waitVolumeCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Volume, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: StatusSubnetEnableResourceNameDNSAAAARecordOnLaunch(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, + Pending: enum.Slice(awstypes.VolumeStateCreating), + Target: enum.Slice(awstypes.VolumeStateAvailable), + Refresh: statusVolume(ctx, conn, id), + Timeout: timeout, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.Volume); ok { return output, err } return nil, err } -func waitSubnetEnableResourceNameDNSARecordOnLaunchUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue bool) (*ec2.Subnet, error) { +func waitVolumeDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Volume, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: StatusSubnetEnableResourceNameDNSARecordOnLaunch(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, + Pending: enum.Slice(awstypes.VolumeStateDeleting), + Target: []string{}, + Refresh: statusVolume(ctx, conn, id), + Timeout: timeout, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.Volume); ok { return output, err } return nil, err } -func WaitSubnetMapCustomerOwnedIPOnLaunchUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue bool) (*ec2.Subnet, error) { +func waitVolumeModificationComplete(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VolumeModification, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: StatusSubnetMapCustomerOwnedIPOnLaunch(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, + Pending: enum.Slice(awstypes.VolumeModificationStateModifying), + // The volume is useable once the state is "optimizing", but will not be at full performance. + // Optimization can take hours. e.g. a full 1 TiB drive takes approximately 6 hours to optimize, + // according to https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-modifications.html. + Target: enum.Slice(awstypes.VolumeModificationStateCompleted, awstypes.VolumeModificationStateOptimizing), + Refresh: statusVolumeModification(ctx, conn, id), + Timeout: timeout, + Delay: 30 * time.Second, + MinTimeout: 30 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.VolumeModification); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) + return output, err } return nil, err } -func WaitSubnetMapPublicIPOnLaunchUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue bool) (*ec2.Subnet, error) { +func waitVolumeUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Volume, error) { stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: StatusSubnetMapPublicIPOnLaunch(ctx, conn, subnetID), - Timeout: ec2PropagationTimeout, + Pending: enum.Slice(awstypes.VolumeStateCreating, awstypes.VolumeState(awstypes.VolumeModificationStateModifying)), + Target: enum.Slice(awstypes.VolumeStateAvailable, awstypes.VolumeStateInUse), + Refresh: statusVolume(ctx, conn, id), + Timeout: timeout, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.Volume); ok { return output, err } return nil, err } -func WaitSubnetPrivateDNSHostnameTypeOnLaunchUpdated(ctx context.Context, conn *ec2.EC2, subnetID string, expectedValue string) (*ec2.Subnet, error) { +func waitVPCAttributeUpdated(ctx context.Context, conn *ec2.Client, vpcID string, attribute awstypes.VpcAttributeName, expectedValue bool) (*awstypes.Vpc, error) { //nolint:unparam stateConf := &retry.StateChangeConf{ - Target: []string{expectedValue}, - Refresh: StatusSubnetPrivateDNSHostnameTypeOnLaunch(ctx, conn, subnetID), + Target: []string{strconv.FormatBool(expectedValue)}, + Refresh: statusVPCAttributeValue(ctx, conn, vpcID, attribute), Timeout: ec2PropagationTimeout, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -263,23 +2688,18 @@ func WaitSubnetPrivateDNSHostnameTypeOnLaunchUpdated(ctx context.Context, conn * outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.Subnet); ok { + if output, ok := outputRaw.(*awstypes.Vpc); ok { return output, err } return nil, err } -const ( - vpcCreatedTimeout = 10 * time.Minute - vpcDeletedTimeout = 5 * time.Minute -) - -func WaitVPCCIDRBlockAssociationCreated(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.VpcCidrBlockState, error) { +func waitVPCCIDRBlockAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcCidrBlockState, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.VpcCidrBlockStateCodeAssociating, ec2.VpcCidrBlockStateCodeDisassociated, ec2.VpcCidrBlockStateCodeFailing}, - Target: []string{ec2.VpcCidrBlockStateCodeAssociated}, - Refresh: StatusVPCCIDRBlockAssociationState(ctx, conn, id), + Pending: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociating, awstypes.VpcCidrBlockStateCodeDisassociated, awstypes.VpcCidrBlockStateCodeFailing), + Target: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociated), + Refresh: statusVPCCIDRBlockAssociationState(ctx, conn, id), Timeout: timeout, Delay: 10 * time.Second, MinTimeout: 5 * time.Second, @@ -287,9 +2707,9 @@ func WaitVPCCIDRBlockAssociationCreated(ctx context.Context, conn *ec2.EC2, id s outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.VpcCidrBlockState); ok { - if state := aws.StringValue(output.State); state == ec2.VpcCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StatusMessage))) + if output, ok := outputRaw.(*awstypes.VpcCidrBlockState); ok { + if state := output.State; state == awstypes.VpcCidrBlockStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) } return output, err @@ -298,11 +2718,11 @@ func WaitVPCCIDRBlockAssociationCreated(ctx context.Context, conn *ec2.EC2, id s return nil, err } -func WaitVPCCIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.VpcCidrBlockState, error) { +func waitVPCCIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcCidrBlockState, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.VpcCidrBlockStateCodeAssociated, ec2.VpcCidrBlockStateCodeDisassociating, ec2.VpcCidrBlockStateCodeFailing}, + Pending: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociated, awstypes.VpcCidrBlockStateCodeDisassociating, awstypes.VpcCidrBlockStateCodeFailing), Target: []string{}, - Refresh: StatusVPCCIDRBlockAssociationState(ctx, conn, id), + Refresh: statusVPCCIDRBlockAssociationState(ctx, conn, id), Timeout: timeout, Delay: 10 * time.Second, MinTimeout: 5 * time.Second, @@ -310,9 +2730,9 @@ func WaitVPCCIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC2, id s outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.VpcCidrBlockState); ok { - if state := aws.StringValue(output.State); state == ec2.VpcCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StatusMessage))) + if output, ok := outputRaw.(*awstypes.VpcCidrBlockState); ok { + if state := output.State; state == awstypes.VpcCidrBlockStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) } return output, err @@ -321,26 +2741,38 @@ func WaitVPCCIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC2, id s return nil, err } -const ( - vpcIPv6CIDRBlockAssociationCreatedTimeout = 10 * time.Minute - vpcIPv6CIDRBlockAssociationDeletedTimeout = 5 * time.Minute -) +func waitVPCCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Vpc, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.VpcStatePending), + Target: enum.Slice(awstypes.VpcStateAvailable), + Refresh: statusVPC(ctx, conn, id), + Timeout: vpcCreatedTimeout, + } -func WaitVPCIPv6CIDRBlockAssociationCreated(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.VpcCidrBlockState, error) { + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.Vpc); ok { + return output, err + } + + return nil, err +} + +func waitVPCEndpointAccepted(ctx context.Context, conn *ec2.Client, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.VpcCidrBlockStateCodeAssociating, ec2.VpcCidrBlockStateCodeDisassociated, ec2.VpcCidrBlockStateCodeFailing}, - Target: []string{ec2.VpcCidrBlockStateCodeAssociated}, - Refresh: StatusVPCIPv6CIDRBlockAssociationState(ctx, conn, id), + Pending: enum.Slice(vpcEndpointStatePendingAcceptance), + Target: enum.Slice(vpcEndpointStateAvailable), Timeout: timeout, - Delay: 10 * time.Second, + Refresh: statusVPCEndpoint(ctx, conn, vpcEndpointID), + Delay: 5 * time.Second, MinTimeout: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.VpcCidrBlockState); ok { - if state := aws.StringValue(output.State); state == ec2.VpcCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StatusMessage))) + if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { + if state, lastError := output.State, output.LastError; state == awstypes.StateFailed && lastError != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(lastError.Code), aws.ToString(lastError.Message))) } return output, err @@ -349,21 +2781,21 @@ func WaitVPCIPv6CIDRBlockAssociationCreated(ctx context.Context, conn *ec2.EC2, return nil, err } -func WaitVPCIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.VpcCidrBlockState, error) { +func waitVPCEndpointAvailable(ctx context.Context, conn *ec2.Client, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.VpcCidrBlockStateCodeAssociated, ec2.VpcCidrBlockStateCodeDisassociating, ec2.VpcCidrBlockStateCodeFailing}, - Target: []string{}, - Refresh: StatusVPCIPv6CIDRBlockAssociationState(ctx, conn, id), + Pending: enum.Slice(vpcEndpointStatePending), + Target: enum.Slice(vpcEndpointStateAvailable, vpcEndpointStatePendingAcceptance), Timeout: timeout, - Delay: 10 * time.Second, + Refresh: statusVPCEndpoint(ctx, conn, vpcEndpointID), + Delay: 5 * time.Second, MinTimeout: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.VpcCidrBlockState); ok { - if state := aws.StringValue(output.State); state == ec2.VpcCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StatusMessage))) + if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { + if state, lastError := output.State, output.LastError; state == awstypes.StateFailed && lastError != nil { + tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(lastError.Code), aws.ToString(lastError.Message))) } return output, err @@ -372,126 +2804,142 @@ func WaitVPCIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.EC2, return nil, err } -func WaitVPCPeeringConnectionActive(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.VpcPeeringConnection, error) { +func waitVPCEndpointConnectionAccepted(ctx context.Context, conn *ec2.Client, serviceID, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpointConnection, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.VpcPeeringConnectionStateReasonCodeInitiatingRequest, ec2.VpcPeeringConnectionStateReasonCodeProvisioning}, - Target: []string{ec2.VpcPeeringConnectionStateReasonCodeActive, ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance}, - Refresh: StatusVPCPeeringConnectionActive(ctx, conn, id), - Timeout: timeout, + Pending: []string{vpcEndpointStatePendingAcceptance, vpcEndpointStatePending}, + Target: []string{vpcEndpointStateAvailable}, + Refresh: statusVPCEndpointConnectionVPCEndpoint(ctx, conn, serviceID, vpcEndpointID), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.VpcPeeringConnection); ok { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.Status.Message))) - + if output, ok := outputRaw.(*awstypes.VpcEndpointConnection); ok { return output, err } return nil, err } -func WaitVPCPeeringConnectionDeleted(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.VpcPeeringConnection, error) { +func waitVPCEndpointDeleted(ctx context.Context, conn *ec2.Client, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ - ec2.VpcPeeringConnectionStateReasonCodeActive, - ec2.VpcPeeringConnectionStateReasonCodeDeleting, - ec2.VpcPeeringConnectionStateReasonCodePendingAcceptance, - }, - Target: []string{}, - Refresh: StatusVPCPeeringConnectionDeleted(ctx, conn, id), - Timeout: timeout, + Pending: enum.Slice(vpcEndpointStateDeleting, vpcEndpointStateDeleted), + Target: []string{}, + Refresh: statusVPCEndpoint(ctx, conn, vpcEndpointID), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.VpcPeeringConnection); ok { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.Status.Message))) - + if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { return output, err } return nil, err } -func WaitNATGatewayCreated(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.NatGateway, error) { +func waitVPCEndpointRouteTableAssociationDeleted(ctx context.Context, conn *ec2.Client, vpcEndpointID, routeTableID string) error { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NatGatewayStatePending}, - Target: []string{ec2.NatGatewayStateAvailable}, - Refresh: StatusNATGatewayState(ctx, conn, id), - Timeout: timeout, + Pending: enum.Slice(vpcEndpointRouteTableAssociationStatusReady), + Target: []string{}, + Refresh: statusVPCEndpointRouteTableAssociation(ctx, conn, vpcEndpointID, routeTableID), + Timeout: ec2PropagationTimeout, + ContinuousTargetOccurence: 2, } - outputRaw, err := stateConf.WaitForStateContext(ctx) + _, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NatGateway); ok { - if state := aws.StringValue(output.State); state == ec2.NatGatewayStateFailed { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(output.FailureCode), aws.StringValue(output.FailureMessage))) - } + return err +} + +func waitVPCEndpointRouteTableAssociationReady(ctx context.Context, conn *ec2.Client, vpcEndpointID, routeTableID string) error { + stateConf := &retry.StateChangeConf{ + Pending: []string{}, + Target: enum.Slice(vpcEndpointRouteTableAssociationStatusReady), + Refresh: statusVPCEndpointRouteTableAssociation(ctx, conn, vpcEndpointID, routeTableID), + Timeout: ec2PropagationTimeout, + ContinuousTargetOccurence: 2, + } + + _, err := stateConf.WaitForStateContext(ctx) + return err +} + +func waitVPCEndpointServiceAvailable(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.ServiceConfiguration, error) { //nolint:unparam + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.ServiceStatePending), + Target: enum.Slice(awstypes.ServiceStateAvailable), + Refresh: statusVPCEndpointServiceAvailable(ctx, conn, id), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, + } + + outputRaw, err := stateConf.WaitForStateContext(ctx) + + if output, ok := outputRaw.(*awstypes.ServiceConfiguration); ok { return output, err } return nil, err } -func WaitNATGatewayDeleted(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.NatGateway, error) { +func waitVPCEndpointServiceDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.ServiceConfiguration, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NatGatewayStateDeleting}, + Pending: enum.Slice(awstypes.ServiceStateAvailable, awstypes.ServiceStateDeleting), Target: []string{}, - Refresh: StatusNATGatewayState(ctx, conn, id), Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, + Refresh: fetchVPCEndpointServiceDeletionStatus(ctx, conn, id), + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NatGateway); ok { - if state := aws.StringValue(output.State); state == ec2.NatGatewayStateFailed { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.StringValue(output.FailureCode), aws.StringValue(output.FailureMessage))) - } - + if output, ok := outputRaw.(*awstypes.ServiceConfiguration); ok { return output, err } return nil, err } -func WaitNATGatewayAddressAssigned(ctx context.Context, conn *ec2.EC2, natGatewayID, privateIP string, timeout time.Duration) (*ec2.NatGatewayAddress, error) { +func waitVPCEndpointServicePrivateDNSNameVerified(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.PrivateDnsNameConfiguration, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NatGatewayAddressStatusAssigning}, - Target: []string{ec2.NatGatewayAddressStatusSucceeded}, - Refresh: StatusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx, conn, natGatewayID, privateIP), - Timeout: timeout, + Pending: enum.Slice(awstypes.DnsNameStatePendingVerification), + Target: enum.Slice(awstypes.DnsNameStateVerified), + Refresh: statusVPCEndpointServicePrivateDNSNameConfiguration(ctx, conn, id), + Timeout: timeout, + ContinuousTargetOccurence: 2, } outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*ec2.NatGatewayAddress); ok { - if status := aws.StringValue(output.Status); status == ec2.NatGatewayAddressStatusFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.FailureMessage))) - } - - return output, err + if out, ok := outputRaw.(*awstypes.PrivateDnsNameConfiguration); ok { + return out, err } return nil, err } -func WaitNATGatewayAddressAssociated(ctx context.Context, conn *ec2.EC2, natGatewayID, allocationID string, timeout time.Duration) (*ec2.NatGatewayAddress, error) { +func waitVPCIPv6CIDRBlockAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcCidrBlockState, error) { //nolint:unparam stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NatGatewayAddressStatusAssociating}, - Target: []string{ec2.NatGatewayAddressStatusSucceeded}, - Refresh: StatusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx, conn, natGatewayID, allocationID), - Timeout: timeout, + Pending: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociating, awstypes.VpcCidrBlockStateCodeDisassociated, awstypes.VpcCidrBlockStateCodeFailing), + Target: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociated), + Refresh: statusVPCIPv6CIDRBlockAssociation(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 5 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NatGatewayAddress); ok { - if status := aws.StringValue(output.Status); status == ec2.NatGatewayAddressStatusFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.FailureMessage))) + if output, ok := outputRaw.(*awstypes.VpcCidrBlockState); ok { + if state := output.State; state == awstypes.VpcCidrBlockStateCodeFailed { + tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) } return output, err @@ -500,20 +2948,33 @@ func WaitNATGatewayAddressAssociated(ctx context.Context, conn *ec2.EC2, natGate return nil, err } -func WaitNATGatewayAddressDisassociated(ctx context.Context, conn *ec2.EC2, natGatewayID, allocationID string, timeout time.Duration) (*ec2.NatGatewayAddress, error) { +func waitVPCIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) error { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NatGatewayAddressStatusSucceeded, ec2.NatGatewayAddressStatusDisassociating}, - Target: []string{}, - Refresh: StatusNATGatewayAddressByNATGatewayIDAndAllocationID(ctx, conn, natGatewayID, allocationID), + Pending: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociated, awstypes.VpcCidrBlockStateCodeDisassociating, awstypes.VpcCidrBlockStateCodeFailing), + Target: []string{}, + Refresh: statusVPCIPv6CIDRBlockAssociation(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 5 * time.Second, + } + + _, err := stateConf.WaitForStateContext(ctx) + + return err +} + +func waitVPCPeeringConnectionActive(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcPeeringConnection, error) { + stateConf := &retry.StateChangeConf{ + Pending: enum.Slice(awstypes.VpcPeeringConnectionStateReasonCodeInitiatingRequest, awstypes.VpcPeeringConnectionStateReasonCodeProvisioning), + Target: enum.Slice(awstypes.VpcPeeringConnectionStateReasonCodeActive, awstypes.VpcPeeringConnectionStateReasonCodePendingAcceptance), + Refresh: statusVPCPeeringConnectionActive(ctx, conn, id), Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NatGatewayAddress); ok { - if status := aws.StringValue(output.Status); status == ec2.NatGatewayAddressStatusFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.FailureMessage))) - } + if output, ok := outputRaw.(*awstypes.VpcPeeringConnection); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) return output, err } @@ -521,20 +2982,22 @@ func WaitNATGatewayAddressDisassociated(ctx context.Context, conn *ec2.EC2, natG return nil, err } -func WaitNATGatewayAddressUnassigned(ctx context.Context, conn *ec2.EC2, natGatewayID, privateIP string, timeout time.Duration) (*ec2.NatGatewayAddress, error) { +func waitVPCPeeringConnectionDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcPeeringConnection, error) { stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NatGatewayAddressStatusUnassigning}, + Pending: enum.Slice( + awstypes.VpcPeeringConnectionStateReasonCodeActive, + awstypes.VpcPeeringConnectionStateReasonCodeDeleting, + awstypes.VpcPeeringConnectionStateReasonCodePendingAcceptance, + ), Target: []string{}, - Refresh: StatusNATGatewayAddressByNATGatewayIDAndPrivateIP(ctx, conn, natGatewayID, privateIP), + Refresh: statusVPCPeeringConnectionDeleted(ctx, conn, id), Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NatGatewayAddress); ok { - if status := aws.StringValue(output.Status); status == ec2.NatGatewayAddressStatusFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.FailureMessage))) - } + if output, ok := outputRaw.(*awstypes.VpcPeeringConnection); ok { + tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) return output, err } @@ -542,186 +3005,190 @@ func WaitNATGatewayAddressUnassigned(ctx context.Context, conn *ec2.EC2, natGate return nil, err } -const ( - dhcpOptionSetDeletedTimeout = 3 * time.Minute -) - -func WaitInternetGatewayAttached(ctx context.Context, conn *ec2.EC2, internetGatewayID, vpcID string, timeout time.Duration) (*ec2.InternetGatewayAttachment, error) { +func waitVPNConnectionCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { + const ( + timeout = 40 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.AttachmentStatusAttaching}, - Target: []string{InternetGatewayAttachmentStateAvailable}, - Timeout: timeout, - NotFoundChecks: InternetGatewayNotFoundChecks, - Refresh: StatusInternetGatewayAttachmentState(ctx, conn, internetGatewayID, vpcID), + Pending: enum.Slice(awstypes.VpnStatePending), + Target: enum.Slice(awstypes.VpnStateAvailable), + Refresh: statusVPNConnection(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.InternetGatewayAttachment); ok { + if output, ok := outputRaw.(*awstypes.VpnConnection); ok { return output, err } return nil, err } -func WaitInternetGatewayDetached(ctx context.Context, conn *ec2.EC2, internetGatewayID, vpcID string, timeout time.Duration) (*ec2.InternetGatewayAttachment, error) { +func waitVPNConnectionDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { + const ( + timeout = 30 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{InternetGatewayAttachmentStateAvailable, ec2.AttachmentStatusDetaching}, - Target: []string{}, - Timeout: timeout, - Refresh: StatusInternetGatewayAttachmentState(ctx, conn, internetGatewayID, vpcID), + Pending: enum.Slice(awstypes.VpnStateDeleting), + Target: []string{}, + Refresh: statusVPNConnection(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.InternetGatewayAttachment); ok { + if output, ok := outputRaw.(*awstypes.VpnConnection); ok { return output, err } return nil, err } -const ( - ManagedPrefixListTimeout = 15 * time.Minute -) - -func WaitManagedPrefixListCreated(ctx context.Context, conn *ec2.EC2, id string) (*ec2.ManagedPrefixList, error) { +func waitVPNConnectionRouteCreated(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) (*awstypes.VpnStaticRoute, error) { + const ( + timeout = 15 * time.Second + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.PrefixListStateCreateInProgress}, - Target: []string{ec2.PrefixListStateCreateComplete}, - Timeout: ManagedPrefixListTimeout, - Refresh: StatusManagedPrefixListState(ctx, conn, id), + Pending: enum.Slice(awstypes.VpnStatePending), + Target: enum.Slice(awstypes.VpnStateAvailable), + Refresh: statusVPNConnectionRoute(ctx, conn, vpnConnectionID, cidrBlock), + Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.ManagedPrefixList); ok { - if state := aws.StringValue(output.State); state == ec2.PrefixListStateCreateFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StateMessage))) - } - + if output, ok := outputRaw.(*awstypes.VpnStaticRoute); ok { return output, err } return nil, err } -func WaitManagedPrefixListModified(ctx context.Context, conn *ec2.EC2, id string) (*ec2.ManagedPrefixList, error) { +func waitVPNConnectionRouteDeleted(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) (*awstypes.VpnStaticRoute, error) { + const ( + timeout = 15 * time.Second + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.PrefixListStateModifyInProgress}, - Target: []string{ec2.PrefixListStateModifyComplete}, - Timeout: ManagedPrefixListTimeout, - Refresh: StatusManagedPrefixListState(ctx, conn, id), + Pending: enum.Slice(awstypes.VpnStatePending, awstypes.VpnStateAvailable, awstypes.VpnStateDeleting), + Target: []string{}, + Refresh: statusVPNConnectionRoute(ctx, conn, vpnConnectionID, cidrBlock), + Timeout: timeout, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.ManagedPrefixList); ok { - if state := aws.StringValue(output.State); state == ec2.PrefixListStateModifyFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StateMessage))) - } - + if output, ok := outputRaw.(*awstypes.VpnStaticRoute); ok { return output, err } return nil, err } -func WaitManagedPrefixListDeleted(ctx context.Context, conn *ec2.EC2, id string) (*ec2.ManagedPrefixList, error) { +func waitVPNConnectionUpdated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { //nolint:unparam + const ( + timeout = 30 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.PrefixListStateDeleteInProgress}, - Target: []string{}, - Timeout: ManagedPrefixListTimeout, - Refresh: StatusManagedPrefixListState(ctx, conn, id), + Pending: enum.Slice(vpnStateModifying), + Target: enum.Slice(awstypes.VpnStateAvailable), + Refresh: statusVPNConnection(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.ManagedPrefixList); ok { - if state := aws.StringValue(output.State); state == ec2.PrefixListStateDeleteFailed { - tfresource.SetLastError(err, errors.New(aws.StringValue(output.StateMessage))) - } - + if output, ok := outputRaw.(*awstypes.VpnConnection); ok { return output, err } return nil, err } -const ( - networkInterfaceAttachedTimeout = 5 * time.Minute - NetworkInterfaceDetachedTimeout = 10 * time.Minute -) - -func WaitNetworkInterfaceAttached(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.NetworkInterfaceAttachment, error) { +func waitVPNGatewayCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnGateway, error) { + const ( + timeout = 10 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.AttachmentStatusAttaching}, - Target: []string{ec2.AttachmentStatusAttached}, - Timeout: timeout, - Refresh: StatusNetworkInterfaceAttachmentStatus(ctx, conn, id), + Pending: enum.Slice(awstypes.VpnStatePending), + Target: enum.Slice(awstypes.VpnStateAvailable), + Refresh: statusVPNGateway(ctx, conn, id), + Timeout: timeout, + Delay: 10 * time.Second, + MinTimeout: 10 * time.Second, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NetworkInterfaceAttachment); ok { + if output, ok := outputRaw.(*awstypes.VpnGateway); ok { return output, err } return nil, err } -func WaitNetworkInterfaceAvailableAfterUse(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.NetworkInterface, error) { - // Hyperplane attached ENI. - // Wait for it to be moved into a removable state. +func waitVPNGatewayDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnGateway, error) { + const ( + timeout = 10 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.NetworkInterfaceStatusInUse}, - Target: []string{ec2.NetworkInterfaceStatusAvailable}, + Pending: enum.Slice(awstypes.VpnStateDeleting), + Target: []string{}, + Refresh: statusVPNGateway(ctx, conn, id), Timeout: timeout, - Refresh: StatusNetworkInterfaceStatus(ctx, conn, id), Delay: 10 * time.Second, MinTimeout: 10 * time.Second, - // Handle EC2 ENI eventual consistency. It can take up to 3 minutes. - ContinuousTargetOccurence: 18, - NotFoundChecks: 1, } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NetworkInterface); ok { + if output, ok := outputRaw.(*awstypes.VpnGateway); ok { return output, err } return nil, err } -func WaitNetworkInterfaceCreated(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.NetworkInterface, error) { +func waitVPNGatewayVPCAttachmentAttached(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) (*awstypes.VpcAttachment, error) { //nolint:unparam + const ( + timeout = 15 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{NetworkInterfaceStatusPending}, - Target: []string{ec2.NetworkInterfaceStatusAvailable}, + Pending: enum.Slice(awstypes.AttachmentStatusAttaching), + Target: enum.Slice(awstypes.AttachmentStatusAttached), + Refresh: statusVPNGatewayVPCAttachment(ctx, conn, vpnGatewayID, vpcID), Timeout: timeout, - Refresh: StatusNetworkInterfaceStatus(ctx, conn, id), } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NetworkInterface); ok { + if output, ok := outputRaw.(*awstypes.VpcAttachment); ok { return output, err } return nil, err } -func WaitNetworkInterfaceDetached(ctx context.Context, conn *ec2.EC2, id string, timeout time.Duration) (*ec2.NetworkInterfaceAttachment, error) { +func waitVPNGatewayVPCAttachmentDetached(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) (*awstypes.VpcAttachment, error) { //nolint:unparam + const ( + timeout = 30 * time.Minute + ) stateConf := &retry.StateChangeConf{ - Pending: []string{ec2.AttachmentStatusAttached, ec2.AttachmentStatusDetaching}, - Target: []string{ec2.AttachmentStatusDetached}, + Pending: enum.Slice(awstypes.AttachmentStatusAttached, awstypes.AttachmentStatusDetaching), + Target: []string{}, + Refresh: statusVPNGatewayVPCAttachment(ctx, conn, vpnGatewayID, vpcID), Timeout: timeout, - Refresh: StatusNetworkInterfaceAttachmentStatus(ctx, conn, id), } outputRaw, err := stateConf.WaitForStateContext(ctx) - if output, ok := outputRaw.(*ec2.NetworkInterfaceAttachment); ok { + if output, ok := outputRaw.(*awstypes.VpcAttachment); ok { return output, err } diff --git a/internal/service/ec2/waitv2.go b/internal/service/ec2/waitv2.go deleted file mode 100644 index 8a7ea17b69b..00000000000 --- a/internal/service/ec2/waitv2.go +++ /dev/null @@ -1,2667 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package ec2 - -import ( - "context" - "errors" - "fmt" - "strconv" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/ec2" - awstypes "github.com/aws/aws-sdk-go-v2/service/ec2/types" - "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" - "github.com/hashicorp/terraform-provider-aws/internal/enum" - "github.com/hashicorp/terraform-provider-aws/internal/tfresource" -) - -const ( - AvailabilityZoneGroupOptInStatusTimeout = 10 * time.Minute -) - -func waitAvailabilityZoneGroupOptedIn(ctx context.Context, conn *ec2.Client, name string) (*awstypes.AvailabilityZone, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AvailabilityZoneOptInStatusNotOptedIn), - Target: enum.Slice(awstypes.AvailabilityZoneOptInStatusOptedIn), - Refresh: statusAvailabilityZoneGroupOptInStatus(ctx, conn, name), - Timeout: AvailabilityZoneGroupOptInStatusTimeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.AvailabilityZone); ok { - return output, err - } - - return nil, err -} - -func waitAvailabilityZoneGroupNotOptedIn(ctx context.Context, conn *ec2.Client, name string) (*awstypes.AvailabilityZone, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AvailabilityZoneOptInStatusOptedIn), - Target: enum.Slice(awstypes.AvailabilityZoneOptInStatusNotOptedIn), - Refresh: statusAvailabilityZoneGroupOptInStatus(ctx, conn, name), - Timeout: AvailabilityZoneGroupOptInStatusTimeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.AvailabilityZone); ok { - return output, err - } - - return nil, err -} - -func waitCapacityReservationActive(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CapacityReservation, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.CapacityReservationStatePending), - Target: enum.Slice(awstypes.CapacityReservationStateActive), - Refresh: statusCapacityReservation(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CapacityReservation); ok { - return output, err - } - - return nil, err -} - -func waitCapacityReservationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.CapacityReservation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.CapacityReservationStateActive), - Target: []string{}, - Refresh: statusCapacityReservation(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CapacityReservation); ok { - return output, err - } - - return nil, err -} - -func waitFleet(ctx context.Context, conn *ec2.Client, id string, pending, target []string, timeout, delay time.Duration) error { - stateConf := &retry.StateChangeConf{ - Pending: pending, - Target: target, - Refresh: statusFleet(ctx, conn, id), - Timeout: timeout, - Delay: delay, - MinTimeout: 1 * time.Second, - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitHostCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Host, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AllocationStatePending), - Target: enum.Slice(awstypes.AllocationStateAvailable), - Timeout: timeout, - Refresh: statusHost(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Host); ok { - return output, err - } - - return nil, err -} - -func waitHostUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Host, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AllocationStatePending), - Target: enum.Slice(awstypes.AllocationStateAvailable), - Timeout: timeout, - Refresh: statusHost(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Host); ok { - return output, err - } - - return nil, err -} - -func waitHostDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Host, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AllocationStateAvailable), - Target: []string{}, - Timeout: timeout, - Refresh: statusHost(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Host); ok { - return output, err - } - - return nil, err -} - -func waitInstanceIAMInstanceProfileUpdated(ctx context.Context, conn *ec2.Client, instanceID string, expectedValue string) (*awstypes.Instance, error) { - stateConf := &retry.StateChangeConf{ - Target: enum.Slice(expectedValue), - Refresh: statusInstanceIAMInstanceProfile(ctx, conn, instanceID), - Timeout: ec2PropagationTimeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Instance); ok { - return output, err - } - - return nil, err -} - -func waitInstanceCapacityReservationSpecificationUpdated(ctx context.Context, conn *ec2.Client, instanceID string, expectedValue *awstypes.CapacityReservationSpecification) (*awstypes.Instance, error) { - stateConf := &retry.StateChangeConf{ - Target: enum.Slice(strconv.FormatBool(true)), - Refresh: statusInstanceCapacityReservationSpecificationEquals(ctx, conn, instanceID, expectedValue), - Timeout: ec2PropagationTimeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Instance); ok { - return output, err - } - - return nil, err -} - -func waitInstanceMaintenanceOptionsAutoRecoveryUpdated(ctx context.Context, conn *ec2.Client, id, expectedValue string, timeout time.Duration) (*awstypes.InstanceMaintenanceOptions, error) { - stateConf := &retry.StateChangeConf{ - Target: enum.Slice(expectedValue), - Refresh: statusInstanceMaintenanceOptionsAutoRecovery(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.InstanceMaintenanceOptions); ok { - return output, err - } - - return nil, err -} - -func waitInstanceMetadataOptionsApplied(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.InstanceMetadataOptionsResponse, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.InstanceMetadataOptionsStatePending), - Target: enum.Slice(awstypes.InstanceMetadataOptionsStateApplied), - Refresh: statusInstanceMetadataOptions(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.InstanceMetadataOptionsResponse); ok { - return output, err - } - - return nil, err -} - -func waitInstanceRootBlockDeviceDeleteOnTerminationUpdated(ctx context.Context, conn *ec2.Client, id string, expectedValue bool, timeout time.Duration) (*awstypes.EbsInstanceBlockDevice, error) { - stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: statusInstanceRootBlockDeviceDeleteOnTermination(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.EbsInstanceBlockDevice); ok { - return output, err - } - - return nil, err -} - -const ( - PlacementGroupCreatedTimeout = 5 * time.Minute - PlacementGroupDeletedTimeout = 5 * time.Minute -) - -func waitPlacementGroupCreated(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PlacementGroup, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.PlacementGroupStatePending), - Target: enum.Slice(awstypes.PlacementGroupStateAvailable), - Timeout: PlacementGroupCreatedTimeout, - Refresh: statusPlacementGroup(ctx, conn, name), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.PlacementGroup); ok { - return output, err - } - - return nil, err -} - -func waitPlacementGroupDeleted(ctx context.Context, conn *ec2.Client, name string) (*awstypes.PlacementGroup, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.PlacementGroupStateDeleting), - Target: []string{}, - Timeout: PlacementGroupDeletedTimeout, - Refresh: statusPlacementGroup(ctx, conn, name), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.PlacementGroup); ok { - return output, err - } - - return nil, err -} - -func waitSpotInstanceRequestFulfilled(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotInstanceRequest, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{spotInstanceRequestStatusCodePendingEvaluation, spotInstanceRequestStatusCodePendingFulfillment}, - Target: []string{spotInstanceRequestStatusCodeFulfilled}, - Refresh: statusSpotInstanceRequest(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SpotInstanceRequest); ok { - if fault := output.Fault; fault != nil { - errFault := fmt.Errorf("%s: %s", aws.ToString(fault.Code), aws.ToString(fault.Message)) - tfresource.SetLastError(err, fmt.Errorf("%s %w", aws.ToString(output.Status.Message), errFault)) - } else { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - } - - return output, err - } - - return nil, err -} - -func waitVPCCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.Vpc, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpcStatePending), - Target: enum.Slice(awstypes.VpcStateAvailable), - Refresh: statusVPC(ctx, conn, id), - Timeout: vpcCreatedTimeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Vpc); ok { - return output, err - } - - return nil, err -} - -func waitVPCIPv6CIDRBlockAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcCidrBlockState, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociating, awstypes.VpcCidrBlockStateCodeDisassociated, awstypes.VpcCidrBlockStateCodeFailing), - Target: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociated), - Refresh: statusVPCIPv6CIDRBlockAssociation(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcCidrBlockState); ok { - if state := output.State; state == awstypes.VpcCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - } - - return output, err - } - - return nil, err -} - -func waitVPCIPv6CIDRBlockAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VpcCidrBlockState, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpcCidrBlockStateCodeAssociated, awstypes.VpcCidrBlockStateCodeDisassociating, awstypes.VpcCidrBlockStateCodeFailing), - Target: []string{}, - Refresh: statusVPCIPv6CIDRBlockAssociation(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcCidrBlockState); ok { - if state := output.State; state == awstypes.VpcCidrBlockStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - } - - return output, err - } - - return nil, err -} - -func waitVPCAttributeUpdated(ctx context.Context, conn *ec2.Client, vpcID string, attribute awstypes.VpcAttributeName, expectedValue bool) (*awstypes.Vpc, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Target: []string{strconv.FormatBool(expectedValue)}, - Refresh: statusVPCAttributeValue(ctx, conn, vpcID, attribute), - Timeout: ec2PropagationTimeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Vpc); ok { - return output, err - } - - return nil, err -} - -func waitNetworkInterfaceAvailableAfterUse(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterface, error) { - // Hyperplane attached ENI. - // Wait for it to be moved into a removable state. - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.NetworkInterfaceStatusInUse), - Target: enum.Slice(awstypes.NetworkInterfaceStatusAvailable), - Timeout: timeout, - Refresh: statusNetworkInterface(ctx, conn, id), - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, - // Handle EC2 ENI eventual consistency. It can take up to 3 minutes. - ContinuousTargetOccurence: 18, - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NetworkInterface); ok { - return output, err - } - - return nil, err -} - -func waitNetworkInterfaceCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterface, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{NetworkInterfaceStatusPending}, - Target: enum.Slice(awstypes.NetworkInterfaceStatusAvailable), - Timeout: timeout, - Refresh: statusNetworkInterface(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NetworkInterface); ok { - return output, err - } - - return nil, err -} - -func waitNetworkInterfaceAttached(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterfaceAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AttachmentStatusAttaching), - Target: enum.Slice(awstypes.AttachmentStatusAttached), - Timeout: timeout, - Refresh: statusNetworkInterfaceAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NetworkInterfaceAttachment); ok { - return output, err - } - - return nil, err -} - -func waitNetworkInterfaceDetached(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInterfaceAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AttachmentStatusAttached, awstypes.AttachmentStatusDetaching), - Target: enum.Slice(awstypes.AttachmentStatusDetached), - Timeout: timeout, - Refresh: statusNetworkInterfaceAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NetworkInterfaceAttachment); ok { - return output, err - } - - return nil, err -} - -func waitVolumeCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Volume, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VolumeStateCreating), - Target: enum.Slice(awstypes.VolumeStateAvailable), - Refresh: statusVolume(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Volume); ok { - return output, err - } - - return nil, err -} - -func waitVolumeDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Volume, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VolumeStateDeleting), - Target: []string{}, - Refresh: statusVolume(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Volume); ok { - return output, err - } - - return nil, err -} - -func waitVolumeUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Volume, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VolumeStateCreating, awstypes.VolumeState(awstypes.VolumeModificationStateModifying)), - Target: enum.Slice(awstypes.VolumeStateAvailable, awstypes.VolumeStateInUse), - Refresh: statusVolume(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Volume); ok { - return output, err - } - - return nil, err -} - -func waitVolumeAttachmentCreated(ctx context.Context, conn *ec2.Client, volumeID, instanceID, deviceName string, timeout time.Duration) (*awstypes.VolumeAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VolumeAttachmentStateAttaching), - Target: enum.Slice(awstypes.VolumeAttachmentStateAttached), - Refresh: statusVolumeAttachment(ctx, conn, volumeID, instanceID, deviceName), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VolumeAttachment); ok { - return output, err - } - - return nil, err -} - -func waitVolumeModificationComplete(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VolumeModification, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VolumeModificationStateModifying), - // The volume is useable once the state is "optimizing", but will not be at full performance. - // Optimization can take hours. e.g. a full 1 TiB drive takes approximately 6 hours to optimize, - // according to https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-modifications.html. - Target: enum.Slice(awstypes.VolumeModificationStateCompleted, awstypes.VolumeModificationStateOptimizing), - Refresh: statusVolumeModification(ctx, conn, id), - Timeout: timeout, - Delay: 30 * time.Second, - MinTimeout: 30 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VolumeModification); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - - return output, err - } - - return nil, err -} - -func waitVPCEndpointAccepted(ctx context.Context, conn *ec2.Client, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(vpcEndpointStatePendingAcceptance), - Target: enum.Slice(vpcEndpointStateAvailable), - Timeout: timeout, - Refresh: statusVPCEndpoint(ctx, conn, vpcEndpointID), - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { - if state, lastError := output.State, output.LastError; state == awstypes.StateFailed && lastError != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(lastError.Code), aws.ToString(lastError.Message))) - } - - return output, err - } - - return nil, err -} - -func waitVPCEndpointAvailable(ctx context.Context, conn *ec2.Client, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(vpcEndpointStatePending), - Target: enum.Slice(vpcEndpointStateAvailable, vpcEndpointStatePendingAcceptance), - Timeout: timeout, - Refresh: statusVPCEndpoint(ctx, conn, vpcEndpointID), - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { - if state, lastError := output.State, output.LastError; state == awstypes.StateFailed && lastError != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(lastError.Code), aws.ToString(lastError.Message))) - } - - return output, err - } - - return nil, err -} - -func waitVPCEndpointDeleted(ctx context.Context, conn *ec2.Client, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(vpcEndpointStateDeleting, vpcEndpointStateDeleted), - Target: []string{}, - Refresh: statusVPCEndpoint(ctx, conn, vpcEndpointID), - Timeout: timeout, - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcEndpoint); ok { - return output, err - } - - return nil, err -} - -func waitRouteDeleted(ctx context.Context, conn *ec2.Client, routeFinder routeFinder, routeTableID, destination string, timeout time.Duration) (*awstypes.Route, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: []string{routeStatusReady}, - Target: []string{}, - Refresh: statusRoute(ctx, conn, routeFinder, routeTableID, destination), - Timeout: timeout, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Route); ok { - return output, err - } - - return nil, err -} - -func waitRouteReady(ctx context.Context, conn *ec2.Client, routeFinder routeFinder, routeTableID, destination string, timeout time.Duration) (*awstypes.Route, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: []string{}, - Target: []string{routeStatusReady}, - Refresh: statusRoute(ctx, conn, routeFinder, routeTableID, destination), - Timeout: timeout, - NotFoundChecks: RouteNotFoundChecks, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Route); ok { - return output, err - } - - return nil, err -} - -func waitRouteTableReady(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTable, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{}, - Target: []string{routeTableStatusReady}, - Refresh: statusRouteTable(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: RouteTableNotFoundChecks, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.RouteTable); ok { - return output, err - } - - return nil, err -} - -func waitRouteTableDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTable, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{routeTableStatusReady}, - Target: []string{}, - Refresh: statusRouteTable(ctx, conn, id), - Timeout: timeout, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.RouteTable); ok { - return output, err - } - - return nil, err -} - -func waitRouteTableAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTableAssociationState, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociating), - Target: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociated), - Refresh: statusRouteTableAssociation(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: RouteTableAssociationCreatedNotFoundChecks, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.RouteTableAssociationState); ok { - if output.State == awstypes.RouteTableAssociationStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - } - - return output, err - } - - return nil, err -} - -func waitRouteTableAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTableAssociationState, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeDisassociating, awstypes.RouteTableAssociationStateCodeAssociated), - Target: []string{}, - Refresh: statusRouteTableAssociation(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.RouteTableAssociationState); ok { - if output.State == awstypes.RouteTableAssociationStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - } - - return output, err - } - - return nil, err -} - -func waitRouteTableAssociationUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.RouteTableAssociationState, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociating), - Target: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociated), - Refresh: statusRouteTableAssociation(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.RouteTableAssociationState); ok { - if output.State == awstypes.RouteTableAssociationStateCodeFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - } - - return output, err - } - - return nil, err -} - -func waitSpotFleetRequestCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotFleetRequestConfig, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.BatchStateSubmitted), - Target: enum.Slice(awstypes.BatchStateActive), - Refresh: statusSpotFleetRequest(ctx, conn, id), - Timeout: timeout, - MinTimeout: 10 * time.Second, - Delay: 30 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SpotFleetRequestConfig); ok { - return output, err - } - - return nil, err -} - -func waitSpotFleetRequestFulfilled(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotFleetRequestConfig, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ActivityStatusPendingFulfillment), - Target: enum.Slice(awstypes.ActivityStatusFulfilled), - Refresh: statusSpotFleetActivityStatus(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SpotFleetRequestConfig); ok { - if output.ActivityStatus == awstypes.ActivityStatusError { - var errs []error - - input := &ec2.DescribeSpotFleetRequestHistoryInput{ - SpotFleetRequestId: aws.String(id), - StartTime: aws.Time(time.UnixMilli(0)), - } - - if output, err := findSpotFleetRequestHistoryRecords(ctx, conn, input); err == nil { - for _, v := range output { - if eventType := v.EventType; eventType == awstypes.EventTypeError || eventType == awstypes.EventTypeInformation { - errs = append(errs, errors.New(aws.ToString(v.EventInformation.EventDescription))) - } - } - } - - tfresource.SetLastError(err, errors.Join(errs...)) - } - - return output, err - } - - return nil, err -} - -func waitSpotFleetRequestUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SpotFleetRequestConfig, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.BatchStateModifying), - Target: enum.Slice(awstypes.BatchStateActive), - Refresh: statusSpotFleetRequest(ctx, conn, id), - Timeout: timeout, - MinTimeout: 10 * time.Second, - Delay: 30 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SpotFleetRequestConfig); ok { - return output, err - } - - return nil, err -} - -func waitVPCEndpointServiceAvailable(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.ServiceConfiguration, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ServiceStatePending), - Target: enum.Slice(awstypes.ServiceStateAvailable), - Refresh: statusVPCEndpointServiceAvailable(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.ServiceConfiguration); ok { - return output, err - } - - return nil, err -} - -func waitVPCEndpointServiceDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.ServiceConfiguration, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ServiceStateAvailable, awstypes.ServiceStateDeleting), - Target: []string{}, - Timeout: timeout, - Refresh: fetchVPCEndpointServiceDeletionStatus(ctx, conn, id), - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.ServiceConfiguration); ok { - return output, err - } - - return nil, err -} - -func waitVPCEndpointRouteTableAssociationReady(ctx context.Context, conn *ec2.Client, vpcEndpointID, routeTableID string) error { - stateConf := &retry.StateChangeConf{ - Pending: []string{}, - Target: enum.Slice(VPCEndpointRouteTableAssociationStatusReady), - Refresh: statusVPCEndpointRouteTableAssociation(ctx, conn, vpcEndpointID, routeTableID), - Timeout: ec2PropagationTimeout, - ContinuousTargetOccurence: 2, - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitVPCEndpointRouteTableAssociationDeleted(ctx context.Context, conn *ec2.Client, vpcEndpointID, routeTableID string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(VPCEndpointRouteTableAssociationStatusReady), - Target: []string{}, - Refresh: statusVPCEndpointRouteTableAssociation(ctx, conn, vpcEndpointID, routeTableID), - Timeout: ec2PropagationTimeout, - ContinuousTargetOccurence: 2, - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitVPCEndpointConnectionAccepted(ctx context.Context, conn *ec2.Client, serviceID, vpcEndpointID string, timeout time.Duration) (*awstypes.VpcEndpointConnection, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{vpcEndpointStatePendingAcceptance, vpcEndpointStatePending}, - Target: []string{vpcEndpointStateAvailable}, - Refresh: statusVPCEndpointConnectionVPCEndpoint(ctx, conn, serviceID, vpcEndpointID), - Timeout: timeout, - Delay: 5 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcEndpointConnection); ok { - return output, err - } - - return nil, err -} - -func waitVPCEndpointServicePrivateDNSNameVerified(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.PrivateDnsNameConfiguration, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.DnsNameStatePendingVerification), - Target: enum.Slice(awstypes.DnsNameStateVerified), - Refresh: statusVPCEndpointServicePrivateDNSNameConfiguration(ctx, conn, id), - Timeout: timeout, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - if out, ok := outputRaw.(*awstypes.PrivateDnsNameConfiguration); ok { - return out, err - } - - return nil, err -} - -func waitClientVPNEndpointDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ClientVpnEndpoint, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ClientVpnEndpointStatusCodeDeleting), - Target: []string{}, - Refresh: statusClientVPNEndpoint(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.ClientVpnEndpoint); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNEndpointClientConnectResponseOptionsUpdated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.ClientConnectResponseOptions, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ClientVpnEndpointAttributeStatusCodeApplying), - Target: enum.Slice(awstypes.ClientVpnEndpointAttributeStatusCodeApplied), - Refresh: statusClientVPNEndpointClientConnectResponseOptions(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.ClientConnectResponseOptions); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNAuthorizationRuleCreated(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string, timeout time.Duration) (*awstypes.AuthorizationRule, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ClientVpnAuthorizationRuleStatusCodeAuthorizing), - Target: enum.Slice(awstypes.ClientVpnAuthorizationRuleStatusCodeActive), - Refresh: statusClientVPNAuthorizationRule(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.AuthorizationRule); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNAuthorizationRuleDeleted(ctx context.Context, conn *ec2.Client, endpointID, targetNetworkCIDR, accessGroupID string, timeout time.Duration) (*awstypes.AuthorizationRule, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ClientVpnAuthorizationRuleStatusCodeRevoking), - Target: []string{}, - Refresh: statusClientVPNAuthorizationRule(ctx, conn, endpointID, targetNetworkCIDR, accessGroupID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.AuthorizationRule); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNNetworkAssociationCreated(ctx context.Context, conn *ec2.Client, associationID, endpointID string, timeout time.Duration) (*awstypes.TargetNetwork, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AssociationStatusCodeAssociating), - Target: enum.Slice(awstypes.AssociationStatusCodeAssociated), - Refresh: statusClientVPNNetworkAssociation(ctx, conn, associationID, endpointID), - Timeout: timeout, - Delay: 4 * time.Minute, - PollInterval: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TargetNetwork); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNNetworkAssociationDeleted(ctx context.Context, conn *ec2.Client, associationID, endpointID string, timeout time.Duration) (*awstypes.TargetNetwork, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AssociationStatusCodeDisassociating), - Target: []string{}, - Refresh: statusClientVPNNetworkAssociation(ctx, conn, associationID, endpointID), - Timeout: timeout, - Delay: 4 * time.Minute, - PollInterval: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TargetNetwork); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNRouteCreated(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string, timeout time.Duration) (*awstypes.ClientVpnRoute, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ClientVpnRouteStatusCodeCreating), - Target: enum.Slice(awstypes.ClientVpnRouteStatusCodeActive), - Refresh: statusClientVPNRoute(ctx, conn, endpointID, targetSubnetID, destinationCIDR), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.ClientVpnRoute); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitClientVPNRouteDeleted(ctx context.Context, conn *ec2.Client, endpointID, targetSubnetID, destinationCIDR string, timeout time.Duration) (*awstypes.ClientVpnRoute, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ClientVpnRouteStatusCodeActive, awstypes.ClientVpnRouteStatusCodeDeleting), - Target: []string{}, - Refresh: statusClientVPNRoute(ctx, conn, endpointID, targetSubnetID, destinationCIDR), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.ClientVpnRoute); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitCarrierGatewayCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CarrierGateway, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.CarrierGatewayStatePending), - Target: enum.Slice(awstypes.CarrierGatewayStateAvailable), - Refresh: statusCarrierGateway(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CarrierGateway); ok { - return output, err - } - - return nil, err -} - -func waitCarrierGatewayDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CarrierGateway, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.CarrierGatewayStateDeleting), - Target: []string{}, - Refresh: statusCarrierGateway(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CarrierGateway); ok { - return output, err - } - - return nil, err -} - -func waitImageAvailable(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Image, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ImageStatePending), - Target: enum.Slice(awstypes.ImageStateAvailable), - Refresh: statusImage(ctx, conn, id), - Timeout: timeout, - Delay: amiRetryDelay, - MinTimeout: amiRetryMinTimeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Image); ok { - if stateReason := output.StateReason; stateReason != nil { - tfresource.SetLastError(err, errors.New(aws.ToString(stateReason.Message))) - } - - return output, err - } - - return nil, err -} - -func waitImageDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Image, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.ImageStateAvailable, awstypes.ImageStateFailed, awstypes.ImageStatePending), - Target: []string{}, - Refresh: statusImage(ctx, conn, id), - Timeout: timeout, - Delay: amiRetryDelay, - MinTimeout: amiRetryMinTimeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Image); ok { - if stateReason := output.StateReason; stateReason != nil { - tfresource.SetLastError(err, errors.New(aws.ToString(stateReason.Message))) - } - - return output, err - } - - return nil, err -} - -func waitImageBlockPublicAccessState(ctx context.Context, conn *ec2.Client, target string, timeout time.Duration) error { - stateConf := &retry.StateChangeConf{ - Target: []string{target}, - Refresh: statusImageBlockPublicAccess(ctx, conn), - Timeout: timeout, - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitVPNConnectionCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { - const ( - timeout = 40 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpnStatePending), - Target: enum.Slice(awstypes.VpnStateAvailable), - Refresh: statusVPNConnection(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnConnection); ok { - return output, err - } - - return nil, err -} - -func waitVPNConnectionUpdated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { //nolint:unparam - const ( - timeout = 30 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(vpnStateModifying), - Target: enum.Slice(awstypes.VpnStateAvailable), - Refresh: statusVPNConnection(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnConnection); ok { - return output, err - } - - return nil, err -} - -func waitVPNConnectionDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnConnection, error) { - const ( - timeout = 30 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpnStateDeleting), - Target: []string{}, - Refresh: statusVPNConnection(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnConnection); ok { - return output, err - } - - return nil, err -} - -func waitVPNConnectionRouteCreated(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) (*awstypes.VpnStaticRoute, error) { - const ( - timeout = 15 * time.Second - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpnStatePending), - Target: enum.Slice(awstypes.VpnStateAvailable), - Refresh: statusVPNConnectionRoute(ctx, conn, vpnConnectionID, cidrBlock), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnStaticRoute); ok { - return output, err - } - - return nil, err -} - -func waitVPNConnectionRouteDeleted(ctx context.Context, conn *ec2.Client, vpnConnectionID, cidrBlock string) (*awstypes.VpnStaticRoute, error) { - const ( - timeout = 15 * time.Second - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpnStatePending, awstypes.VpnStateAvailable, awstypes.VpnStateDeleting), - Target: []string{}, - Refresh: statusVPNConnectionRoute(ctx, conn, vpnConnectionID, cidrBlock), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnStaticRoute); ok { - return output, err - } - - return nil, err -} - -func waitVPNGatewayCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnGateway, error) { - const ( - timeout = 10 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpnStatePending), - Target: enum.Slice(awstypes.VpnStateAvailable), - Refresh: statusVPNGateway(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnGateway); ok { - return output, err - } - - return nil, err -} - -func waitVPNGatewayDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.VpnGateway, error) { - const ( - timeout = 10 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VpnStateDeleting), - Target: []string{}, - Refresh: statusVPNGateway(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpnGateway); ok { - return output, err - } - - return nil, err -} - -func waitVPNGatewayVPCAttachmentAttached(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) (*awstypes.VpcAttachment, error) { //nolint:unparam - const ( - timeout = 15 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AttachmentStatusAttaching), - Target: enum.Slice(awstypes.AttachmentStatusAttached), - Refresh: statusVPNGatewayVPCAttachment(ctx, conn, vpnGatewayID, vpcID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcAttachment); ok { - return output, err - } - - return nil, err -} - -func waitVPNGatewayVPCAttachmentDetached(ctx context.Context, conn *ec2.Client, vpnGatewayID, vpcID string) (*awstypes.VpcAttachment, error) { //nolint:unparam - const ( - timeout = 30 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AttachmentStatusAttached, awstypes.AttachmentStatusDetaching), - Target: []string{}, - Refresh: statusVPNGatewayVPCAttachment(ctx, conn, vpnGatewayID, vpcID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VpcAttachment); ok { - return output, err - } - - return nil, err -} - -func waitCustomerGatewayCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CustomerGateway, error) { - const ( - timeout = 10 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(CustomerGatewayStatePending), - Target: enum.Slice(CustomerGatewayStateAvailable), - Refresh: statusCustomerGateway(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - MinTimeout: 3 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CustomerGateway); ok { - return output, err - } - - return nil, err -} - -func waitCustomerGatewayDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.CustomerGateway, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(CustomerGatewayStateAvailable, CustomerGatewayStateDeleting), - Target: []string{}, - Refresh: statusCustomerGateway(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.CustomerGateway); ok { - return output, err - } - - return nil, err -} - -func waitIPAMCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ipam, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamStateCreateInProgress), - Target: enum.Slice(awstypes.IpamStateCreateComplete), - Refresh: statusIPAM(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Ipam); ok { - return output, err - } - - return nil, err -} - -func waitIPAMUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ipam, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamStateModifyInProgress), - Target: enum.Slice(awstypes.IpamStateModifyComplete), - Refresh: statusIPAM(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Ipam); ok { - return output, err - } - - return nil, err -} - -func waitIPAMDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ipam, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamStateCreateComplete, awstypes.IpamStateModifyComplete, awstypes.IpamStateDeleteInProgress), - Target: []string{}, - Refresh: statusIPAM(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Ipam); ok { - return output, err - } - - return nil, err -} - -func waitIPAMPoolCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamPool, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamPoolStateCreateInProgress), - Target: enum.Slice(awstypes.IpamPoolStateCreateComplete), - Refresh: statusIPAMPool(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamPool); ok { - if state := output.State; state == awstypes.IpamPoolStateCreateFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) - } - - return output, err - } - - return nil, err -} - -func waitIPAMPoolUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamPool, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamPoolStateModifyInProgress), - Target: enum.Slice(awstypes.IpamPoolStateModifyComplete), - Refresh: statusIPAMPool(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamPool); ok { - if state := output.State; state == awstypes.IpamPoolStateModifyFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) - } - - return output, err - } - - return nil, err -} - -func waitIPAMPoolDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamPool, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamPoolStateDeleteInProgress), - Target: []string{}, - Refresh: statusIPAMPool(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamPool); ok { - if state := output.State; state == awstypes.IpamPoolStateDeleteFailed { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) - } - - return output, err - } - - return nil, err -} - -func waitIPAMPoolCIDRCreated(ctx context.Context, conn *ec2.Client, poolCIDRID, poolID, cidrBlock string, timeout time.Duration) (*awstypes.IpamPoolCidr, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamPoolCidrStatePendingProvision), - Target: enum.Slice(awstypes.IpamPoolCidrStateProvisioned), - Refresh: statusIPAMPoolCIDR(ctx, conn, cidrBlock, poolID, poolCIDRID), - Timeout: timeout, - Delay: 5 * time.Second, - NotFoundChecks: 1000, // Should exceed any reasonable custom timeout value. - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamPoolCidr); ok { - if state, failureReason := output.State, output.FailureReason; state == awstypes.IpamPoolCidrStateFailedProvision && failureReason != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", string(failureReason.Code), aws.ToString(failureReason.Message))) - } - - return output, err - } - - return nil, err -} - -func waitIPAMPoolCIDRDeleted(ctx context.Context, conn *ec2.Client, poolCIDRID, poolID, cidrBlock string, timeout time.Duration) (*awstypes.IpamPoolCidr, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamPoolCidrStatePendingDeprovision, awstypes.IpamPoolCidrStateProvisioned), - Target: []string{}, - Refresh: statusIPAMPoolCIDR(ctx, conn, cidrBlock, poolID, poolCIDRID), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamPoolCidr); ok { - if state, failureReason := output.State, output.FailureReason; state == awstypes.IpamPoolCidrStateFailedDeprovision && failureReason != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", string(failureReason.Code), aws.ToString(failureReason.Message))) - } - - return output, err - } - - return nil, err -} - -func waitIPAMResourceDiscoveryCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscovery, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamResourceDiscoveryStateCreateInProgress), - Target: enum.Slice(awstypes.IpamResourceDiscoveryStateCreateComplete), - Refresh: statusIPAMResourceDiscovery(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamResourceDiscovery); ok { - return output, err - } - - return nil, err -} - -func waitIPAMResourceDiscoveryUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscovery, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamResourceDiscoveryStateModifyInProgress), - Target: enum.Slice(awstypes.IpamResourceDiscoveryStateModifyComplete), - Refresh: statusIPAMResourceDiscovery(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamResourceDiscovery); ok { - return output, err - } - - return nil, err -} - -func waitIPAMResourceDiscoveryDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscovery, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamResourceDiscoveryStateCreateComplete, awstypes.IpamResourceDiscoveryStateModifyComplete, awstypes.IpamResourceDiscoveryStateDeleteInProgress), - Target: []string{}, - Refresh: statusIPAMResourceDiscovery(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamResourceDiscovery); ok { - return output, err - } - - return nil, err -} - -func waitIPAMResourceDiscoveryAssociationCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscoveryAssociation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamResourceDiscoveryAssociationStateAssociateInProgress), - Target: enum.Slice(awstypes.IpamResourceDiscoveryAssociationStateAssociateComplete), - Refresh: statusIPAMResourceDiscoveryAssociation(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamResourceDiscoveryAssociation); ok { - return output, err - } - - return nil, err -} - -func waitIPAMResourceDiscoveryAssociationDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamResourceDiscoveryAssociation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamResourceDiscoveryAssociationStateAssociateComplete, awstypes.IpamResourceDiscoveryAssociationStateDisassociateInProgress), - Target: []string{}, - Refresh: statusIPAMResourceDiscoveryAssociation(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamResourceDiscoveryAssociation); ok { - return output, err - } - - return nil, err -} - -func waitIPAMScopeCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamScope, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamScopeStateCreateInProgress), - Target: enum.Slice(awstypes.IpamScopeStateCreateComplete), - Refresh: statusIPAMScope(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamScope); ok { - return output, err - } - - return nil, err -} - -func waitIPAMScopeUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamScope, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamScopeStateModifyInProgress), - Target: enum.Slice(awstypes.IpamScopeStateModifyComplete), - Refresh: statusIPAMScope(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamScope); ok { - return output, err - } - - return nil, err -} - -func waitIPAMScopeDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.IpamScope, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.IpamScopeStateCreateComplete, awstypes.IpamScopeStateModifyComplete, awstypes.IpamScopeStateDeleteInProgress), - Target: []string{}, - Refresh: statusIPAMScope(ctx, conn, id), - Timeout: timeout, - Delay: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.IpamScope); ok { - return output, err - } - - return nil, err -} - -func waitLocalGatewayRouteDeleted(ctx context.Context, conn *ec2.Client, localGatewayRouteTableID, destinationCIDRBlock string) (*awstypes.LocalGatewayRoute, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.LocalGatewayRouteStateDeleting), - Target: []string{}, - Refresh: statusLocalGatewayRoute(ctx, conn, localGatewayRouteTableID, destinationCIDRBlock), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.LocalGatewayRoute); ok { - return output, err - } - - return nil, err -} - -func waitLocalGatewayRouteTableVPCAssociationAssociated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociating), - Target: enum.Slice(awstypes.RouteTableAssociationStateCodeAssociated), - Refresh: statusLocalGatewayRouteTableVPCAssociation(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.LocalGatewayRouteTableVpcAssociation); ok { - return output, err - } - - return nil, err -} - -func waitLocalGatewayRouteTableVPCAssociationDisassociated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.LocalGatewayRouteTableVpcAssociation, error) { - const ( - timeout = 5 * time.Minute - ) - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.RouteTableAssociationStateCodeDisassociating), - Target: []string{}, - Refresh: statusLocalGatewayRouteTableVPCAssociation(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.LocalGatewayRouteTableVpcAssociation); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGateway, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayStatePending), - Target: enum.Slice(awstypes.TransitGatewayStateAvailable), - Refresh: statusTransitGateway(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGateway); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGateway, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayStateAvailable, awstypes.TransitGatewayStateDeleting), - Target: []string{}, - Refresh: statusTransitGateway(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGateway); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGateway, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayStateModifying), - Target: enum.Slice(awstypes.TransitGatewayStateAvailable), - Refresh: statusTransitGateway(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGateway); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayConnectCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnect, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStatePending), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), - Refresh: statusTransitGatewayConnect(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayConnect); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayConnectDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnect, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable, awstypes.TransitGatewayAttachmentStateDeleting), - Target: []string{}, - Refresh: statusTransitGatewayConnect(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayConnect); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayConnectPeerCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnectPeer, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayConnectPeerStatePending), - Target: enum.Slice(awstypes.TransitGatewayConnectPeerStateAvailable), - Refresh: statusTransitGatewayConnectPeer(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayConnectPeer); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayConnectPeerDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayConnectPeer, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayConnectPeerStateAvailable, awstypes.TransitGatewayConnectPeerStateDeleting), - Target: []string{}, - Refresh: statusTransitGatewayConnectPeer(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayConnectPeer); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayMulticastDomainCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomain, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayMulticastDomainStatePending), - Target: enum.Slice(awstypes.TransitGatewayMulticastDomainStateAvailable), - Refresh: statusTransitGatewayMulticastDomain(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomain); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayMulticastDomainDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomain, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayMulticastDomainStateAvailable, awstypes.TransitGatewayMulticastDomainStateDeleting), - Target: []string{}, - Refresh: statusTransitGatewayMulticastDomain(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomain); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayMulticastDomainAssociationCreated(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AssociationStatusCodeAssociating), - Target: enum.Slice(awstypes.AssociationStatusCodeAssociated), - Refresh: statusTransitGatewayMulticastDomainAssociation(ctx, conn, multicastDomainID, attachmentID, subnetID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomainAssociation); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayMulticastDomainAssociationDeleted(ctx context.Context, conn *ec2.Client, multicastDomainID, attachmentID, subnetID string, timeout time.Duration) (*awstypes.TransitGatewayMulticastDomainAssociation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AssociationStatusCodeAssociated, awstypes.AssociationStatusCodeDisassociating), - Target: []string{}, - Refresh: statusTransitGatewayMulticastDomainAssociation(ctx, conn, multicastDomainID, attachmentID, subnetID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayMulticastDomainAssociation); ok { - return output, err - } - - return nil, err -} - -const ( - TransitGatewayPeeringAttachmentCreatedTimeout = 10 * time.Minute - TransitGatewayPeeringAttachmentDeletedTimeout = 10 * time.Minute - TransitGatewayPeeringAttachmentUpdatedTimeout = 10 * time.Minute -) - -func waitTransitGatewayPeeringAttachmentAccepted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPeeringAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStatePending, awstypes.TransitGatewayAttachmentStatePendingAcceptance), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), - Timeout: TransitGatewayPeeringAttachmentUpdatedTimeout, - Refresh: statusTransitGatewayPeeringAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPeeringAttachment); ok { - if status := output.Status; status != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(status.Code), aws.ToString(status.Message))) - } - - return output, err - } - - return nil, err -} - -func waitTransitGatewayPeeringAttachmentCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPeeringAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateFailing, awstypes.TransitGatewayAttachmentStateInitiatingRequest, awstypes.TransitGatewayAttachmentStatePending), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable, awstypes.TransitGatewayAttachmentStatePendingAcceptance), - Timeout: TransitGatewayPeeringAttachmentCreatedTimeout, - Refresh: statusTransitGatewayPeeringAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPeeringAttachment); ok { - if status := output.Status; status != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(status.Code), aws.ToString(status.Message))) - } - - return output, err - } - - return nil, err -} - -func waitTransitGatewayPeeringAttachmentDeleted(ctx context.Context, conn *ec2.Client, id string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice( - awstypes.TransitGatewayAttachmentStateAvailable, - awstypes.TransitGatewayAttachmentStateDeleting, - awstypes.TransitGatewayAttachmentStatePendingAcceptance, - awstypes.TransitGatewayAttachmentStateRejecting, - ), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateDeleted), - Timeout: TransitGatewayPeeringAttachmentDeletedTimeout, - Refresh: statusTransitGatewayPeeringAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPeeringAttachment); ok { - if status := output.Status; status != nil { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", aws.ToString(status.Code), aws.ToString(status.Message))) - } - } - - return err -} - -const ( - TransitGatewayPrefixListReferenceTimeout = 5 * time.Minute -) - -func waitTransitGatewayPrefixListReferenceStateCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStatePending), - Target: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateAvailable), - Timeout: TransitGatewayPrefixListReferenceTimeout, - Refresh: statusTransitGatewayPrefixListReference(ctx, conn, transitGatewayRouteTableID, prefixListID), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPrefixListReference); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayPrefixListReferenceStateDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateDeleting), - Target: []string{}, - Timeout: TransitGatewayPrefixListReferenceTimeout, - Refresh: statusTransitGatewayPrefixListReference(ctx, conn, transitGatewayRouteTableID, prefixListID), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPrefixListReference); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayPrefixListReferenceStateUpdated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, prefixListID string) (*awstypes.TransitGatewayPrefixListReference, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateModifying), - Target: enum.Slice(awstypes.TransitGatewayPrefixListReferenceStateAvailable), - Timeout: TransitGatewayPrefixListReferenceTimeout, - Refresh: statusTransitGatewayPrefixListReference(ctx, conn, transitGatewayRouteTableID, prefixListID), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPrefixListReference); ok { - return output, err - } - - return nil, err -} - -const ( - TransitGatewayRouteCreatedTimeout = 2 * time.Minute - TransitGatewayRouteDeletedTimeout = 2 * time.Minute -) - -func waitTransitGatewayRouteCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) (*awstypes.TransitGatewayRoute, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayRouteStatePending), - Target: enum.Slice(awstypes.TransitGatewayRouteStateActive, awstypes.TransitGatewayRouteStateBlackhole), - Timeout: TransitGatewayRouteCreatedTimeout, - Refresh: statusTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayRoute); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayRouteDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, destination string) (*awstypes.TransitGatewayRoute, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayRouteStateActive, awstypes.TransitGatewayRouteStateBlackhole, awstypes.TransitGatewayRouteStateDeleting), - Target: []string{}, - Timeout: TransitGatewayRouteDeletedTimeout, - Refresh: statusTransitGatewayStaticRoute(ctx, conn, transitGatewayRouteTableID, destination), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayRoute); ok { - return output, err - } - - return nil, err -} - -const ( - TransitGatewayRouteTableCreatedTimeout = 10 * time.Minute - TransitGatewayRouteTableDeletedTimeout = 10 * time.Minute - TransitGatewayPolicyTableCreatedTimeout = 10 * time.Minute - TransitGatewayPolicyTableDeletedTimeout = 10 * time.Minute -) - -func waitTransitGatewayPolicyTableCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPolicyTable, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPolicyTableStatePending), - Target: enum.Slice(awstypes.TransitGatewayPolicyTableStateAvailable), - Timeout: TransitGatewayPolicyTableCreatedTimeout, - Refresh: statusTransitGatewayPolicyTable(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTable); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayRouteTableCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayRouteTable, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayRouteTableStatePending), - Target: enum.Slice(awstypes.TransitGatewayRouteTableStateAvailable), - Timeout: TransitGatewayRouteTableCreatedTimeout, - Refresh: statusTransitGatewayRouteTable(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayRouteTable); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayPolicyTableDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayPolicyTable, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPolicyTableStateAvailable, awstypes.TransitGatewayPolicyTableStateDeleting), - Target: []string{}, - Timeout: TransitGatewayPolicyTableDeletedTimeout, - Refresh: statusTransitGatewayPolicyTable(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTable); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayRouteTableDeleted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayRouteTable, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayRouteTableStateAvailable, awstypes.TransitGatewayRouteTableStateDeleting), - Target: []string{}, - Timeout: TransitGatewayRouteTableDeletedTimeout, - Refresh: statusTransitGatewayRouteTable(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayRouteTable); ok { - return output, err - } - - return nil, err -} - -const ( - TransitGatewayPolicyTableAssociationCreatedTimeout = 5 * time.Minute - TransitGatewayPolicyTableAssociationDeletedTimeout = 10 * time.Minute - TransitGatewayRouteTableAssociationCreatedTimeout = 5 * time.Minute - TransitGatewayRouteTableAssociationDeletedTimeout = 10 * time.Minute -) - -func waitTransitGatewayPolicyTableAssociationCreated(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayPolicyTableAssociation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociating), - Target: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated), - Timeout: TransitGatewayPolicyTableAssociationCreatedTimeout, - Refresh: statusTransitGatewayPolicyTableAssociation(ctx, conn, transitGatewayPolicyTableID, transitGatewayAttachmentID), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTableAssociation); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayPolicyTableAssociationDeleted(ctx context.Context, conn *ec2.Client, transitGatewayPolicyTableID, transitGatewayAttachmentID string) (*awstypes.TransitGatewayPolicyTableAssociation, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated, awstypes.TransitGatewayAssociationStateDisassociating), - Target: []string{}, - Timeout: TransitGatewayPolicyTableAssociationDeletedTimeout, - Refresh: statusTransitGatewayPolicyTableAssociation(ctx, conn, transitGatewayPolicyTableID, transitGatewayAttachmentID), - NotFoundChecks: 1, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayPolicyTableAssociation); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayRouteTableAssociationCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociating), - Target: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated), - Timeout: TransitGatewayRouteTableAssociationCreatedTimeout, - Refresh: statusTransitGatewayRouteTableAssociation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitTransitGatewayRouteTableAssociationDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID, transitGatewayAttachmentID string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAssociationStateAssociated, awstypes.TransitGatewayAssociationStateDisassociating), - Target: []string{}, - Timeout: TransitGatewayRouteTableAssociationDeletedTimeout, - Refresh: statusTransitGatewayRouteTableAssociation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), - NotFoundChecks: 1, - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -const ( - TransitGatewayRouteTablePropagationCreatedTimeout = 5 * time.Minute - TransitGatewayRouteTablePropagationDeletedTimeout = 5 * time.Minute -) - -func waitTransitGatewayRouteTablePropagationCreated(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPropagationStateEnabling), - Target: enum.Slice(awstypes.TransitGatewayPropagationStateEnabled), - Timeout: TransitGatewayRouteTablePropagationCreatedTimeout, - Refresh: statusTransitGatewayRouteTablePropagation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitTransitGatewayRouteTablePropagationDeleted(ctx context.Context, conn *ec2.Client, transitGatewayRouteTableID string, transitGatewayAttachmentID string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayPropagationStateDisabling), - Target: []string{}, - Timeout: TransitGatewayRouteTablePropagationDeletedTimeout, - Refresh: statusTransitGatewayRouteTablePropagation(ctx, conn, transitGatewayRouteTableID, transitGatewayAttachmentID), - } - - _, err := stateConf.WaitForStateContext(ctx) - - if tfawserr.ErrCodeEquals(err, errCodeInvalidRouteTableIDNotFound) { - return nil - } - - return err -} - -const ( - TransitGatewayVPCAttachmentCreatedTimeout = 10 * time.Minute - TransitGatewayVPCAttachmentDeletedTimeout = 10 * time.Minute - TransitGatewayVPCAttachmentUpdatedTimeout = 10 * time.Minute -) - -func waitTransitGatewayVPCAttachmentAccepted(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStatePending, awstypes.TransitGatewayAttachmentStatePendingAcceptance), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), - Timeout: TransitGatewayVPCAttachmentUpdatedTimeout, - Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayVpcAttachment); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayVPCAttachmentCreated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateFailing, awstypes.TransitGatewayAttachmentStatePending), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable, awstypes.TransitGatewayAttachmentStatePendingAcceptance), - Timeout: TransitGatewayVPCAttachmentCreatedTimeout, - Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayVpcAttachment); ok { - return output, err - } - - return nil, err -} - -func waitTransitGatewayVPCAttachmentDeleted(ctx context.Context, conn *ec2.Client, id string) error { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice( - awstypes.TransitGatewayAttachmentStateAvailable, - awstypes.TransitGatewayAttachmentStateDeleting, - awstypes.TransitGatewayAttachmentStatePendingAcceptance, - awstypes.TransitGatewayAttachmentStateRejecting, - ), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateDeleted), - Timeout: TransitGatewayVPCAttachmentDeletedTimeout, - Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), - } - - _, err := stateConf.WaitForStateContext(ctx) - - return err -} - -func waitTransitGatewayVPCAttachmentUpdated(ctx context.Context, conn *ec2.Client, id string) (*awstypes.TransitGatewayVpcAttachment, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.TransitGatewayAttachmentStateModifying), - Target: enum.Slice(awstypes.TransitGatewayAttachmentStateAvailable), - Timeout: TransitGatewayVPCAttachmentUpdatedTimeout, - Refresh: statusTransitGatewayVPCAttachment(ctx, conn, id), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.TransitGatewayVpcAttachment); ok { - return output, err - } - - return nil, err -} - -func waitEIPDomainNameAttributeUpdated(ctx context.Context, conn *ec2.Client, allocationID string, timeout time.Duration) (*awstypes.AddressAttribute, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{PTRUpdateStatusPending}, - Target: []string{""}, - Timeout: timeout, - Refresh: statusEIPDomainNameAttribute(ctx, conn, allocationID), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.AddressAttribute); ok { - if v := output.PtrRecordUpdate; v != nil { - tfresource.SetLastError(err, errors.New(aws.ToString(v.Reason))) - } - - return output, err - } - - return nil, err -} - -func waitEIPDomainNameAttributeDeleted(ctx context.Context, conn *ec2.Client, allocationID string, timeout time.Duration) (*awstypes.AddressAttribute, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{PTRUpdateStatusPending}, - Target: []string{}, - Timeout: timeout, - Refresh: statusEIPDomainNameAttribute(ctx, conn, allocationID), - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.AddressAttribute); ok { - if v := output.PtrRecordUpdate; v != nil { - tfresource.SetLastError(err, errors.New(aws.ToString(v.Reason))) - } - - return output, err - } - - return nil, err -} - -func waitEBSSnapshotImportComplete(ctx context.Context, conn *ec2.Client, importTaskID string, timeout time.Duration) (*awstypes.SnapshotTaskDetail, error) { - stateConf := &retry.StateChangeConf{ - Pending: []string{ - EBSSnapshotImportStateActive, - EBSSnapshotImportStateUpdating, - EBSSnapshotImportStateValidating, - EBSSnapshotImportStateValidated, - EBSSnapshotImportStateConverting, - }, - Target: []string{EBSSnapshotImportStateCompleted}, - Refresh: statusEBSSnapshotImport(ctx, conn, importTaskID), - Timeout: timeout, - Delay: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SnapshotTaskDetail); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - - return output, err - } - - return nil, err -} - -const ( - ebsSnapshotArchivedTimeout = 60 * time.Minute -) - -func waitEBSSnapshotTierArchive(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.SnapshotTierStatus, error) { //nolint:unparam - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(TargetStorageTierStandard), - Target: enum.Slice(awstypes.TargetStorageTierArchive), - Refresh: statusSnapshotStorageTier(ctx, conn, id), - Timeout: timeout, - Delay: 10 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.SnapshotTierStatus); ok { - tfresource.SetLastError(err, fmt.Errorf("%s: %s", string(output.LastTieringOperationStatus), aws.ToString(output.LastTieringOperationStatusDetail))) - - return output, err - } - - return nil, err -} - -func waitInstanceConnectEndpointCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ec2InstanceConnectEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.Ec2InstanceConnectEndpointStateCreateInProgress), - Target: enum.Slice(awstypes.Ec2InstanceConnectEndpointStateCreateComplete), - Refresh: statusInstanceConnectEndpoint(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Ec2InstanceConnectEndpoint); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) - - return output, err - } - - return nil, err -} - -func waitInstanceConnectEndpointDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.Ec2InstanceConnectEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.Ec2InstanceConnectEndpointStateDeleteInProgress), - Target: []string{}, - Refresh: statusInstanceConnectEndpoint(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.Ec2InstanceConnectEndpoint); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StateMessage))) - - return output, err - } - - return nil, err -} - -func waitVerifiedAccessEndpointCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VerifiedAccessEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodePending), - Target: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeActive), - Refresh: statusVerifiedAccessEndpoint(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: 20, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VerifiedAccessEndpoint); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitVerifiedAccessEndpointUpdated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VerifiedAccessEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeUpdating), - Target: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeActive), - Refresh: statusVerifiedAccessEndpoint(ctx, conn, id), - Timeout: timeout, - NotFoundChecks: 20, - ContinuousTargetOccurence: 2, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VerifiedAccessEndpoint); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitVerifiedAccessEndpointDeleted(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.VerifiedAccessEndpoint, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.VerifiedAccessEndpointStatusCodeDeleting, awstypes.VerifiedAccessEndpointStatusCodeActive, awstypes.VerifiedAccessEndpointStatusCodeDeleted), - Target: []string{}, - Refresh: statusVerifiedAccessEndpoint(ctx, conn, id), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.VerifiedAccessEndpoint); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.Status.Message))) - - return output, err - } - - return nil, err -} - -func waitFastSnapshotRestoreCreated(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string, timeout time.Duration) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.FastSnapshotRestoreStateCodeEnabling, awstypes.FastSnapshotRestoreStateCodeOptimizing), - Target: enum.Slice(awstypes.FastSnapshotRestoreStateCodeEnabled), - Refresh: statusFastSnapshotRestore(ctx, conn, availabilityZone, snapshotID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.DescribeFastSnapshotRestoreSuccessItem); ok { - return output, err - } - - return nil, err -} - -func waitFastSnapshotRestoreDeleted(ctx context.Context, conn *ec2.Client, availabilityZone, snapshotID string, timeout time.Duration) (*awstypes.DescribeFastSnapshotRestoreSuccessItem, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.FastSnapshotRestoreStateCodeDisabling, awstypes.FastSnapshotRestoreStateCodeOptimizing, awstypes.FastSnapshotRestoreStateCodeEnabled), - Target: []string{}, - Refresh: statusFastSnapshotRestore(ctx, conn, availabilityZone, snapshotID), - Timeout: timeout, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.DescribeFastSnapshotRestoreSuccessItem); ok { - return output, err - } - - return nil, err -} - -func waitNetworkInsightsAnalysisCreated(ctx context.Context, conn *ec2.Client, id string, timeout time.Duration) (*awstypes.NetworkInsightsAnalysis, error) { - stateConf := &retry.StateChangeConf{ - Pending: enum.Slice(awstypes.AnalysisStatusRunning), - Target: enum.Slice(awstypes.AnalysisStatusSucceeded), - Timeout: timeout, - Refresh: statusNetworkInsightsAnalysis(ctx, conn, id), - Delay: 10 * time.Second, - MinTimeout: 5 * time.Second, - } - - outputRaw, err := stateConf.WaitForStateContext(ctx) - - if output, ok := outputRaw.(*awstypes.NetworkInsightsAnalysis); ok { - tfresource.SetLastError(err, errors.New(aws.ToString(output.StatusMessage))) - - return output, err - } - - return nil, err -} diff --git a/internal/service/ec2/wavelength_carrier_gateway.go b/internal/service/ec2/wavelength_carrier_gateway.go index f62726d4e62..aa08a339d2f 100644 --- a/internal/service/ec2/wavelength_carrier_gateway.go +++ b/internal/service/ec2/wavelength_carrier_gateway.go @@ -66,7 +66,7 @@ func resourceCarrierGatewayCreate(ctx context.Context, d *schema.ResourceData, m input := &ec2.CreateCarrierGatewayInput{ ClientToken: aws.String(id.UniqueId()), - TagSpecifications: getTagSpecificationsInV2(ctx, awstypes.ResourceTypeCarrierGateway), + TagSpecifications: getTagSpecificationsIn(ctx, awstypes.ResourceTypeCarrierGateway), VpcId: aws.String(d.Get(names.AttrVPCID).(string)), } @@ -78,7 +78,7 @@ func resourceCarrierGatewayCreate(ctx context.Context, d *schema.ResourceData, m d.SetId(aws.ToString(output.CarrierGateway.CarrierGatewayId)) - if _, err := waitCarrierGatewayCreated(ctx, conn, d.Id()); err != nil { + if _, err := waitCarrierGatewayCreated(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Carrier Gateway (%s) create: %s", d.Id(), err) } @@ -113,7 +113,7 @@ func resourceCarrierGatewayRead(ctx context.Context, d *schema.ResourceData, met d.Set(names.AttrOwnerID, ownerID) d.Set(names.AttrVPCID, carrierGateway.VpcId) - setTagsOutV2(ctx, carrierGateway.Tags) + setTagsOut(ctx, carrierGateway.Tags) return diags } @@ -143,7 +143,7 @@ func resourceCarrierGatewayDelete(ctx context.Context, d *schema.ResourceData, m return sdkdiag.AppendErrorf(diags, "deleting EC2 Carrier Gateway (%s): %s", d.Id(), err) } - if _, err := waitCarrierGatewayDeleted(ctx, conn, d.Id()); err != nil { + if _, err := waitCarrierGatewayDeleted(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { return sdkdiag.AppendErrorf(diags, "waiting for EC2 Carrier Gateway (%s) delete: %s", d.Id(), err) } diff --git a/internal/service/ec2/wavelength_carrier_gateway_test.go b/internal/service/ec2/wavelength_carrier_gateway_test.go index 1a6611a62bb..5a0eb0108e1 100644 --- a/internal/service/ec2/wavelength_carrier_gateway_test.go +++ b/internal/service/ec2/wavelength_carrier_gateway_test.go @@ -178,7 +178,7 @@ func testAccPreCheckWavelengthZoneAvailable(ctx context.Context, t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) input := &ec2.DescribeAvailabilityZonesInput{ - Filters: tfec2.NewAttributeFilterListV2(map[string]string{ + Filters: tfec2.NewAttributeFilterList(map[string]string{ "zone-type": "wavelength-zone", "opt-in-status": "opted-in", }), diff --git a/internal/service/efs/mount_target.go b/internal/service/efs/mount_target.go index fd99607f686..d6f27c5a712 100644 --- a/internal/service/efs/mount_target.go +++ b/internal/service/efs/mount_target.go @@ -11,9 +11,9 @@ import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/efs" awstypes "github.com/aws/aws-sdk-go-v2/service/efs/types" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -111,7 +111,7 @@ func resourceMountTargetCreate(ctx context.Context, d *schema.ResourceData, meta // and we would end up managing the same MT as 2 resources. // So we make it fail by calling 1 request per AZ at a time. subnetID := d.Get(names.AttrSubnetID).(string) - az, err := getAZFromSubnetID(ctx, meta.(*conns.AWSClient).EC2Conn(ctx), subnetID) + az, err := getAZFromSubnetID(ctx, meta.(*conns.AWSClient).EC2Client(ctx), subnetID) if err != nil { return sdkdiag.AppendErrorf(diags, "reading EC2 Subnet (%s): %s", subnetID, err) @@ -242,7 +242,7 @@ func resourceMountTargetDelete(ctx context.Context, d *schema.ResourceData, meta return diags } -func getAZFromSubnetID(ctx context.Context, conn *ec2.EC2, subnetID string) (string, error) { +func getAZFromSubnetID(ctx context.Context, conn *ec2.Client, subnetID string) (string, error) { subnet, err := tfec2.FindSubnetByID(ctx, conn, subnetID) if err != nil { diff --git a/internal/service/elasticbeanstalk/environment.go b/internal/service/elasticbeanstalk/environment.go index 366b7756e78..0a8fc305e6b 100644 --- a/internal/service/elasticbeanstalk/environment.go +++ b/internal/service/elasticbeanstalk/environment.go @@ -15,10 +15,10 @@ import ( // nosemgrep:ci.semgrep.aws.multiple-service-imports "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk" awstypes "github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk/types" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" + "github.com/hashicorp/aws-sdk-go-base/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -400,7 +400,7 @@ func resourceEnvironmentRead(ctx context.Context, d *schema.ResourceData, meta i if value := aws.ToString(optionSetting.Value); value != "" { switch aws.ToString(optionSetting.OptionName) { case "SecurityGroups": - m[names.AttrValue] = dropGeneratedSecurityGroup(ctx, meta.(*conns.AWSClient).EC2Conn(ctx), value) + m[names.AttrValue] = dropGeneratedSecurityGroup(ctx, meta.(*conns.AWSClient).EC2Client(ctx), value) case "Subnets", "ELBSubnets": m[names.AttrValue] = sortValues(value) default: @@ -838,9 +838,9 @@ func extractOptionSettings(s *schema.Set) []awstypes.ConfigurationOptionSetting return settings } -func dropGeneratedSecurityGroup(ctx context.Context, conn *ec2.EC2, settingValue string) string { +func dropGeneratedSecurityGroup(ctx context.Context, conn *ec2.Client, settingValue string) string { input := &ec2.DescribeSecurityGroupsInput{ - GroupIds: aws.StringSlice(strings.Split(settingValue, ",")), + GroupIds: strings.Split(settingValue, ","), } securityGroup, err := tfec2.FindSecurityGroups(ctx, conn, input) diff --git a/internal/service/elasticbeanstalk/environment_test.go b/internal/service/elasticbeanstalk/environment_test.go index 23dd8a13ebc..db86e396059 100644 --- a/internal/service/elasticbeanstalk/environment_test.go +++ b/internal/service/elasticbeanstalk/environment_test.go @@ -445,10 +445,10 @@ func TestAccElasticBeanstalkEnvironment_platformARN(t *testing.T) { var app awstypes.EnvironmentDescription rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_elastic_beanstalk_environment.test" - platformNameWithVersion1 := "Python 3.8 running on 64bit Amazon Linux 2/3.5.12" + platformNameWithVersion1 := "Python 3.8 running on 64bit Amazon Linux 2/3.7.0" rValue1 := sdkacctest.RandIntRange(1000, 2000) rValue1Str := strconv.Itoa(rValue1) - platformNameWithVersion2 := "Python 3.9 running on 64bit Amazon Linux 2023/4.0.9" + platformNameWithVersion2 := "Python 3.9 running on 64bit Amazon Linux 2023/4.1.1" rValue2 := sdkacctest.RandIntRange(3000, 4000) rValue2Str := strconv.Itoa(rValue2) diff --git a/internal/service/elb/load_balancer.go b/internal/service/elb/load_balancer.go index 3b7f02d9263..24bc3a45088 100644 --- a/internal/service/elb/load_balancer.go +++ b/internal/service/elb/load_balancer.go @@ -378,7 +378,7 @@ func resourceLoadBalancerRead(ctx context.Context, d *schema.ResourceData, meta // Manually look up the ELB Security Group ID, since it's not provided if lb.VPCId != nil { - sg, err := tfec2.FindSecurityGroupByNameAndVPCIDAndOwnerID(ctx, meta.(*conns.AWSClient).EC2Conn(ctx), aws.ToString(lb.SourceSecurityGroup.GroupName), aws.ToString(lb.VPCId), aws.ToString(lb.SourceSecurityGroup.OwnerAlias)) + sg, err := tfec2.FindSecurityGroupByNameAndVPCIDAndOwnerID(ctx, meta.(*conns.AWSClient).EC2Client(ctx), aws.ToString(lb.SourceSecurityGroup.GroupName), aws.ToString(lb.VPCId), aws.ToString(lb.SourceSecurityGroup.OwnerAlias)) if err != nil { return sdkdiag.AppendErrorf(diags, "reading ELB Classic Load Balancer (%s) security group: %s", d.Id(), err) } else { diff --git a/internal/service/elb/load_balancer_data_source.go b/internal/service/elb/load_balancer_data_source.go index 7b716e00ff7..67028c5a79a 100644 --- a/internal/service/elb/load_balancer_data_source.go +++ b/internal/service/elb/load_balancer_data_source.go @@ -204,7 +204,7 @@ func dataSourceLoadBalancer() *schema.Resource { func dataSourceLoadBalancerRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { var diags diag.Diagnostics conn := meta.(*conns.AWSClient).ELBClient(ctx) - ec2conn := meta.(*conns.AWSClient).EC2Conn(ctx) + ec2conn := meta.(*conns.AWSClient).EC2Client(ctx) ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig lbName := d.Get(names.AttrName).(string) diff --git a/internal/service/emr/cluster_test.go b/internal/service/emr/cluster_test.go index 069fc986466..a9a34eb5350 100644 --- a/internal/service/emr/cluster_test.go +++ b/internal/service/emr/cluster_test.go @@ -9,9 +9,10 @@ import ( "testing" "github.com/YakDriver/regexache" + "github.com/aws/aws-sdk-go-v2/service/ec2" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/emr" sdkacctest "github.com/hashicorp/terraform-plugin-testing/helper/acctest" "github.com/hashicorp/terraform-plugin-testing/helper/resource" @@ -541,7 +542,7 @@ func TestAccEMRCluster_CoreInstanceGroup_name(t *testing.T) { func TestAccEMRCluster_EC2Attributes_defaultManagedSecurityGroups(t *testing.T) { ctx := acctest.Context(t) var cluster emr.Cluster - var vpc ec2.Vpc + var vpc ec2types.Vpc rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_emr_cluster.test" @@ -567,7 +568,7 @@ func TestAccEMRCluster_EC2Attributes_defaultManagedSecurityGroups(t *testing.T) }, { PreConfig: func() { - conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Conn(ctx) + conn := acctest.Provider.Meta().(*conns.AWSClient).EC2Client(ctx) err := testAccDeleteManagedSecurityGroups(ctx, conn, &vpc) @@ -1823,9 +1824,9 @@ func testAccCheckClusterRecreated(i, j *emr.Cluster) resource.TestCheckFunc { } } -func testAccDeleteManagedSecurityGroups(ctx context.Context, conn *ec2.EC2, vpc *ec2.Vpc) error { +func testAccDeleteManagedSecurityGroups(ctx context.Context, conn *ec2.Client, vpc *ec2types.Vpc) error { // Reference: https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-man-sec-groups.html - managedSecurityGroups := map[string]*ec2.SecurityGroup{ + managedSecurityGroups := map[string]*ec2types.SecurityGroup{ "ElasticMapReduce-master": nil, "ElasticMapReduce-slave": nil, } @@ -1869,23 +1870,23 @@ func testAccDeleteManagedSecurityGroups(ctx context.Context, conn *ec2.EC2, vpc return nil } -func testAccRevokeManagedSecurityGroup(ctx context.Context, conn *ec2.EC2, securityGroup *ec2.SecurityGroup) error { +func testAccRevokeManagedSecurityGroup(ctx context.Context, conn *ec2.Client, securityGroup *ec2types.SecurityGroup) error { input := &ec2.RevokeSecurityGroupIngressInput{ GroupId: securityGroup.GroupId, IpPermissions: securityGroup.IpPermissions, } - _, err := conn.RevokeSecurityGroupIngressWithContext(ctx, input) + _, err := conn.RevokeSecurityGroupIngress(ctx, input) return err } -func testAccDeleteManagedSecurityGroup(ctx context.Context, conn *ec2.EC2, securityGroup *ec2.SecurityGroup) error { +func testAccDeleteManagedSecurityGroup(ctx context.Context, conn *ec2.Client, securityGroup *ec2types.SecurityGroup) error { input := &ec2.DeleteSecurityGroupInput{ GroupId: securityGroup.GroupId, } - _, err := conn.DeleteSecurityGroupWithContext(ctx, input) + _, err := conn.DeleteSecurityGroup(ctx, input) return err } @@ -2178,14 +2179,18 @@ EOF func testAccClusterConfig_Step(rName string, stepConfig string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true log_uri = "s3://${aws_s3_bucket.test.bucket}/" name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn termination_protection = false master_instance_group { @@ -2200,13 +2205,17 @@ resource "aws_emr_cluster" "test" { ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } %[2]s - depends_on = [aws_route_table_association.test] + depends_on = [ + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + ] } resource "aws_s3_bucket" "test" { @@ -2544,6 +2553,8 @@ EOF func testAccClusterConfig_coreInstanceGroupAutoScalingPolicy(rName, autoscalingPolicy string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` data "aws_partition" "current" {} @@ -2578,12 +2589,12 @@ resource "aws_emr_cluster" "test" { keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2601,6 +2612,8 @@ POLICY depends_on = [ aws_route_table_association.test, aws_iam_role_policy_attachment.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, ] } `, rName, autoscalingPolicy)) @@ -2609,6 +2622,8 @@ POLICY func testAccClusterConfig_coreInstanceGroupAutoScalingPolicyRemoved(rName string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` data "aws_partition" "current" {} @@ -2643,12 +2658,12 @@ resource "aws_emr_cluster" "test" { keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2663,6 +2678,8 @@ resource "aws_emr_cluster" "test" { depends_on = [ aws_route_table_association.test, aws_iam_role_policy_attachment.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, ] } `, rName)) @@ -2671,18 +2688,22 @@ resource "aws_emr_cluster" "test" { func testAccClusterConfig_coreInstanceGroupBidPrice(rName, bidPrice string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2695,7 +2716,11 @@ resource "aws_emr_cluster" "test" { instance_type = "m4.large" } - depends_on = [aws_route_table_association.test] + depends_on = [ + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + ] } `, rName, bidPrice)) } @@ -2703,18 +2728,22 @@ resource "aws_emr_cluster" "test" { func testAccClusterConfig_coreInstanceGroupInstanceCount(rName string, instanceCount int) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2727,7 +2756,11 @@ resource "aws_emr_cluster" "test" { instance_type = "m4.large" } - depends_on = [aws_route_table_association.test] + depends_on = [ + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + ] } `, rName, instanceCount)) } @@ -2735,18 +2768,22 @@ resource "aws_emr_cluster" "test" { func testAccClusterConfig_coreInstanceGroupInstanceType(rName, instanceType string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2758,7 +2795,11 @@ resource "aws_emr_cluster" "test" { instance_type = %[2]q } - depends_on = [aws_route_table_association.test] + depends_on = [ + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + ] } `, rName, instanceType)) } @@ -2766,18 +2807,22 @@ resource "aws_emr_cluster" "test" { func testAccClusterConfig_coreInstanceGroupName(rName, instanceGroupName string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { emr_managed_master_security_group = aws_security_group.test.id emr_managed_slave_security_group = aws_security_group.test.id - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2790,7 +2835,11 @@ resource "aws_emr_cluster" "test" { name = %[2]q } - depends_on = [aws_route_table_association.test] + depends_on = [ + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + ] } `, rName, instanceGroupName)) } @@ -2798,16 +2847,20 @@ resource "aws_emr_cluster" "test" { func testAccClusterConfig_ec2AttributesDefaultManagedSecurityGroups(rName string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.33.1" - service_role = "EMR_DefaultRole" + service_role = aws_iam_role.emr_service.arn ec2_attributes { - instance_profile = "EMR_EC2_DefaultRole" + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn subnet_id = aws_subnet.test.id } @@ -2815,7 +2868,11 @@ resource "aws_emr_cluster" "test" { instance_type = "m4.large" } - depends_on = [aws_route_table_association.test] + depends_on = [ + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + ] } `, rName)) } @@ -2823,7 +2880,11 @@ resource "aws_emr_cluster" "test" { func testAccClusterConfig_kerberosDedicatedKdc(rName string, password string) string { return acctest.ConfigCompose( testAccClusterConfig_baseVPC(rName, false), + testAccClusterConfig_baseIAMServiceRole(rName), + testAccClusterConfig_baseIAMInstanceProfile(rName), fmt.Sprintf(` +data "aws_partition" "current" {} + resource "aws_emr_security_configuration" "test" { configuration = <