From 5b118d8cea8bd7707d6b74bd4d3de652850524ee Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 6 Oct 2021 17:32:59 -0700 Subject: [PATCH 1/3] Adds Semgrep rule to prevent unneeded type conversion of literal numbers --- .semgrep.yml | 14 ++++++++++++++ internal/service/acmpca/sweep.go | 2 +- internal/service/autoscaling/flex_test.go | 4 ++-- internal/service/autoscaling/group.go | 4 ++-- internal/service/batch/job_definition_test.go | 10 +++++----- .../distribution_configuration_structure.go | 2 +- internal/service/codepipeline/webhook.go | 2 +- internal/service/cognitoidentity/pool_test.go | 2 +- internal/service/cognitoidp/sweep.go | 4 ++-- internal/service/cognitoidp/user_pool_test.go | 2 +- .../service/cognitoidp/user_pools_data_source.go | 2 +- internal/service/directconnect/lag.go | 4 ++-- internal/service/ec2/flex_test.go | 16 ++++++++-------- internal/service/ec2/host.go | 2 +- internal/service/ec2/instance.go | 6 +++--- internal/service/ec2/security_group.go | 8 ++++---- internal/service/ec2/security_group_rule_test.go | 16 ++++++++-------- internal/service/ec2/security_group_test.go | 14 +++++++------- internal/service/ec2/spot_fleet_request.go | 2 +- internal/service/ecs/service.go | 2 +- internal/service/elasticsearch/domain_test.go | 2 +- internal/service/elb/flex_test.go | 12 ++++++------ internal/service/elb/load_balancer_test.go | 10 +++++----- internal/service/kms/grant.go | 2 +- internal/service/kms/sweep.go | 2 +- internal/service/ram/resource_share_accepter.go | 2 +- .../service/redshift/snapshot_copy_grant_test.go | 2 +- internal/service/route53/zone_test.go | 2 +- 28 files changed, 83 insertions(+), 69 deletions(-) diff --git a/.semgrep.yml b/.semgrep.yml index f053a706c86..990eb25d85a 100644 --- a/.semgrep.yml +++ b/.semgrep.yml @@ -638,3 +638,17 @@ rules: patterns: - pattern: 'if d.HasChangeExcept("tags_all") {...}' severity: WARNING + + - id: unnecessary-literal-type-conversion + languages: [go] + message: Literal numbers do not need type conversions + paths: + include: + - internal/ + patterns: + - pattern: "aws.Int64(int64($X))" + - metavariable-regex: + metavariable: $X + regex: (\d+) + severity: ERROR + fix: "aws.Int64($X)" diff --git a/internal/service/acmpca/sweep.go b/internal/service/acmpca/sweep.go index e165c349098..37461bbd9a4 100644 --- a/internal/service/acmpca/sweep.go +++ b/internal/service/acmpca/sweep.go @@ -68,7 +68,7 @@ func sweepCertificateAuthorities(region string) error { log.Printf("[INFO] Deleting ACM PCA Certificate Authority: %s", arn) _, err := conn.DeleteCertificateAuthority(&acmpca.DeleteCertificateAuthorityInput{ CertificateAuthorityArn: aws.String(arn), - PermanentDeletionTimeInDays: aws.Int64(int64(7)), + PermanentDeletionTimeInDays: aws.Int64(7), }) if tfawserr.ErrMessageContains(err, acmpca.ErrCodeResourceNotFoundException, "") { continue diff --git a/internal/service/autoscaling/flex_test.go b/internal/service/autoscaling/flex_test.go index ba0a389206d..86b142ae673 100644 --- a/internal/service/autoscaling/flex_test.go +++ b/internal/service/autoscaling/flex_test.go @@ -45,7 +45,7 @@ func TestExpandStepAdjustments(t *testing.T) { expected := &autoscaling.StepAdjustment{ MetricIntervalLowerBound: aws.Float64(1.0), MetricIntervalUpperBound: aws.Float64(2.0), - ScalingAdjustment: aws.Int64(int64(1)), + ScalingAdjustment: aws.Int64(1), } if !reflect.DeepEqual(parameters[0], expected) { @@ -61,7 +61,7 @@ func TestFlattenStepAdjustments(t *testing.T) { { MetricIntervalLowerBound: aws.Float64(1.0), MetricIntervalUpperBound: aws.Float64(2.5), - ScalingAdjustment: aws.Int64(int64(1)), + ScalingAdjustment: aws.Int64(1), }, } diff --git a/internal/service/autoscaling/group.go b/internal/service/autoscaling/group.go index e6d19ae5f03..db8ffe825d4 100644 --- a/internal/service/autoscaling/group.go +++ b/internal/service/autoscaling/group.go @@ -661,8 +661,8 @@ func resourceGroupCreate(d *schema.ResourceData, meta interface{}) error { maxSize := aws.Int64(int64(d.Get("max_size").(int))) if twoPhases { - createOpts.MinSize = aws.Int64(int64(0)) - createOpts.MaxSize = aws.Int64(int64(0)) + createOpts.MinSize = aws.Int64(0) + createOpts.MaxSize = aws.Int64(0) updateOpts.MinSize = minSize updateOpts.MaxSize = maxSize diff --git a/internal/service/batch/job_definition_test.go b/internal/service/batch/job_definition_test.go index 4f299a1933e..12726ef28f5 100644 --- a/internal/service/batch/job_definition_test.go +++ b/internal/service/batch/job_definition_test.go @@ -200,14 +200,14 @@ func TestAccBatchJobDefinition_ContainerProperties_advanced(t *testing.T) { "param2": aws.String("val2"), }, RetryStrategy: &batch.RetryStrategy{ - Attempts: aws.Int64(int64(1)), + Attempts: aws.Int64(1), EvaluateOnExit: []*batch.EvaluateOnExit{ {Action: aws.String(strings.ToLower(batch.RetryActionRetry)), OnStatusReason: aws.String("Host EC2*")}, {Action: aws.String(strings.ToLower(batch.RetryActionExit)), OnReason: aws.String("*")}, }, }, Timeout: &batch.JobTimeout{ - AttemptDurationSeconds: aws.Int64(int64(60)), + AttemptDurationSeconds: aws.Int64(60), }, ContainerProperties: &batch.ContainerProperties{ Command: []*string{aws.String("ls"), aws.String("-la")}, @@ -215,16 +215,16 @@ func TestAccBatchJobDefinition_ContainerProperties_advanced(t *testing.T) { {Name: aws.String("VARNAME"), Value: aws.String("VARVAL")}, }, Image: aws.String("busybox"), - Memory: aws.Int64(int64(512)), + Memory: aws.Int64(512), MountPoints: []*batch.MountPoint{ {ContainerPath: aws.String("/tmp"), ReadOnly: aws.Bool(false), SourceVolume: aws.String("tmp")}, }, ResourceRequirements: []*batch.ResourceRequirement{}, Secrets: []*batch.Secret{}, Ulimits: []*batch.Ulimit{ - {HardLimit: aws.Int64(int64(1024)), Name: aws.String("nofile"), SoftLimit: aws.Int64(int64(1024))}, + {HardLimit: aws.Int64(1024), Name: aws.String("nofile"), SoftLimit: aws.Int64(1024)}, }, - Vcpus: aws.Int64(int64(1)), + Vcpus: aws.Int64(1), Volumes: []*batch.Volume{ { Host: &batch.Host{SourcePath: aws.String("/tmp")}, diff --git a/internal/service/cloudfront/distribution_configuration_structure.go b/internal/service/cloudfront/distribution_configuration_structure.go index 97841978d0a..57b2595d2f6 100644 --- a/internal/service/cloudfront/distribution_configuration_structure.go +++ b/internal/service/cloudfront/distribution_configuration_structure.go @@ -1238,7 +1238,7 @@ func flattenRestrictions(r *cloudfront.Restrictions) []interface{} { func ExpandGeoRestriction(m map[string]interface{}) *cloudfront.GeoRestriction { gr := &cloudfront.GeoRestriction{ - Quantity: aws.Int64(int64(0)), + Quantity: aws.Int64(0), RestrictionType: aws.String(m["restriction_type"].(string)), } diff --git a/internal/service/codepipeline/webhook.go b/internal/service/codepipeline/webhook.go index e5fadd568a9..b91c07a5db3 100644 --- a/internal/service/codepipeline/webhook.go +++ b/internal/service/codepipeline/webhook.go @@ -174,7 +174,7 @@ func GetWebhook(conn *codepipeline.CodePipeline, arn string) (*codepipeline.List for { input := &codepipeline.ListWebhooksInput{ - MaxResults: aws.Int64(int64(60)), + MaxResults: aws.Int64(60), } if nextToken != "" { input.NextToken = aws.String(nextToken) diff --git a/internal/service/cognitoidentity/pool_test.go b/internal/service/cognitoidentity/pool_test.go index 76f2419de32..fe97d6d0147 100644 --- a/internal/service/cognitoidentity/pool_test.go +++ b/internal/service/cognitoidentity/pool_test.go @@ -372,7 +372,7 @@ func testAccPreCheck(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIdentityConn input := &cognitoidentity.ListIdentityPoolsInput{ - MaxResults: aws.Int64(int64(1)), + MaxResults: aws.Int64(1), } _, err := conn.ListIdentityPools(input) diff --git a/internal/service/cognitoidp/sweep.go b/internal/service/cognitoidp/sweep.go index a535af6558f..d4a06f34f38 100644 --- a/internal/service/cognitoidp/sweep.go +++ b/internal/service/cognitoidp/sweep.go @@ -37,7 +37,7 @@ func sweepUserPoolDomains(region string) error { conn := client.(*conns.AWSClient).CognitoIDPConn input := &cognitoidentityprovider.ListUserPoolsInput{ - MaxResults: aws.Int64(int64(50)), + MaxResults: aws.Int64(50), } err = conn.ListUserPoolsPages(input, func(resp *cognitoidentityprovider.ListUserPoolsOutput, lastPage bool) bool { @@ -89,7 +89,7 @@ func sweepUserPools(region string) error { conn := client.(*conns.AWSClient).CognitoIDPConn input := &cognitoidentityprovider.ListUserPoolsInput{ - MaxResults: aws.Int64(int64(50)), + MaxResults: aws.Int64(50), } err = conn.ListUserPoolsPages(input, func(resp *cognitoidentityprovider.ListUserPoolsOutput, lastPage bool) bool { diff --git a/internal/service/cognitoidp/user_pool_test.go b/internal/service/cognitoidp/user_pool_test.go index 6e9014a6db4..701f4d20fb6 100644 --- a/internal/service/cognitoidp/user_pool_test.go +++ b/internal/service/cognitoidp/user_pool_test.go @@ -1473,7 +1473,7 @@ func testAccPreCheckIdentityProvider(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIDPConn input := &cognitoidentityprovider.ListUserPoolsInput{ - MaxResults: aws.Int64(int64(1)), + MaxResults: aws.Int64(1), } _, err := conn.ListUserPools(input) diff --git a/internal/service/cognitoidp/user_pools_data_source.go b/internal/service/cognitoidp/user_pools_data_source.go index 59feea792a0..0c29cc0e82a 100644 --- a/internal/service/cognitoidp/user_pools_data_source.go +++ b/internal/service/cognitoidp/user_pools_data_source.go @@ -76,7 +76,7 @@ func getAllCognitoUserPools(conn *cognitoidentityprovider.CognitoIdentityProvide for { input := &cognitoidentityprovider.ListUserPoolsInput{ // MaxResults Valid Range: Minimum value of 1. Maximum value of 60 - MaxResults: aws.Int64(int64(60)), + MaxResults: aws.Int64(60), } if nextToken != "" { input.NextToken = aws.String(nextToken) diff --git a/internal/service/directconnect/lag.go b/internal/service/directconnect/lag.go index 2fdc5195250..3270a0d6ec8 100644 --- a/internal/service/directconnect/lag.go +++ b/internal/service/directconnect/lag.go @@ -97,9 +97,9 @@ func resourceLagCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("connection_id"); ok { connectionIDSpecified = true input.ConnectionId = aws.String(v.(string)) - input.NumberOfConnections = aws.Int64(int64(1)) + input.NumberOfConnections = aws.Int64(1) } else { - input.NumberOfConnections = aws.Int64(int64(1)) + input.NumberOfConnections = aws.Int64(1) } if v, ok := d.GetOk("provider_name"); ok { diff --git a/internal/service/ec2/flex_test.go b/internal/service/ec2/flex_test.go index eda3a863013..3a1d9c4bb10 100644 --- a/internal/service/ec2/flex_test.go +++ b/internal/service/ec2/flex_test.go @@ -12,7 +12,7 @@ import ( func TestFlattenAttachment(t *testing.T) { expanded := &ec2.NetworkInterfaceAttachment{ InstanceId: aws.String("i-00001"), - DeviceIndex: aws.Int64(int64(1)), + DeviceIndex: aws.Int64(1), AttachmentId: aws.String("at-002"), } @@ -37,7 +37,7 @@ func TestFlattenAttachment(t *testing.T) { func TestFlattenAttachmentWhenNoInstanceId(t *testing.T) { expanded := &ec2.NetworkInterfaceAttachment{ - DeviceIndex: aws.Int64(int64(1)), + DeviceIndex: aws.Int64(1), AttachmentId: aws.String("at-002"), } @@ -107,7 +107,7 @@ func TestExpandIPPerms(t *testing.T) { expected := []ec2.IpPermission{ { IpProtocol: aws.String("icmp"), - FromPort: aws.Int64(int64(1)), + FromPort: aws.Int64(1), ToPort: aws.Int64(int64(-1)), IpRanges: []*ec2.IpRange{ { @@ -129,7 +129,7 @@ func TestExpandIPPerms(t *testing.T) { }, { IpProtocol: aws.String("icmp"), - FromPort: aws.Int64(int64(1)), + FromPort: aws.Int64(1), ToPort: aws.Int64(int64(-1)), UserIdGroupPairs: []*ec2.UserIdGroupPair{ { @@ -216,8 +216,8 @@ func TestExpandIPPerms_NegOneProtocol(t *testing.T) { expected := []ec2.IpPermission{ { IpProtocol: aws.String("-1"), - FromPort: aws.Int64(int64(0)), - ToPort: aws.Int64(int64(0)), + FromPort: aws.Int64(0), + ToPort: aws.Int64(0), IpRanges: []*ec2.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, UserIdGroupPairs: []*ec2.UserIdGroupPair{ { @@ -312,7 +312,7 @@ func TestExpandIPPerms_nonVPC(t *testing.T) { expected := []ec2.IpPermission{ { IpProtocol: aws.String("icmp"), - FromPort: aws.Int64(int64(1)), + FromPort: aws.Int64(1), ToPort: aws.Int64(int64(-1)), IpRanges: []*ec2.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, UserIdGroupPairs: []*ec2.UserIdGroupPair{ @@ -326,7 +326,7 @@ func TestExpandIPPerms_nonVPC(t *testing.T) { }, { IpProtocol: aws.String("icmp"), - FromPort: aws.Int64(int64(1)), + FromPort: aws.Int64(1), ToPort: aws.Int64(int64(-1)), UserIdGroupPairs: []*ec2.UserIdGroupPair{ { diff --git a/internal/service/ec2/host.go b/internal/service/ec2/host.go index e1c243b3697..05fd3f010a3 100644 --- a/internal/service/ec2/host.go +++ b/internal/service/ec2/host.go @@ -80,7 +80,7 @@ func resourceHostCreate(d *schema.ResourceData, meta interface{}) error { AutoPlacement: aws.String(d.Get("auto_placement").(string)), AvailabilityZone: aws.String(d.Get("availability_zone").(string)), HostRecovery: aws.String(d.Get("host_recovery").(string)), - Quantity: aws.Int64(int64(1)), + Quantity: aws.Int64(1), } if v, ok := d.GetOk("instance_family"); ok { diff --git a/internal/service/ec2/instance.go b/internal/service/ec2/instance.go index b8534d4183d..ecb3cc73943 100644 --- a/internal/service/ec2/instance.go +++ b/internal/service/ec2/instance.go @@ -744,8 +744,8 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { Ipv6Addresses: instanceOpts.Ipv6Addresses, KeyName: instanceOpts.KeyName, LaunchTemplate: instanceOpts.LaunchTemplate, - MaxCount: aws.Int64(int64(1)), - MinCount: aws.Int64(int64(1)), + MaxCount: aws.Int64(1), + MinCount: aws.Int64(1), NetworkInterfaces: instanceOpts.NetworkInterfaces, Placement: instanceOpts.Placement, PrivateIpAddress: instanceOpts.PrivateIPAddress, @@ -2182,7 +2182,7 @@ func buildNetworkInterfaceOpts(d *schema.ResourceData, groups []*string, nInterf // to avoid: Network interfaces and an instance-level security groups may not be specified on // the same request ni := &ec2.InstanceNetworkInterfaceSpecification{ - DeviceIndex: aws.Int64(int64(0)), + DeviceIndex: aws.Int64(0), SubnetId: aws.String(subnet.(string)), Groups: groups, } diff --git a/internal/service/ec2/security_group.go b/internal/service/ec2/security_group.go index 85ea6fecbd2..b450fe3ed60 100644 --- a/internal/service/ec2/security_group.go +++ b/internal/service/ec2/security_group.go @@ -291,8 +291,8 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error GroupId: createResp.GroupId, IpPermissions: []*ec2.IpPermission{ { - FromPort: aws.Int64(int64(0)), - ToPort: aws.Int64(int64(0)), + FromPort: aws.Int64(0), + ToPort: aws.Int64(0), IpRanges: []*ec2.IpRange{ { CidrIp: aws.String("0.0.0.0/0"), @@ -312,8 +312,8 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error GroupId: createResp.GroupId, IpPermissions: []*ec2.IpPermission{ { - FromPort: aws.Int64(int64(0)), - ToPort: aws.Int64(int64(0)), + FromPort: aws.Int64(0), + ToPort: aws.Int64(0), Ipv6Ranges: []*ec2.Ipv6Range{ { CidrIpv6: aws.String("::/0"), diff --git a/internal/service/ec2/security_group_rule_test.go b/internal/service/ec2/security_group_rule_test.go index e42f47fc13d..c6984154a41 100644 --- a/internal/service/ec2/security_group_rule_test.go +++ b/internal/service/ec2/security_group_rule_test.go @@ -23,8 +23,8 @@ import ( func TestIpPermissionIDHash(t *testing.T) { simple := &ec2.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(80)), - ToPort: aws.Int64(int64(8000)), + FromPort: aws.Int64(80), + ToPort: aws.Int64(8000), IpRanges: []*ec2.IpRange{ { CidrIp: aws.String("10.0.0.0/8"), @@ -34,8 +34,8 @@ func TestIpPermissionIDHash(t *testing.T) { egress := &ec2.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(80)), - ToPort: aws.Int64(int64(8000)), + FromPort: aws.Int64(80), + ToPort: aws.Int64(8000), IpRanges: []*ec2.IpRange{ { CidrIp: aws.String("10.0.0.0/8"), @@ -54,8 +54,8 @@ func TestIpPermissionIDHash(t *testing.T) { vpc_security_group_source := &ec2.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(80)), - ToPort: aws.Int64(int64(8000)), + FromPort: aws.Int64(80), + ToPort: aws.Int64(8000), UserIdGroupPairs: []*ec2.UserIdGroupPair{ { UserId: aws.String("987654321"), @@ -74,8 +74,8 @@ func TestIpPermissionIDHash(t *testing.T) { security_group_source := &ec2.IpPermission{ IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(80)), - ToPort: aws.Int64(int64(8000)), + FromPort: aws.Int64(80), + ToPort: aws.Int64(8000), UserIdGroupPairs: []*ec2.UserIdGroupPair{ { UserId: aws.String("987654321"), diff --git a/internal/service/ec2/security_group_test.go b/internal/service/ec2/security_group_test.go index dd0094deba3..d159fb467d6 100644 --- a/internal/service/ec2/security_group_test.go +++ b/internal/service/ec2/security_group_test.go @@ -352,7 +352,7 @@ func TestSecurityGroupIPPermGather(t *testing.T) { raw := []*ec2.IpPermission{ { IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(1)), + FromPort: aws.Int64(1), ToPort: aws.Int64(int64(-1)), IpRanges: []*ec2.IpRange{{CidrIp: aws.String("0.0.0.0/0")}}, UserIdGroupPairs: []*ec2.UserIdGroupPair{ @@ -364,8 +364,8 @@ func TestSecurityGroupIPPermGather(t *testing.T) { }, { IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(80)), - ToPort: aws.Int64(int64(80)), + FromPort: aws.Int64(80), + ToPort: aws.Int64(80), UserIdGroupPairs: []*ec2.UserIdGroupPair{ // VPC { @@ -375,8 +375,8 @@ func TestSecurityGroupIPPermGather(t *testing.T) { }, { IpProtocol: aws.String("tcp"), - FromPort: aws.Int64(int64(443)), - ToPort: aws.Int64(int64(443)), + FromPort: aws.Int64(443), + ToPort: aws.Int64(443), UserIdGroupPairs: []*ec2.UserIdGroupPair{ // Classic { @@ -393,8 +393,8 @@ func TestSecurityGroupIPPermGather(t *testing.T) { }, { IpProtocol: aws.String("-1"), - FromPort: aws.Int64(int64(0)), - ToPort: aws.Int64(int64(0)), + FromPort: aws.Int64(0), + ToPort: aws.Int64(0), PrefixListIds: []*ec2.PrefixListId{ { PrefixListId: aws.String("pl-12345678"), diff --git a/internal/service/ec2/spot_fleet_request.go b/internal/service/ec2/spot_fleet_request.go index 399dc1dd6fd..4d37d56dcb0 100644 --- a/internal/service/ec2/spot_fleet_request.go +++ b/internal/service/ec2/spot_fleet_request.go @@ -664,7 +664,7 @@ func buildSpotFleetLaunchSpecification(d map[string]interface{}, meta interface{ ni := &ec2.InstanceNetworkInterfaceSpecification{ AssociatePublicIpAddress: aws.Bool(true), DeleteOnTermination: aws.Bool(true), - DeviceIndex: aws.Int64(int64(0)), + DeviceIndex: aws.Int64(0), SubnetId: aws.String(subnetId.(string)), Groups: securityGroupIds, } diff --git a/internal/service/ecs/service.go b/internal/service/ecs/service.go index 690cbc6b578..93d3fd47794 100644 --- a/internal/service/ecs/service.go +++ b/internal/service/ecs/service.go @@ -1207,7 +1207,7 @@ func resourceServiceDelete(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateService(&ecs.UpdateServiceInput{ Service: aws.String(d.Id()), Cluster: aws.String(d.Get("cluster").(string)), - DesiredCount: aws.Int64(int64(0)), + DesiredCount: aws.Int64(0), }) if err != nil { return err diff --git a/internal/service/elasticsearch/domain_test.go b/internal/service/elasticsearch/domain_test.go index 1ad596e120f..7bba2cb1213 100644 --- a/internal/service/elasticsearch/domain_test.go +++ b/internal/service/elasticsearch/domain_test.go @@ -2430,7 +2430,7 @@ func testAccPreCheckCognitoIdentityProvider(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).CognitoIDPConn input := &cognitoidentityprovider.ListUserPoolsInput{ - MaxResults: aws.Int64(int64(1)), + MaxResults: aws.Int64(1), } _, err := conn.ListUserPools(input) diff --git a/internal/service/elb/flex_test.go b/internal/service/elb/flex_test.go index b4943db6364..fd1d05250f1 100644 --- a/internal/service/elb/flex_test.go +++ b/internal/service/elb/flex_test.go @@ -31,8 +31,8 @@ func TestExpandListeners(t *testing.T) { } expected := &elb.Listener{ - InstancePort: aws.Int64(int64(8000)), - LoadBalancerPort: aws.Int64(int64(80)), + InstancePort: aws.Int64(8000), + LoadBalancerPort: aws.Int64(80), InstanceProtocol: aws.String("http"), Protocol: aws.String("http"), } @@ -77,11 +77,11 @@ func TestFlattenHealthCheck(t *testing.T) { }{ { Input: &elb.HealthCheck{ - UnhealthyThreshold: aws.Int64(int64(10)), - HealthyThreshold: aws.Int64(int64(10)), + UnhealthyThreshold: aws.Int64(10), + HealthyThreshold: aws.Int64(10), Target: aws.String("HTTP:80/"), - Timeout: aws.Int64(int64(30)), - Interval: aws.Int64(int64(30)), + Timeout: aws.Int64(30), + Interval: aws.Int64(30), }, Output: []map[string]interface{}{ { diff --git a/internal/service/elb/load_balancer_test.go b/internal/service/elb/load_balancer_test.go index 31df867d8ee..765e8282ed1 100644 --- a/internal/service/elb/load_balancer_test.go +++ b/internal/service/elb/load_balancer_test.go @@ -503,7 +503,7 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { conn := acctest.Provider.Meta().(*conns.AWSClient).ELBConn input := &elb.DeleteLoadBalancerListenersInput{ LoadBalancerName: conf.LoadBalancerName, - LoadBalancerPorts: []*int64{aws.Int64(int64(80))}, + LoadBalancerPorts: []*int64{aws.Int64(80)}, } if _, err := conn.DeleteLoadBalancerListeners(input); err != nil { t.Fatalf("Error deleting listener: %s", err) @@ -529,9 +529,9 @@ func TestAccELBLoadBalancer_listener(t *testing.T) { LoadBalancerName: conf.LoadBalancerName, Listeners: []*elb.Listener{ { - InstancePort: aws.Int64(int64(22)), + InstancePort: aws.Int64(22), InstanceProtocol: aws.String("tcp"), - LoadBalancerPort: aws.Int64(int64(22)), + LoadBalancerPort: aws.Int64(22), Protocol: aws.String("tcp"), }, }, @@ -921,9 +921,9 @@ func testAccCheckLoadBalancerDisappears(loadBalancer *elb.LoadBalancerDescriptio func testAccCheckLoadBalancerAttributes(conf *elb.LoadBalancerDescription) resource.TestCheckFunc { return func(s *terraform.State) error { l := elb.Listener{ - InstancePort: aws.Int64(int64(8000)), + InstancePort: aws.Int64(8000), InstanceProtocol: aws.String("HTTP"), - LoadBalancerPort: aws.Int64(int64(80)), + LoadBalancerPort: aws.Int64(80), Protocol: aws.String("HTTP"), } diff --git a/internal/service/kms/grant.go b/internal/service/kms/grant.go index 9ad74a6dee5..7d86d007362 100644 --- a/internal/service/kms/grant.go +++ b/internal/service/kms/grant.go @@ -364,7 +364,7 @@ func findKmsGrantById(conn *kms.KMS, keyId string, grantId string, marker *strin input := kms.ListGrantsInput{ KeyId: aws.String(keyId), - Limit: aws.Int64(int64(100)), + Limit: aws.Int64(100), Marker: marker, } diff --git a/internal/service/kms/sweep.go b/internal/service/kms/sweep.go index ec120240ade..4bb2460ee9b 100644 --- a/internal/service/kms/sweep.go +++ b/internal/service/kms/sweep.go @@ -28,7 +28,7 @@ func sweepKeys(region string) error { } conn := client.(*conns.AWSClient).KMSConn - err = conn.ListKeysPages(&kms.ListKeysInput{Limit: aws.Int64(int64(1000))}, func(out *kms.ListKeysOutput, lastPage bool) bool { + err = conn.ListKeysPages(&kms.ListKeysInput{Limit: aws.Int64(1000)}, func(out *kms.ListKeysOutput, lastPage bool) bool { for _, k := range out.Keys { kKeyId := aws.StringValue(k.KeyId) kOut, err := conn.DescribeKey(&kms.DescribeKeyInput{ diff --git a/internal/service/ram/resource_share_accepter.go b/internal/service/ram/resource_share_accepter.go index 4b06f4c2810..037abac8c73 100644 --- a/internal/service/ram/resource_share_accepter.go +++ b/internal/service/ram/resource_share_accepter.go @@ -165,7 +165,7 @@ func resourceResourceShareAccepterRead(d *schema.ResourceData, meta interface{}) d.Set("share_name", resourceShare.Name) listInput := &ram.ListResourcesInput{ - MaxResults: aws.Int64(int64(500)), + MaxResults: aws.Int64(500), ResourceOwner: aws.String(ram.ResourceOwnerOtherAccounts), ResourceShareArns: aws.StringSlice([]string{d.Id()}), } diff --git a/internal/service/redshift/snapshot_copy_grant_test.go b/internal/service/redshift/snapshot_copy_grant_test.go index 1470be3480c..24a60cd4589 100644 --- a/internal/service/redshift/snapshot_copy_grant_test.go +++ b/internal/service/redshift/snapshot_copy_grant_test.go @@ -138,7 +138,7 @@ func testAccCheckSnapshotCopyGrantExists(name string) resource.TestCheckFunc { conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftConn input := redshift.DescribeSnapshotCopyGrantsInput{ - MaxRecords: aws.Int64(int64(100)), + MaxRecords: aws.Int64(100), SnapshotCopyGrantName: aws.String(rs.Primary.ID), } diff --git a/internal/service/route53/zone_test.go b/internal/service/route53/zone_test.go index b214a6fe6c0..0e15d5aa421 100644 --- a/internal/service/route53/zone_test.go +++ b/internal/service/route53/zone_test.go @@ -480,7 +480,7 @@ func testAccCreateRandomRoute53RecordsInZoneIdWithProvider(providerF func() *sch ResourceRecords: []*route53.ResourceRecord{ {Value: aws.String(fmt.Sprintf("random.%s", *zone.HostedZone.Name))}, }, - TTL: aws.Int64(int64(30)), + TTL: aws.Int64(30), }, }) } From a7d287a167277e5923d1bb6763b531f215a2edde Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 7 Oct 2021 17:04:01 -0700 Subject: [PATCH 2/3] Enables `gomnd` linter. Uses forked version of `gomnd` which supports functions without a package identifier --- .golangci.yml | 14 ++++++-- internal/acctest/acctest.go | 35 +++++++++++++------ internal/acctest/crypto.go | 8 ++--- .../service/acmpca/certificate_authority.go | 22 +++++++++--- internal/service/cloudwatchevents/rule.go | 5 +-- internal/service/ec2/instance.go | 2 +- internal/service/ec2/sweep.go | 2 +- internal/service/efs/mount_target.go | 6 +++- internal/service/efs/sweep.go | 3 +- internal/service/elasticache/cluster.go | 8 +++-- internal/service/elasticache/wait.go | 4 +-- internal/service/elasticbeanstalk/sweep.go | 2 +- .../service/elb/lb_ssl_negotiation_policy.go | 7 ++-- internal/service/elbv2/listener_rule.go | 17 ++++++--- internal/service/gamelift/fleet.go | 9 +++-- internal/service/gamelift/fleet_test.go | 2 +- internal/service/gamelift/sweep.go | 2 +- internal/service/iam/access_key.go | 2 +- internal/service/opsworks/stack.go | 9 +++-- internal/service/rds/sweep.go | 2 +- .../service/redshift/snapshot_schedule.go | 3 +- .../redshift/snapshot_schedule_association.go | 9 +++-- internal/service/route53/record.go | 15 +++++--- internal/service/route53/zone.go | 11 ++++-- internal/service/route53resolver/endpoint.go | 12 +++++-- internal/service/route53resolver/rule.go | 12 +++++-- .../route53resolver/rule_association.go | 9 +++-- internal/service/route53resolver/sweep.go | 7 ++-- tools/go.mod | 2 ++ tools/go.sum | 4 +-- 30 files changed, 171 insertions(+), 74 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 41526b20f79..27b9ecc8c99 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,7 +18,7 @@ linters: # - deadcode - errcheck - gofmt - # - gomnd + - gomnd - gosimple - ineffassign - makezero @@ -44,17 +44,25 @@ linters-settings: ignored-functions: # AWS Go SDK - aws.Int64 - - nullable.* - request.ConstantWaiterDelay - request.WithWaiterMaxAttempts + # AWS Provider + - mapMaxItems + - wafv2RootStatementSchema + - wafv2WebACLRootStatementSchema + - nullable.* + - sweep.SweepOrchestratorContext # Terraform Plugin SDK + - resource.Retry - schema.DefaultTimeout + - validation.* + # Go + - make - strconv.FormatFloat - strconv.FormatInt - strconv.ParseFloat - strconv.ParseInt - strings.SplitN - - validation.* nolintlint: allow-leading-space: false require-explanation: true diff --git a/internal/acctest/acctest.go b/internal/acctest/acctest.go index 0cdbdf89f4a..eb1f6cda9f1 100644 --- a/internal/acctest/acctest.go +++ b/internal/acctest/acctest.go @@ -1910,7 +1910,7 @@ func (d domainName) Subdomain(name string) domainName { } func (d domainName) RandomSubdomain() domainName { - return d.Subdomain(sdkacctest.RandString(8)) + return d.Subdomain(sdkacctest.RandString(8)) //nolint:gomnd } func (d domainName) FQDN() domainName { @@ -1956,6 +1956,20 @@ func PreCheckOutpostsOutposts(t *testing.T) { } } +const ( + // ACM domain names cannot be longer than 64 characters + // Other resources, e.g. Cognito User Pool Domains, limit this to 63 + acmCertificateDomainMaxLen = 63 + + acmRandomSubDomainPrefix = "tf-acc-" + acmRandomSubDomainPrefixLen = len(acmRandomSubDomainPrefix) + + // Max length (63) + // Subtract "tf-acc-" prefix (7) + // Subtract "." between prefix and root domain (1) + acmRandomSubDomainRemainderLen = acmCertificateDomainMaxLen - acmRandomSubDomainPrefixLen - 1 +) + func ACMCertificateDomainFromEnv(t *testing.T) string { rootDomain := os.Getenv("ACM_CERTIFICATE_ROOT_DOMAIN") @@ -1970,11 +1984,11 @@ func ACMCertificateDomainFromEnv(t *testing.T) string { "contact addresses.") } - if len(rootDomain) >= 56 { - t.Skip( - "Environment variable ACM_CERTIFICATE_ROOT_DOMAIN is too long. " + - "The domain must be shorter than 56 characters to allow for " + - "subdomain randomization in the testing.") + if len(rootDomain) > acmRandomSubDomainRemainderLen { + t.Skipf( + "Environment variable ACM_CERTIFICATE_ROOT_DOMAIN is too long. "+ + "The domain must be %d characters or shorter to allow for "+ + "subdomain randomization in the testing.", acmRandomSubDomainRemainderLen) } return rootDomain @@ -1983,11 +1997,10 @@ func ACMCertificateDomainFromEnv(t *testing.T) string { // ACM domain names cannot be longer than 64 characters // Other resources, e.g. Cognito User Pool Domains, limit this to 63 func ACMCertificateRandomSubDomain(rootDomain string) string { - // Max length (63) - // Subtract "tf-acc-" prefix (7) - // Subtract "." between prefix and root domain (1) - // Subtract length of root domain - return fmt.Sprintf("tf-acc-%s.%s", sdkacctest.RandString(55-len(rootDomain)), rootDomain) + return fmt.Sprintf( + acmRandomSubDomainPrefix+"%s.%s", + sdkacctest.RandString(acmRandomSubDomainRemainderLen-len(rootDomain)), + rootDomain) } func CheckACMPCACertificateAuthorityActivateCA(certificateAuthority *acmpca.CertificateAuthority) resource.TestCheckFunc { diff --git a/internal/acctest/crypto.go b/internal/acctest/crypto.go index a86d2758d43..448385158b4 100644 --- a/internal/acctest/crypto.go +++ b/internal/acctest/crypto.go @@ -19,7 +19,7 @@ const ( pemBlockTypeCertificateRequest = `CERTIFICATE REQUEST` ) -var tlsX509CertificateSerialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128) +var tlsX509CertificateSerialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128) //nolint:gomnd // TLSRSAPrivateKeyPEM generates a RSA private key PEM string. // Wrap with TLSPEMEscapeNewlines() to allow simple fmt.Sprintf() @@ -110,7 +110,7 @@ func TLSRSAX509LocallySignedCertificatePEM(caKeyPem, caCertificatePem, keyPem, c BasicConstraintsValid: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, - NotAfter: time.Now().Add(24 * time.Hour), + NotAfter: time.Now().Add(24 * time.Hour), //nolint:gomnd NotBefore: time.Now(), SerialNumber: serialNumber, Subject: pkix.Name{ @@ -168,7 +168,7 @@ func TLSRSAX509SelfSignedCACertificatePEM(keyPem string) string { ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IsCA: true, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, - NotAfter: time.Now().Add(24 * time.Hour), + NotAfter: time.Now().Add(24 * time.Hour), //nolint:gomnd NotBefore: time.Now(), SerialNumber: serialNumber, Subject: pkix.Name{ @@ -217,7 +217,7 @@ func TLSRSAX509SelfSignedCertificatePEM(keyPem, commonName string) string { BasicConstraintsValid: true, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, - NotAfter: time.Now().Add(24 * time.Hour), + NotAfter: time.Now().Add(24 * time.Hour), //nolint:gomnd NotBefore: time.Now(), SerialNumber: serialNumber, Subject: pkix.Name{ diff --git a/internal/service/acmpca/certificate_authority.go b/internal/service/acmpca/certificate_authority.go index 7d83bbc3057..2a5c6146133 100644 --- a/internal/service/acmpca/certificate_authority.go +++ b/internal/service/acmpca/certificate_authority.go @@ -17,6 +17,12 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) +const ( + certificateAuthorityPermanentDeletionTimeInDaysMin = 7 + certificateAuthorityPermanentDeletionTimeInDaysMax = 30 + certificateAuthorityPermanentDeletionTimeInDaysDefault = certificateAuthorityPermanentDeletionTimeInDaysMax +) + func ResourceCertificateAuthority() *schema.Resource { //lintignore:R011 return &schema.Resource{ @@ -26,7 +32,10 @@ func ResourceCertificateAuthority() *schema.Resource { Delete: resourceCertificateAuthorityDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - d.Set("permanent_deletion_time_in_days", 30) + d.Set( + "permanent_deletion_time_in_days", + certificateAuthorityPermanentDeletionTimeInDaysDefault, + ) return []*schema.ResourceData{d}, nil }, @@ -258,10 +267,13 @@ func ResourceCertificateAuthority() *schema.Resource { Computed: true, }, "permanent_deletion_time_in_days": { - Type: schema.TypeInt, - Optional: true, - Default: 30, - ValidateFunc: validation.IntBetween(7, 30), + Type: schema.TypeInt, + Optional: true, + Default: certificateAuthorityPermanentDeletionTimeInDaysDefault, + ValidateFunc: validation.IntBetween( + certificateAuthorityPermanentDeletionTimeInDaysMin, + certificateAuthorityPermanentDeletionTimeInDaysMax, + ), }, "tags": tftags.TagsSchema(), "tags_all": tftags.TagsSchemaComputed(), diff --git a/internal/service/cloudwatchevents/rule.go b/internal/service/cloudwatchevents/rule.go index 5f6fffe0365..fe53c66b4dc 100644 --- a/internal/service/cloudwatchevents/rule.go +++ b/internal/service/cloudwatchevents/rule.go @@ -355,8 +355,9 @@ func validateEventPatternValue() schema.SchemaValidateFunc { } // Check whether the normalized JSON is within the given length. - if len(json) > 2048 { - errors = append(errors, fmt.Errorf("%q cannot be longer than %d characters: %q", k, 2048, json)) + const maxJsonLength = 2048 + if len(json) > maxJsonLength { + errors = append(errors, fmt.Errorf("%q cannot be longer than %d characters: %q", k, maxJsonLength, json)) } return } diff --git a/internal/service/ec2/instance.go b/internal/service/ec2/instance.go index ecb3cc73943..4525b2a8890 100644 --- a/internal/service/ec2/instance.go +++ b/internal/service/ec2/instance.go @@ -1431,7 +1431,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error stopping instance (%s): %s", d.Id(), err) } - if err := WaitForInstanceStopping(conn, d.Id(), 10*time.Minute); err != nil { + if err := WaitForInstanceStopping(conn, d.Id(), InstanceStopTimeout); err != nil { return err } diff --git a/internal/service/ec2/sweep.go b/internal/service/ec2/sweep.go index 63328257e4f..c9168ffc501 100644 --- a/internal/service/ec2/sweep.go +++ b/internal/service/ec2/sweep.go @@ -1877,7 +1877,7 @@ func sweepVPCPeeringConnections(region string) error { continue } - if err := WaitForVPCPeeringConnectionDeletion(conn, id, 5*time.Minute); err != nil { + if err := WaitForVPCPeeringConnectionDeletion(conn, id, 5*time.Minute); err != nil { //nolint:gomnd log.Printf("[ERROR] Error waiting for EC2 VPC Peering Connection (%s) to be deleted: %s", id, err) } } diff --git a/internal/service/efs/mount_target.go b/internal/service/efs/mount_target.go index cd4b3987ecb..fac2afea104 100644 --- a/internal/service/efs/mount_target.go +++ b/internal/service/efs/mount_target.go @@ -17,6 +17,10 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/flex" ) +const ( + mountTargetDeleteTimeout = 10 * time.Minute +) + func ResourceMountTarget() *schema.Resource { return &schema.Resource{ Create: resourceMountTargetCreate, @@ -270,7 +274,7 @@ func resourceMountTargetDelete(d *schema.ResourceData, meta interface{}) error { return err } - err = WaitForDeleteMountTarget(conn, d.Id(), 10*time.Minute) + err = WaitForDeleteMountTarget(conn, d.Id(), mountTargetDeleteTimeout) if err != nil { return fmt.Errorf("Error waiting for EFS mount target (%q) to delete: %s", d.Id(), err.Error()) } diff --git a/internal/service/efs/sweep.go b/internal/service/efs/sweep.go index 4d9b331ffae..7fead2910cc 100644 --- a/internal/service/efs/sweep.go +++ b/internal/service/efs/sweep.go @@ -6,7 +6,6 @@ package efs import ( "fmt" "log" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/efs" @@ -175,7 +174,7 @@ func sweepMountTargets(region string) error { continue } - err = WaitForDeleteMountTarget(conn, id, 10*time.Minute) + err = WaitForDeleteMountTarget(conn, id, mountTargetDeleteTimeout) if err != nil { errors = multierror.Append(errors, fmt.Errorf("error waiting for EFS Mount Target %q to delete: %w", id, err)) continue diff --git a/internal/service/elasticache/cluster.go b/internal/service/elasticache/cluster.go index c1e14ac7ebf..727c77100a4 100644 --- a/internal/service/elasticache/cluster.go +++ b/internal/service/elasticache/cluster.go @@ -29,6 +29,10 @@ const ( elasticacheDefaultMemcachedPort = "11211" ) +const ( + cacheClusterCreatedTimeout = 40 * time.Minute +) + func ResourceCluster() *schema.Resource { return &schema.Resource{ Create: resourceClusterCreate, @@ -366,7 +370,7 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(id) - _, err = WaitCacheClusterAvailable(conn, d.Id(), 40*time.Minute) + _, err = waitCacheClusterAvailable(conn, d.Id(), cacheClusterCreatedTimeout) if err != nil { return fmt.Errorf("error waiting for ElastiCache Cache Cluster (%s) to be created: %w", d.Id(), err) } @@ -597,7 +601,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error updating ElastiCache cluster (%s), error: %w", d.Id(), err) } - _, err = WaitCacheClusterAvailable(conn, d.Id(), CacheClusterUpdatedTimeout) + _, err = waitCacheClusterAvailable(conn, d.Id(), CacheClusterUpdatedTimeout) if err != nil { return fmt.Errorf("error waiting for ElastiCache Cache Cluster (%s) to update: %w", d.Id(), err) } diff --git a/internal/service/elasticache/wait.go b/internal/service/elasticache/wait.go index a5420663b80..e91b8588c29 100644 --- a/internal/service/elasticache/wait.go +++ b/internal/service/elasticache/wait.go @@ -100,8 +100,8 @@ const ( cacheClusterDeletedDelay = 30 * time.Second ) -// WaitCacheClusterAvailable waits for a Cache Cluster to return Available -func WaitCacheClusterAvailable(conn *elasticache.ElastiCache, cacheClusterID string, timeout time.Duration) (*elasticache.CacheCluster, error) { +// waitCacheClusterAvailable waits for a Cache Cluster to return Available +func waitCacheClusterAvailable(conn *elasticache.ElastiCache, cacheClusterID string, timeout time.Duration) (*elasticache.CacheCluster, error) { stateConf := &resource.StateChangeConf{ Pending: []string{ CacheClusterStatusCreating, diff --git a/internal/service/elasticbeanstalk/sweep.go b/internal/service/elasticbeanstalk/sweep.go index 781f2252a84..66328d0b27e 100644 --- a/internal/service/elasticbeanstalk/sweep.go +++ b/internal/service/elasticbeanstalk/sweep.go @@ -101,7 +101,7 @@ func sweepEnvironments(region string) error { environmentID := aws.StringValue(bse.EnvironmentId) log.Printf("Trying to terminate (%s) (%s)", environmentName, environmentID) - err := DeleteEnvironment(conn, environmentID, 5*time.Minute, 10*time.Second) + err := DeleteEnvironment(conn, environmentID, 5*time.Minute, 10*time.Second) //nolint:gomnd if err != nil { errors = multierror.Append(fmt.Errorf("error deleting Elastic Beanstalk Environment %q: %w", environmentID, err)) } diff --git a/internal/service/elb/lb_ssl_negotiation_policy.go b/internal/service/elb/lb_ssl_negotiation_policy.go index b241b4e992b..3b1ac817f73 100644 --- a/internal/service/elb/lb_ssl_negotiation_policy.go +++ b/internal/service/elb/lb_ssl_negotiation_policy.go @@ -198,9 +198,10 @@ func resourceSSLNegotiationPolicyDelete(d *schema.ResourceData, meta interface{} // it's constituent parts. You need three axes (LB name, policy name, and LB // port) to create or identify an SSL negotiation policy in AWS's API. func SSLNegotiationPolicyParseID(id string) (string, int, string, error) { - parts := strings.SplitN(id, ":", 3) - if n := len(parts); n != 3 { - return "", 0, "", fmt.Errorf("incorrect format of SSL negotiation policy resource ID. Expected %d parts, got %d", 3, n) + const partCount = 3 + parts := strings.SplitN(id, ":", partCount) + if n := len(parts); n != partCount { + return "", 0, "", fmt.Errorf("incorrect format of SSL negotiation policy resource ID. Expected %d parts, got %d", partCount, n) } port, err := strconv.Atoi(parts[1]) diff --git a/internal/service/elbv2/listener_rule.go b/internal/service/elbv2/listener_rule.go index e02d540e453..e1be12c9790 100644 --- a/internal/service/elbv2/listener_rule.go +++ b/internal/service/elbv2/listener_rule.go @@ -24,6 +24,15 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) +const ( + listenerRulePriorityMin = 1 + listenerRulePriorityMax = 50_000 + listenerRulePriorityDefault = 99_999 + + listenerActionOrderMin = 1 + listenerActionOrderMax = 50_000 +) + func ResourceListenerRule() *schema.Resource { return &schema.Resource{ Create: resourceListenerRuleCreate, @@ -66,7 +75,7 @@ func ResourceListenerRule() *schema.Resource { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntBetween(1, 50000), + ValidateFunc: validation.IntBetween(listenerActionOrderMin, listenerActionOrderMax), }, "target_group_arn": { @@ -613,7 +622,7 @@ func resourceListenerRuleRead(d *schema.ResourceData, meta interface{}) error { // Rules are evaluated in priority order, from the lowest value to the highest value. The default rule has the lowest priority. if aws.StringValue(rule.Priority) == "default" { - d.Set("priority", 99999) + d.Set("priority", listenerRulePriorityDefault) } else { if priority, err := strconv.Atoi(aws.StringValue(rule.Priority)); err != nil { return fmt.Errorf("Cannot convert rule priority %q to int: %w", aws.StringValue(rule.Priority), err) @@ -887,8 +896,8 @@ func resourceListenerRuleDelete(d *schema.ResourceData, meta interface{}) error func validListenerRulePriority(v interface{}, k string) (ws []string, errors []error) { value := v.(int) - if value < 1 || (value > 50000 && value != 99999) { - errors = append(errors, fmt.Errorf("%q must be in the range 1-50000 for normal rule or 99999 for default rule", k)) + if value < listenerRulePriorityMin || (value > listenerRulePriorityMax && value != listenerRulePriorityDefault) { + errors = append(errors, fmt.Errorf("%q must be in the range %d-%d for normal rule or %d for the default rule", k, listenerRulePriorityMin, listenerRulePriorityMax, listenerRulePriorityDefault)) } return } diff --git a/internal/service/gamelift/fleet.go b/internal/service/gamelift/fleet.go index 8f1d6476b56..214dffedfaf 100644 --- a/internal/service/gamelift/fleet.go +++ b/internal/service/gamelift/fleet.go @@ -20,6 +20,11 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) +const ( + fleetCreatedDefaultTimeout = 70 * time.Minute + FleetDeletedDefaultTimeout = 20 * time.Minute +) + func ResourceFleet() *schema.Resource { return &schema.Resource{ Create: resourceFleetCreate, @@ -28,8 +33,8 @@ func ResourceFleet() *schema.Resource { Delete: resourceFleetDelete, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(70 * time.Minute), - Delete: schema.DefaultTimeout(20 * time.Minute), + Create: schema.DefaultTimeout(fleetCreatedDefaultTimeout), + Delete: schema.DefaultTimeout(FleetDeletedDefaultTimeout), }, Schema: map[string]*schema.Schema{ diff --git a/internal/service/gamelift/fleet_test.go b/internal/service/gamelift/fleet_test.go index 0fe8f431556..aebd8f3e089 100644 --- a/internal/service/gamelift/fleet_test.go +++ b/internal/service/gamelift/fleet_test.go @@ -534,7 +534,7 @@ func testAccCheckFleetDisappears(res *gamelift.FleetAttributes) resource.TestChe return fmt.Errorf("Error deleting Gamelift fleet: %s", err) } - return tfgamelift.WaitForFleetToBeDeleted(conn, *res.FleetId, 15*time.Minute) + return tfgamelift.WaitForFleetToBeDeleted(conn, *res.FleetId, tfgamelift.FleetDeletedDefaultTimeout) } } diff --git a/internal/service/gamelift/sweep.go b/internal/service/gamelift/sweep.go index 70c7004d2e7..2c5fd39fac0 100644 --- a/internal/service/gamelift/sweep.go +++ b/internal/service/gamelift/sweep.go @@ -161,7 +161,7 @@ func sweepFleets(region string) error { *attr.FleetId, err) } - err = WaitForFleetToBeDeleted(conn, *attr.FleetId, 5*time.Minute) + err = WaitForFleetToBeDeleted(conn, *attr.FleetId, FleetDeletedDefaultTimeout) if err != nil { return fmt.Errorf("Error waiting for Gamelift Fleet (%s) to be deleted: %s", *attr.FleetId, err) diff --git a/internal/service/iam/access_key.go b/internal/service/iam/access_key.go index 56623569072..e60aeebdc05 100644 --- a/internal/service/iam/access_key.go +++ b/internal/service/iam/access_key.go @@ -271,7 +271,7 @@ func SessmTPPasswordFromSecretKeySigV4(key *string, region string) (string, erro if key == nil { return "", nil } - version := byte(0x04) + const version = byte(0x04) date := []byte("11111111") service := []byte("ses") terminal := []byte("aws4_request") diff --git a/internal/service/opsworks/stack.go b/internal/service/opsworks/stack.go index 36fa659d53b..423c35622ef 100644 --- a/internal/service/opsworks/stack.go +++ b/internal/service/opsworks/stack.go @@ -20,6 +20,11 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) +const ( + securityGroupsCreatedSleepTime = 30 * time.Second + securityGroupsDeletedSleepTime = 30 * time.Second +) + func ResourceStack() *schema.Resource { return &schema.Resource{ Create: resourceStackCreate, @@ -509,7 +514,7 @@ func resourceStackCreate(d *schema.ResourceData, meta interface{}) error { // we can't actually check for them. Instead, we just wait a nominal // amount of time for their creation to complete. log.Print("[INFO] Waiting for OpsWorks built-in security groups to be created") - time.Sleep(30 * time.Second) + time.Sleep(securityGroupsCreatedSleepTime) } return resourceStackUpdate(d, meta) @@ -632,7 +637,7 @@ func resourceStackDelete(d *schema.ResourceData, meta interface{}) error { if inVpc && useOpsworksDefaultSg { log.Print("[INFO] Waiting for Opsworks built-in security groups to be deleted") - time.Sleep(30 * time.Second) + time.Sleep(securityGroupsDeletedSleepTime) } return nil diff --git a/internal/service/rds/sweep.go b/internal/service/rds/sweep.go index 3da8810fbc8..624d0a53f43 100644 --- a/internal/service/rds/sweep.go +++ b/internal/service/rds/sweep.go @@ -255,7 +255,7 @@ func sweepClusters(region string) error { continue } - if err := WaitForClusterDeletion(conn, id, 40*time.Minute); err != nil { + if err := WaitForClusterDeletion(conn, id, 40*time.Minute); err != nil { //nolint:gomnd log.Printf("[ERROR] Failure while waiting for RDS DB Cluster (%s) to be deleted: %s", id, err) } } diff --git a/internal/service/redshift/snapshot_schedule.go b/internal/service/redshift/snapshot_schedule.go index 0c1fb739587..832b00f4632 100644 --- a/internal/service/redshift/snapshot_schedule.go +++ b/internal/service/redshift/snapshot_schedule.go @@ -3,7 +3,6 @@ package redshift import ( "fmt" "log" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" @@ -246,7 +245,7 @@ func resourceSnapshotScheduleDeleteAllAssociatedClusters(conn *redshift.Redshift } for _, associatedCluster := range snapshotSchedule.AssociatedClusters { - if err := waitForRedshiftSnapshotScheduleAssociationDestroy(conn, 75*time.Minute, aws.StringValue(associatedCluster.ClusterIdentifier), scheduleIdentifier); err != nil { + if err := waitForRedshiftSnapshotScheduleAssociationDestroy(conn, snapshotScheduleAssociationDestroyedTimeout, aws.StringValue(associatedCluster.ClusterIdentifier), scheduleIdentifier); err != nil { return err } } diff --git a/internal/service/redshift/snapshot_schedule_association.go b/internal/service/redshift/snapshot_schedule_association.go index 328f0e2dd84..64068d47cb5 100644 --- a/internal/service/redshift/snapshot_schedule_association.go +++ b/internal/service/redshift/snapshot_schedule_association.go @@ -14,6 +14,11 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/conns" ) +const ( + snapshotScheduleAssociationActivatedTimeout = 75 * time.Minute + snapshotScheduleAssociationDestroyedTimeout = 75 * time.Minute +) + func ResourceSnapshotScheduleAssociation() *schema.Resource { return &schema.Resource{ @@ -64,7 +69,7 @@ func resourceSnapshotScheduleAssociationCreate(d *schema.ResourceData, meta inte return fmt.Errorf("Error associating Redshift Cluster (%s) and Snapshot Schedule (%s): %s", clusterIdentifier, scheduleIdentifier, err) } - if err := WaitForSnapshotScheduleAssociationActive(conn, 75*time.Minute, clusterIdentifier, scheduleIdentifier); err != nil { + if err := WaitForSnapshotScheduleAssociationActive(conn, snapshotScheduleAssociationActivatedTimeout, clusterIdentifier, scheduleIdentifier); err != nil { return err } @@ -143,7 +148,7 @@ func resourceSnapshotScheduleAssociationDelete(d *schema.ResourceData, meta inte return fmt.Errorf("Error disassociate Redshift Cluster (%s) and Snapshot Schedule (%s) Association: %s", clusterIdentifier, scheduleIdentifier, err) } - if err := waitForRedshiftSnapshotScheduleAssociationDestroy(conn, 75*time.Minute, clusterIdentifier, scheduleIdentifier); err != nil { + if err := waitForRedshiftSnapshotScheduleAssociationDestroy(conn, snapshotScheduleAssociationDestroyedTimeout, clusterIdentifier, scheduleIdentifier); err != nil { return err } diff --git a/internal/service/route53/record.go b/internal/service/route53/record.go index cd4c5ea3b4e..ae3deffde5a 100644 --- a/internal/service/route53/record.go +++ b/internal/service/route53/record.go @@ -22,9 +22,16 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) -var r53NoRecordsFound = errors.New("No matching records found") -var r53NoHostedZoneFound = errors.New("No matching Hosted Zone found") -var r53ValidRecordTypes = regexp.MustCompile("^(A|AAAA|CAA|CNAME|MX|NAPTR|NS|PTR|SOA|SPF|SRV|TXT|DS)$") +const ( + recordSetSyncMinDelay = 10 + recordSetSyncMaxDelay = 30 +) + +var ( + r53NoRecordsFound = errors.New("No matching records found") + r53NoHostedZoneFound = errors.New("No matching Hosted Zone found") + r53ValidRecordTypes = regexp.MustCompile("^(A|AAAA|CAA|CNAME|MX|NAPTR|NS|PTR|SOA|SPF|SRV|TXT|DS)$") +) func ResourceRecord() *schema.Resource { //lintignore:R011 @@ -497,7 +504,7 @@ func WaitForRecordSetToSync(conn *route53.Route53, requestId string) error { wait := resource.StateChangeConf{ Pending: []string{route53.ChangeStatusPending}, Target: []string{route53.ChangeStatusInsync}, - Delay: time.Duration(rand.Int63n(20)+10) * time.Second, + Delay: time.Duration(rand.Int63n(recordSetSyncMaxDelay-recordSetSyncMinDelay)+recordSetSyncMinDelay) * time.Second, MinTimeout: 5 * time.Second, PollInterval: 20 * time.Second, Timeout: 30 * time.Minute, diff --git a/internal/service/route53/zone.go b/internal/service/route53/zone.go index df7d50bd8dd..ad8326f5951 100644 --- a/internal/service/route53/zone.go +++ b/internal/service/route53/zone.go @@ -24,6 +24,13 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) +const ( + zoneChangeSyncMinDelay = 10 + zoneChangeSyncMaxDelay = 30 + zoneChangeSyncMinPollInterval = 15 + zoneChangeSyncMaxPollInterval = 30 +) + func ResourceZone() *schema.Resource { return &schema.Resource{ Create: resourceZoneCreate, @@ -688,9 +695,9 @@ func route53WaitForChangeSynchronization(conn *route53.Route53, changeID string) conf := resource.StateChangeConf{ Pending: []string{route53.ChangeStatusPending}, Target: []string{route53.ChangeStatusInsync}, - Delay: time.Duration(rand.Int63n(20)+10) * time.Second, + Delay: time.Duration(rand.Int63n(zoneChangeSyncMaxDelay-zoneChangeSyncMinDelay)+zoneChangeSyncMinDelay) * time.Second, MinTimeout: 5 * time.Second, - PollInterval: time.Duration(rand.Int63n(15)+15) * time.Second, + PollInterval: time.Duration(rand.Int63n(zoneChangeSyncMaxPollInterval-zoneChangeSyncMinPollInterval)+zoneChangeSyncMinPollInterval) * time.Second, Timeout: 15 * time.Minute, Refresh: func() (result interface{}, state string, err error) { input := &route53.GetChangeInput{ diff --git a/internal/service/route53resolver/endpoint.go b/internal/service/route53resolver/endpoint.go index 0d936d4845c..58abfa34a4e 100644 --- a/internal/service/route53resolver/endpoint.go +++ b/internal/service/route53resolver/endpoint.go @@ -23,6 +23,12 @@ const ( EndpointStatusDeleted = "DELETED" ) +const ( + endpointCreatedDefaultTimeout = 10 * time.Minute + endpointUpdatedDefaultTimeout = 10 * time.Minute + endpointDeletedDefaultTimeout = 10 * time.Minute +) + func ResourceEndpoint() *schema.Resource { return &schema.Resource{ Create: resourceEndpointCreate, @@ -101,9 +107,9 @@ func ResourceEndpoint() *schema.Resource { }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Update: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(10 * time.Minute), + Create: schema.DefaultTimeout(endpointCreatedDefaultTimeout), + Update: schema.DefaultTimeout(endpointUpdatedDefaultTimeout), + Delete: schema.DefaultTimeout(endpointDeletedDefaultTimeout), }, CustomizeDiff: verify.SetTagsDiff, diff --git a/internal/service/route53resolver/rule.go b/internal/service/route53resolver/rule.go index 9f3c171e713..6e62e565107 100644 --- a/internal/service/route53resolver/rule.go +++ b/internal/service/route53resolver/rule.go @@ -25,6 +25,12 @@ const ( RuleStatusDeleted = "DELETED" ) +const ( + ruleCreatedDefaultTimeout = 10 * time.Minute + ruleUpdatedDefaultTimeout = 10 * time.Minute + ruleDeletedDefaultTimeout = 10 * time.Minute +) + func ResourceRule() *schema.Resource { return &schema.Resource{ Create: resourceRuleCreate, @@ -40,9 +46,9 @@ func ResourceRule() *schema.Resource { }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Update: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(10 * time.Minute), + Create: schema.DefaultTimeout(ruleCreatedDefaultTimeout), + Update: schema.DefaultTimeout(ruleUpdatedDefaultTimeout), + Delete: schema.DefaultTimeout(ruleDeletedDefaultTimeout), }, Schema: map[string]*schema.Schema{ diff --git a/internal/service/route53resolver/rule_association.go b/internal/service/route53resolver/rule_association.go index 2e869db7b9d..46e4f874636 100644 --- a/internal/service/route53resolver/rule_association.go +++ b/internal/service/route53resolver/rule_association.go @@ -18,6 +18,11 @@ const ( RuleAssociationStatusDeleted = "DELETED" ) +const ( + ruleAssociationCreatedDefaultTimeout = 10 * time.Minute + ruleAssociationDeletedDefaultTimeout = 10 * time.Minute +) + func ResourceRuleAssociation() *schema.Resource { return &schema.Resource{ Create: resourceRuleAssociationCreate, @@ -28,8 +33,8 @@ func ResourceRuleAssociation() *schema.Resource { }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(10 * time.Minute), + Create: schema.DefaultTimeout(ruleAssociationCreatedDefaultTimeout), + Delete: schema.DefaultTimeout(ruleAssociationDeletedDefaultTimeout), }, Schema: map[string]*schema.Schema{ diff --git a/internal/service/route53resolver/sweep.go b/internal/service/route53resolver/sweep.go index ed472b33739..dd72d1a8ef2 100644 --- a/internal/service/route53resolver/sweep.go +++ b/internal/service/route53resolver/sweep.go @@ -6,7 +6,6 @@ package route53resolver import ( "fmt" "log" - "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" @@ -177,7 +176,7 @@ func sweepEndpoints(region string) error { continue } - err = EndpointWaitUntilTargetState(conn, id, 10*time.Minute, + err = EndpointWaitUntilTargetState(conn, id, endpointDeletedDefaultTimeout, []string{route53resolver.ResolverEndpointStatusDeleting}, []string{EndpointStatusDeleted}) if err != nil { @@ -588,7 +587,7 @@ func sweepRuleAssociations(region string) error { continue } - err = RuleAssociationWaitUntilTargetState(conn, id, 10*time.Minute, + err = RuleAssociationWaitUntilTargetState(conn, id, ruleAssociationDeletedDefaultTimeout, []string{route53resolver.ResolverRuleAssociationStatusDeleting}, []string{RuleAssociationStatusDeleted}) if err != nil { @@ -644,7 +643,7 @@ func sweepRules(region string) error { continue } - err = RuleWaitUntilTargetState(conn, id, 10*time.Minute, + err = RuleWaitUntilTargetState(conn, id, ruleDeletedDefaultTimeout, []string{route53resolver.ResolverRuleStatusDeleting}, []string{RuleStatusDeleted}) if err != nil { diff --git a/tools/go.mod b/tools/go.mod index 1845a4920b5..eff3157e4dd 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -21,3 +21,5 @@ replace github.com/hashicorp/go-changelog => github.com/breathingdust/go-changel // v1.5.1 was incorrectly built exclude github.com/hashicorp/go-getter v1.5.1 + +replace github.com/tommy-muehle/go-mnd/v2 => github.com/gdavison/go-mnd/v2 v2.4.1-0.20211001004251-d5db99f5fd61 diff --git a/tools/go.sum b/tools/go.sum index 0a92bb4f2c8..6fa45c1d7dd 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -228,6 +228,8 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/fullstorydev/grpcurl v1.6.0/go.mod h1:ZQ+ayqbKMJNhzLmbpCiurTVlaK2M/3nqZCxaQ2Ze/sM= github.com/fzipp/gocyclo v0.3.1 h1:A9UeX3HJSXTBzvHzhqoYVuE0eAhe+aM8XBCCwsPMZOc= github.com/fzipp/gocyclo v0.3.1/go.mod h1:DJHO6AUmbdqj2ET4Z9iArSuwWgYDRryYt2wASxc7x3E= +github.com/gdavison/go-mnd/v2 v2.4.1-0.20211001004251-d5db99f5fd61 h1:hKrCOUfOn67BFceaHxu1NRyeeGw8nvAxnQ/LoH+31Xk= +github.com/gdavison/go-mnd/v2 v2.4.1-0.20211001004251-d5db99f5fd61/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= github.com/gdavison/terrafmt v0.3.1-0.20210204054728-84242796be99 h1:6Plt7xsU0Z1l7hu37EshJXFFi0VxGsmRG+i3lr6X/NA= github.com/gdavison/terrafmt v0.3.1-0.20210204054728-84242796be99/go.mod h1:B3IJj041fZWEirIxp4l2YGNYXH1PdptEu8we8YzQm/8= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= @@ -895,8 +897,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1 github.com/tomarrell/wrapcheck/v2 v2.3.0 h1:i3DNjtyyL1xwaBQOsPPk8LAcpayWfQv2rxNi9b/eEx4= github.com/tomarrell/wrapcheck/v2 v2.3.0/go.mod h1:aF5rnkdtqNWP/gC7vPUO5pKsB0Oac2FDTQP4F+dpZMU= github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= -github.com/tommy-muehle/go-mnd/v2 v2.4.0 h1:1t0f8Uiaq+fqKteUR4N9Umr6E99R+lDnLnq7PwX2PPE= -github.com/tommy-muehle/go-mnd/v2 v2.4.0/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= From 9e1cca86c3154cb1d1a7006f766f217bdeaf07a8 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 18 Oct 2021 14:38:20 -0700 Subject: [PATCH 3/3] Extends `golangci-lint` timeout to 20 minutes --- .golangci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 27b9ecc8c99..86fe1b62905 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -72,4 +72,4 @@ linters-settings: - gomnd run: - timeout: 15m + timeout: 20m