diff --git a/.semgrep.yml b/.semgrep.yml index b5ca7b36efb..e4f58f08fd8 100644 --- a/.semgrep.yml +++ b/.semgrep.yml @@ -43,27 +43,24 @@ rules: languages: [go] message: Prefer AWS Go SDK pointer conversion functions for dereferencing during assignment, e.g. aws.StringValue() paths: - exclude: - - aws/cloudfront_distribution_configuration_structure.go - - aws/data_source_aws_route_table.go - - aws/opsworks_layers.go - - aws/resource_aws_d* - - aws/resource_aws_e* - - aws/resource_aws_g* - - aws/resource_aws_i* - - aws/resource_aws_k* - - aws/resource_aws_l* - - aws/resource_aws_mq_broker.go - - aws/resource_aws_o* - - aws/resource_aws_r* - - aws/resource_aws_s* - - aws/structure.go - - aws/waf_helpers.go - - aws/internal/generators/ - - aws/internal/keyvaluetags/ - - providerlint/vendor/ include: - - aws/ + - internal/service + exclude: + - internal/service/ec2 + - internal/service/elasticbeanstalk + - internal/service/elasticsearch + - internal/service/elb + - internal/service/emr + - internal/service/gamelift + - internal/service/iam + - internal/service/lambda + - internal/service/opsworks + - internal/service/rds + - internal/service/redshift + - internal/service/route53 + - internal/service/s3 + - internal/service/servicediscovery + - internal/service/ssm patterns: - pattern: '$LHS = *$RHS' - pattern-not: '*$LHS2 = *$RHS' @@ -121,7 +118,7 @@ rules: message: Prefer AWS Go SDK pointer conversion aws.StringValue() function for dereferencing during d.SetId() paths: include: - - aws/ + - internal/ pattern: 'd.SetId(*$VALUE)' severity: WARNING @@ -131,7 +128,7 @@ rules: message: Using AWS Go SDK pointer conversion, e.g. aws.String(), with immediate dereferencing is extraneous paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: '*aws.Bool($VALUE)' @@ -146,7 +143,7 @@ rules: message: Calling a resource's Read method from within a data-source is discouraged paths: include: - - aws/data_source_aws_*.go + - internal/service/**/*_data_source.go patterns: - pattern-regex: '(resource.+Read|flatten.+Resource)' - pattern-inside: func $FUNCNAME(...) $RETURNTYPE { ... } @@ -164,7 +161,7 @@ rules: message: Using `acctest.RandInt()` in constant or variable declaration will execute during compilation and not randomize, pass into string generating function instead paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: const $CONST = fmt.Sprintf(..., <... acctest.RandInt() ...>, ...) @@ -176,7 +173,7 @@ rules: message: Using `acctest.RandString()` in constant or variable declaration will execute during compilation and not randomize, pass into string generating function instead paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: const $CONST = fmt.Sprintf(..., <... acctest.RandString(...) ...>, ...) @@ -188,7 +185,7 @@ rules: message: Using `acctest.RandomWithPrefix()` in constant or variable declaration will execute during compilation and not randomize, pass into string generating function instead paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: const $CONST = fmt.Sprintf(..., <... acctest.RandomWithPrefix(...) ...>, ...) @@ -200,7 +197,7 @@ rules: message: Prefer `flattenStringSet()` function for casting a list of string pointers to a set paths: include: - - aws/ + - internal/ pattern: schema.NewSet(schema.HashString, flattenStringList($APIOBJECT)) severity: WARNING @@ -209,7 +206,7 @@ rules: message: Prefer `expandStringSet()` function for casting a set to a list of string pointers paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: expandStringList($SET.List()) @@ -224,7 +221,7 @@ rules: message: Zero value conditional check after `d.GetOk()` is extraneous paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: if $VALUE, $OK := d.GetOk($KEY); $OK && $VALUE.(bool) { $BODY } @@ -240,7 +237,7 @@ rules: message: AWS Go SDK pointer conversion function for `d.Set()` value is extraneous paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: d.Set($ATTRIBUTE, aws.BoolValue($APIOBJECT)) @@ -251,28 +248,29 @@ rules: - pattern: d.Set($ATTRIBUTE, aws.StringValue($APIOBJECT)) severity: WARNING - - id: helper-schema-ResourceData-DataSource-Set-tags - languages: [go] - message: (schema.ResourceData).Set() call with the tags key should include IgnoreConfig in the value - paths: - include: - - aws/data_source*.go - exclude: - - aws/resource*.go - patterns: - - pattern-inside: func $READMETHOD(...) $ERRORTYPE { ... } - - pattern: if err := d.Set("tags", $TAGSMAP); err != nil { ... } - - pattern-not: if err := d.Set("tags", $KEYVALUETAGS.IgnoreAws().IgnoreConfig($CONFIG).Map()); err != nil { ... } - severity: WARNING + # Not sure why this isn't working + # - id: helper-schema-ResourceData-DataSource-Set-tags + # languages: [go] + # message: (schema.ResourceData).Set() call with the tags key should include IgnoreConfig in the value + # paths: + # include: + # - internal/service/**/*_data_source.go + # exclude: + # - internal/service/**/*.go + # patterns: + # - pattern-inside: func $READMETHOD(...) $ERRORTYPE { ... } + # - pattern: if err := d.Set("tags", $TAGSMAP); err != nil { ... } + # - pattern-not: if err := d.Set("tags", $KEYVALUETAGS.IgnoreAws().IgnoreConfig($CONFIG).Map()); err != nil { ... } + # severity: WARNING - id: helper-schema-ResourceData-Resource-Set-tags languages: [go] message: (schema.ResourceData).Set() call with the tags key should be preceded by a call to IgnoreConfig or include IgnoreConfig in the value in the case of ASG paths: include: - - aws/resource*.go + - internal/service/**/*.go exclude: - - aws/data_source*.go + - internal/service/**/*_data_source.go patterns: - pattern-inside: func $READMETHOD(...) $ERRORTYPE { ... } - pattern-either: @@ -301,6 +299,9 @@ rules: - pattern-not: | tags = keyvaluetags.$VALUETAGS($RESOURCETAGS).IgnoreAws().IgnoreConfig($CONFIG) ... + - pattern-not: | + tags = $VALUETAGS($RESOURCETAGS).IgnoreAWS().IgnoreConfig($CONFIG).Ignore($IGNORE) + ... severity: WARNING - id: helper-schema-ResourceData-SetId-empty-without-IsNewResource-check @@ -352,9 +353,9 @@ rules: paths: exclude: - "*_test.go" - - aws/internal/tfresource/*.go + - sweep.go include: - - aws/ + - internal/ patterns: - pattern-either: - patterns: @@ -434,7 +435,7 @@ rules: exclude: - "*_test.go" include: - - aws/ + - internal/ patterns: - pattern-either: - patterns: @@ -486,7 +487,7 @@ rules: message: Check for resource.NotFoundError errors with tfresource.NotFound() paths: include: - - aws/ + - internal/ patterns: - pattern-either: - patterns: @@ -510,7 +511,7 @@ rules: message: Use time.Equal() instead of == paths: include: - - aws/ + - internal/ patterns: - pattern-either: - pattern: | @@ -536,7 +537,7 @@ rules: message: Use lastPage for bool variable in pagination functions paths: include: - - aws/ + - internal/ patterns: - pattern: | $X.$Z(..., func(..., $Y bool) { @@ -559,10 +560,10 @@ rules: languages: [go] message: Do not call `fmt.Print` and variant paths: + include: + - internal/ exclude: - providerlint/vendor/ - include: - - aws/ patterns: - pattern-either: - pattern: | @@ -595,7 +596,7 @@ rules: message: Use default email address or generate a random email address. https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/running-and-writing-acceptance-tests.md#hardcoded-email-addresses paths: include: - - aws/ + - internal/ patterns: - pattern-regex: '[-_A-Za-z0-9.+]+@([-A-Za-z0-9]+\.)(com|net|org)' - pattern-not-regex: 'no-reply@hashicorp\.com' @@ -607,7 +608,7 @@ rules: message: Generate random SSH keys using acctest.RandSSHKeyPair() or RandSSHKeyPairSize(). https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/running-and-writing-acceptance-tests.md#hardcoded-ssh-key paths: include: - - aws/ + - internal/ exclude: - providerlint/vendor/ patterns: @@ -622,7 +623,7 @@ rules: message: Incorrect form of non-tags change detection. https://github.com/hashicorp/terraform-provider-aws/blob/main/docs/contributing/contribution-checklists.md#resource-tagging-code-implementation paths: include: - - aws/ + - internal/ patterns: - pattern: 'if d.HasChangeExcept("tags_all") {...}' severity: WARNING diff --git a/internal/service/apigateway/flex.go b/internal/service/apigateway/flex.go index 2d2794936ab..14c0a215f70 100644 --- a/internal/service/apigateway/flex.go +++ b/internal/service/apigateway/flex.go @@ -112,11 +112,11 @@ func FlattenThrottleSettings(settings *apigateway.ThrottleSettings) []map[string if settings != nil { r := make(map[string]interface{}) if settings.BurstLimit != nil { - r["burst_limit"] = *settings.BurstLimit + r["burst_limit"] = aws.Int64Value(settings.BurstLimit) } if settings.RateLimit != nil { - r["rate_limit"] = *settings.RateLimit + r["rate_limit"] = aws.Float64Value(settings.RateLimit) } result = append(result, r) diff --git a/internal/service/autoscaling/launch_configuration.go b/internal/service/autoscaling/launch_configuration.go index 2d5bc4becfd..08440500bff 100644 --- a/internal/service/autoscaling/launch_configuration.go +++ b/internal/service/autoscaling/launch_configuration.go @@ -744,15 +744,11 @@ func readBlockDevicesFromLaunchConfiguration(d *schema.ResourceData, lc *autosca if len(lc.BlockDeviceMappings) == 0 { return nil, nil } - rootDeviceName, err := fetchRootDeviceName(d.Get("image_id").(string), ec2conn) + v, err := fetchRootDeviceName(d.Get("image_id").(string), ec2conn) if err != nil { return nil, err } - if rootDeviceName == nil { - // We do this so the value is empty so we don't have to do nil checks later - var blank string - rootDeviceName = &blank - } + rootDeviceName := aws.StringValue(v) // Collect existing configured devices, so we can check // existing value of delete_on_termination below @@ -777,41 +773,41 @@ func readBlockDevicesFromLaunchConfiguration(d *schema.ResourceData, lc *autosca } bd["delete_on_termination"] = deleteOnTermination } else if bdm.Ebs != nil && bdm.Ebs.DeleteOnTermination != nil { - bd["delete_on_termination"] = *bdm.Ebs.DeleteOnTermination + bd["delete_on_termination"] = aws.BoolValue(bdm.Ebs.DeleteOnTermination) } if bdm.Ebs != nil && bdm.Ebs.VolumeSize != nil { - bd["volume_size"] = *bdm.Ebs.VolumeSize + bd["volume_size"] = aws.Int64Value(bdm.Ebs.VolumeSize) } if bdm.Ebs != nil && bdm.Ebs.VolumeType != nil { - bd["volume_type"] = *bdm.Ebs.VolumeType + bd["volume_type"] = aws.StringValue(bdm.Ebs.VolumeType) } if bdm.Ebs != nil && bdm.Ebs.Iops != nil { - bd["iops"] = *bdm.Ebs.Iops + bd["iops"] = aws.Int64Value(bdm.Ebs.Iops) } if bdm.Ebs != nil && bdm.Ebs.Throughput != nil { - bd["throughput"] = *bdm.Ebs.Throughput + bd["throughput"] = aws.Int64Value(bdm.Ebs.Throughput) } if bdm.Ebs != nil && bdm.Ebs.Encrypted != nil { - bd["encrypted"] = *bdm.Ebs.Encrypted + bd["encrypted"] = aws.BoolValue(bdm.Ebs.Encrypted) } - if bdm.DeviceName != nil && *bdm.DeviceName == *rootDeviceName { + if bdm.DeviceName != nil && aws.StringValue(bdm.DeviceName) == rootDeviceName { blockDevices["root"] = bd } else { if bdm.DeviceName != nil { - bd["device_name"] = *bdm.DeviceName + bd["device_name"] = aws.StringValue(bdm.DeviceName) } if bdm.VirtualName != nil { - bd["virtual_name"] = *bdm.VirtualName + bd["virtual_name"] = aws.StringValue(bdm.VirtualName) blockDevices["ephemeral"] = append(blockDevices["ephemeral"].([]map[string]interface{}), bd) } else { if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil { - bd["snapshot_id"] = *bdm.Ebs.SnapshotId + bd["snapshot_id"] = aws.StringValue(bdm.Ebs.SnapshotId) } if bdm.NoDevice != nil { - bd["no_device"] = *bdm.NoDevice + bd["no_device"] = aws.BoolValue(bdm.NoDevice) } blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd) } diff --git a/internal/service/autoscaling/sweep.go b/internal/service/autoscaling/sweep.go index de2f1f74f84..6cacca29204 100644 --- a/internal/service/autoscaling/sweep.go +++ b/internal/service/autoscaling/sweep.go @@ -104,7 +104,7 @@ func sweepLaunchConfigurations(region string) error { } for _, lc := range resp.LaunchConfigurations { - name := *lc.LaunchConfigurationName + name := aws.StringValue(lc.LaunchConfigurationName) log.Printf("[INFO] Deleting Launch Configuration: %s", name) _, err := conn.DeleteLaunchConfiguration( diff --git a/internal/service/cloudformation/flex.go b/internal/service/cloudformation/flex.go index 4cc6bdc7119..e0a40388ae9 100644 --- a/internal/service/cloudformation/flex.go +++ b/internal/service/cloudformation/flex.go @@ -20,7 +20,7 @@ func expandParameters(params map[string]interface{}) []*cloudformation.Parameter func flattenAllCloudFormationParameters(cfParams []*cloudformation.Parameter) map[string]interface{} { params := make(map[string]interface{}, len(cfParams)) for _, p := range cfParams { - params[*p.ParameterKey] = *p.ParameterValue + params[aws.StringValue(p.ParameterKey)] = aws.StringValue(p.ParameterValue) } return params } @@ -28,7 +28,7 @@ func flattenAllCloudFormationParameters(cfParams []*cloudformation.Parameter) ma func flattenOutputs(cfOutputs []*cloudformation.Output) map[string]string { outputs := make(map[string]string, len(cfOutputs)) for _, o := range cfOutputs { - outputs[*o.OutputKey] = *o.OutputValue + outputs[aws.StringValue(o.OutputKey)] = aws.StringValue(o.OutputValue) } return outputs } @@ -40,9 +40,9 @@ func flattenParameters(cfParams []*cloudformation.Parameter, originalParams map[string]interface{}) map[string]interface{} { params := make(map[string]interface{}, len(cfParams)) for _, p := range cfParams { - _, isConfigured := originalParams[*p.ParameterKey] + _, isConfigured := originalParams[aws.StringValue(p.ParameterKey)] if isConfigured { - params[*p.ParameterKey] = *p.ParameterValue + params[aws.StringValue(p.ParameterKey)] = aws.StringValue(p.ParameterValue) } } return params diff --git a/internal/service/cloudfront/distribution_configuration_structure.go b/internal/service/cloudfront/distribution_configuration_structure.go index 14b8f1ea34b..778baeedaa0 100644 --- a/internal/service/cloudfront/distribution_configuration_structure.go +++ b/internal/service/cloudfront/distribution_configuration_structure.go @@ -386,7 +386,7 @@ func flattenCacheBehavior(cb *cloudfront.CacheBehavior) map[string]interface{} { m["max_ttl"] = int(*cb.MaxTTL) } if cb.SmoothStreaming != nil { - m["smooth_streaming"] = *cb.SmoothStreaming + m["smooth_streaming"] = aws.BoolValue(cb.SmoothStreaming) } if cb.DefaultTTL != nil { m["default_ttl"] = int(*cb.DefaultTTL) @@ -398,7 +398,7 @@ func flattenCacheBehavior(cb *cloudfront.CacheBehavior) map[string]interface{} { m["cached_methods"] = FlattenCachedMethods(cb.AllowedMethods.CachedMethods) } if cb.PathPattern != nil { - m["path_pattern"] = *cb.PathPattern + m["path_pattern"] = aws.StringValue(cb.PathPattern) } return m } @@ -1154,7 +1154,7 @@ func FlattenCustomErrorResponse(er *cloudfront.CustomErrorResponse) map[string]i m["response_code"], _ = strconv.Atoi(*er.ResponseCode) } if er.ResponsePagePath != nil { - m["response_page_path"] = *er.ResponsePagePath + m["response_page_path"] = aws.StringValue(er.ResponsePagePath) } return m } @@ -1285,18 +1285,18 @@ func flattenViewerCertificate(vc *cloudfront.ViewerCertificate) []interface{} { m := make(map[string]interface{}) if vc.IAMCertificateId != nil { - m["iam_certificate_id"] = *vc.IAMCertificateId - m["ssl_support_method"] = *vc.SSLSupportMethod + m["iam_certificate_id"] = aws.StringValue(vc.IAMCertificateId) + m["ssl_support_method"] = aws.StringValue(vc.SSLSupportMethod) } if vc.ACMCertificateArn != nil { - m["acm_certificate_arn"] = *vc.ACMCertificateArn - m["ssl_support_method"] = *vc.SSLSupportMethod + m["acm_certificate_arn"] = aws.StringValue(vc.ACMCertificateArn) + m["ssl_support_method"] = aws.StringValue(vc.SSLSupportMethod) } if vc.CloudFrontDefaultCertificate != nil { - m["cloudfront_default_certificate"] = *vc.CloudFrontDefaultCertificate + m["cloudfront_default_certificate"] = aws.BoolValue(vc.CloudFrontDefaultCertificate) } if vc.MinimumProtocolVersion != nil { - m["minimum_protocol_version"] = *vc.MinimumProtocolVersion + m["minimum_protocol_version"] = aws.StringValue(vc.MinimumProtocolVersion) } return []interface{}{m} } diff --git a/internal/service/cognitoidentity/flex.go b/internal/service/cognitoidentity/flex.go index 17f05119265..0226be8a6d6 100644 --- a/internal/service/cognitoidentity/flex.go +++ b/internal/service/cognitoidentity/flex.go @@ -110,11 +110,11 @@ func flattenIdentityPoolRoleMappingsAttachment(rms map[string]*cognitoidentity.R } if v.Type != nil { - m["type"] = *v.Type + m["type"] = aws.StringValue(v.Type) } if v.AmbiguousRoleResolution != nil { - m["ambiguous_role_resolution"] = *v.AmbiguousRoleResolution + m["ambiguous_role_resolution"] = aws.StringValue(v.AmbiguousRoleResolution) } if v.RulesConfiguration != nil && v.RulesConfiguration.Rules != nil { @@ -128,23 +128,15 @@ func flattenIdentityPoolRoleMappingsAttachment(rms map[string]*cognitoidentity.R return roleMappings } -func flattenIdentityPoolRoles(config map[string]*string) map[string]string { - m := map[string]string{} - for k, v := range config { - m[k] = *v - } - return m -} - func flattenIdentityPoolRolesAttachmentMappingRules(d []*cognitoidentity.MappingRule) []interface{} { rules := make([]interface{}, 0) for _, rule := range d { r := make(map[string]interface{}) - r["claim"] = *rule.Claim - r["match_type"] = *rule.MatchType - r["role_arn"] = *rule.RoleARN - r["value"] = *rule.Value + r["claim"] = aws.StringValue(rule.Claim) + r["match_type"] = aws.StringValue(rule.MatchType) + r["role_arn"] = aws.StringValue(rule.RoleARN) + r["value"] = aws.StringValue(rule.Value) rules = append(rules, r) } @@ -163,15 +155,15 @@ func flattenIdentityProviders(ips []*cognitoidentity.Provider) []map[string]inte } if v.ClientId != nil { - ip["client_id"] = *v.ClientId + ip["client_id"] = aws.StringValue(v.ClientId) } if v.ProviderName != nil { - ip["provider_name"] = *v.ProviderName + ip["provider_name"] = aws.StringValue(v.ProviderName) } if v.ServerSideTokenCheck != nil { - ip["server_side_token_check"] = *v.ServerSideTokenCheck + ip["server_side_token_check"] = aws.BoolValue(v.ServerSideTokenCheck) } values = append(values, ip) @@ -179,11 +171,3 @@ func flattenIdentityProviders(ips []*cognitoidentity.Provider) []map[string]inte return values } - -func flattenSupportedLoginProviders(config map[string]*string) map[string]string { - m := map[string]string{} - for k, v := range config { - m[k] = *v - } - return m -} diff --git a/internal/service/cognitoidentity/pool.go b/internal/service/cognitoidentity/pool.go index 9ac03e06488..910f2ab3aac 100644 --- a/internal/service/cognitoidentity/pool.go +++ b/internal/service/cognitoidentity/pool.go @@ -204,19 +204,19 @@ func resourcePoolRead(d *schema.ResourceData, meta interface{}) error { } if err := d.Set("cognito_identity_providers", flattenIdentityProviders(ip.CognitoIdentityProviders)); err != nil { - return fmt.Errorf("Error setting cognito_identity_providers error: %#v", err) + return fmt.Errorf("Error setting cognito_identity_providers error: %w", err) } if err := d.Set("openid_connect_provider_arns", flex.FlattenStringList(ip.OpenIdConnectProviderARNs)); err != nil { - return fmt.Errorf("Error setting openid_connect_provider_arns error: %#v", err) + return fmt.Errorf("Error setting openid_connect_provider_arns error: %w", err) } if err := d.Set("saml_provider_arns", flex.FlattenStringList(ip.SamlProviderARNs)); err != nil { - return fmt.Errorf("Error setting saml_provider_arns error: %#v", err) + return fmt.Errorf("Error setting saml_provider_arns error: %w", err) } - if err := d.Set("supported_login_providers", flattenSupportedLoginProviders(ip.SupportedLoginProviders)); err != nil { - return fmt.Errorf("Error setting supported_login_providers error: %#v", err) + if err := d.Set("supported_login_providers", aws.StringValueMap(ip.SupportedLoginProviders)); err != nil { + return fmt.Errorf("Error setting supported_login_providers error: %w", err) } return nil diff --git a/internal/service/cognitoidentity/pool_roles_attachment.go b/internal/service/cognitoidentity/pool_roles_attachment.go index 239fde994e3..943338a01cb 100644 --- a/internal/service/cognitoidentity/pool_roles_attachment.go +++ b/internal/service/cognitoidentity/pool_roles_attachment.go @@ -159,7 +159,7 @@ func resourcePoolRolesAttachmentRead(d *schema.ResourceData, meta interface{}) e d.Set("identity_pool_id", ip.IdentityPoolId) - if err := d.Set("roles", flattenIdentityPoolRoles(ip.Roles)); err != nil { + if err := d.Set("roles", aws.StringValueMap(ip.Roles)); err != nil { return fmt.Errorf("Error setting roles error: %#v", err) } diff --git a/internal/service/configservice/flex.go b/internal/service/configservice/flex.go index f241d1b739c..d5f3c6db9c5 100644 --- a/internal/service/configservice/flex.go +++ b/internal/service/configservice/flex.go @@ -164,11 +164,11 @@ func flattenRecordingGroup(g *configservice.RecordingGroup) []map[string]interfa m := make(map[string]interface{}, 1) if g.AllSupported != nil { - m["all_supported"] = *g.AllSupported + m["all_supported"] = aws.BoolValue(g.AllSupported) } if g.IncludeGlobalResourceTypes != nil { - m["include_global_resource_types"] = *g.IncludeGlobalResourceTypes + m["include_global_resource_types"] = aws.BoolValue(g.IncludeGlobalResourceTypes) } if g.ResourceTypes != nil && len(g.ResourceTypes) > 0 { @@ -183,16 +183,16 @@ func flattenRuleScope(scope *configservice.Scope) []interface{} { m := make(map[string]interface{}) if scope.ComplianceResourceId != nil { - m["compliance_resource_id"] = *scope.ComplianceResourceId + m["compliance_resource_id"] = aws.StringValue(scope.ComplianceResourceId) } if scope.ComplianceResourceTypes != nil { m["compliance_resource_types"] = flex.FlattenStringSet(scope.ComplianceResourceTypes) } if scope.TagKey != nil { - m["tag_key"] = *scope.TagKey + m["tag_key"] = aws.StringValue(scope.TagKey) } if scope.TagValue != nil { - m["tag_value"] = *scope.TagValue + m["tag_value"] = aws.StringValue(scope.TagValue) } items = append(items, m) @@ -202,8 +202,8 @@ func flattenRuleScope(scope *configservice.Scope) []interface{} { func flattenRuleSource(source *configservice.Source) []interface{} { var result []interface{} m := make(map[string]interface{}) - m["owner"] = *source.Owner - m["source_identifier"] = *source.SourceIdentifier + m["owner"] = aws.StringValue(source.Owner) + m["source_identifier"] = aws.StringValue(source.SourceIdentifier) if len(source.SourceDetails) > 0 { m["source_detail"] = schema.NewSet(ruleSourceDetailsHash, flattenRuleSourceDetails(source.SourceDetails)) } @@ -216,13 +216,13 @@ func flattenRuleSourceDetails(details []*configservice.SourceDetail) []interface for _, d := range details { m := make(map[string]interface{}) if d.MessageType != nil { - m["message_type"] = *d.MessageType + m["message_type"] = aws.StringValue(d.MessageType) } if d.EventSource != nil { - m["event_source"] = *d.EventSource + m["event_source"] = aws.StringValue(d.EventSource) } if d.MaximumExecutionFrequency != nil { - m["maximum_execution_frequency"] = *d.MaximumExecutionFrequency + m["maximum_execution_frequency"] = aws.StringValue(d.MaximumExecutionFrequency) } items = append(items, m) @@ -235,7 +235,7 @@ func flattenSnapshotDeliveryProperties(p *configservice.ConfigSnapshotDeliveryPr m := make(map[string]interface{}) if p.DeliveryFrequency != nil { - m["delivery_frequency"] = *p.DeliveryFrequency + m["delivery_frequency"] = aws.StringValue(p.DeliveryFrequency) } return []map[string]interface{}{m} diff --git a/internal/service/dax/cluster.go b/internal/service/dax/cluster.go index 4b8fc72c290..10fafec2a77 100644 --- a/internal/service/dax/cluster.go +++ b/internal/service/dax/cluster.go @@ -584,7 +584,7 @@ func daxClusterStateRefreshFunc(conn *dax.DAX, clusterID, givenState string, pen // return the current state if it's in the pending array for _, p := range pending { log.Printf("[DEBUG] DAX: checking pending state (%s) for cluster (%s), cluster status: %s", pending, clusterID, *c.Status) - s := *c.Status + s := aws.StringValue(c.Status) if p == s { log.Printf("[DEBUG] Return with status: %v", *c.Status) return c, p, nil diff --git a/internal/service/docdb/sweep.go b/internal/service/docdb/sweep.go index 3e8b432f196..5d2887e2c79 100644 --- a/internal/service/docdb/sweep.go +++ b/internal/service/docdb/sweep.go @@ -12,12 +12,13 @@ import ( "github.com/aws/aws-sdk-go/service/docdb" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/sweep" ) func init() { resource.AddTestSweepers("aws_docdb_global_cluster", &resource.Sweeper{ Name: "aws_docdb_global_cluster", - F: testSweepDocDBGlobalClusters, + F: sweepGlobalClusters, Dependencies: []string{ "aws_docdb_cluster", }, @@ -50,14 +51,14 @@ func sweepGlobalClusters(region string) error { continue } - if err := WaitForDocDBGlobalClusterDeletion(context.TODO(), conn, id); err != nil { + if err := WaitForGlobalClusterDeletion(context.TODO(), conn, id, GlobalClusterDeleteTimeout); err != nil { log.Printf("[ERROR] Failure while waiting for DocDB Global Cluster (%s) to be deleted: %s", id, err) } } return !lastPage }) - if testSweepSkipSweepError(err) { + if sweep.SkipSweepError(err) { log.Printf("[WARN] Skipping DocDB Global Cluster sweep for %s: %s", region, err) return nil } diff --git a/internal/service/dynamodb/global_table.go b/internal/service/dynamodb/global_table.go index 45186302404..ce9848f2f42 100644 --- a/internal/service/dynamodb/global_table.go +++ b/internal/service/dynamodb/global_table.go @@ -310,6 +310,6 @@ func flattenReplicas(replicaDescriptions []*dynamodb.ReplicaDescription) []inter func flattenReplica(replicaDescription *dynamodb.ReplicaDescription) map[string]interface{} { replica := make(map[string]interface{}) - replica["region_name"] = *replicaDescription.RegionName + replica["region_name"] = aws.StringValue(replicaDescription.RegionName) return replica } diff --git a/internal/service/ecr/repository.go b/internal/service/ecr/repository.go index 3518fd180c9..225606304fe 100644 --- a/internal/service/ecr/repository.go +++ b/internal/service/ecr/repository.go @@ -135,7 +135,7 @@ func resourceRepositoryCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error creating ECR repository: %s", err) } - repository := *out.Repository + repository := *out.Repository // nosemgrep: prefer-aws-go-sdk-pointer-conversion-assignment // false positive log.Printf("[DEBUG] ECR repository created: %q", *repository.RepositoryArn) diff --git a/internal/service/ecs/flex.go b/internal/service/ecs/flex.go index d0654fee5a6..68f5ca395c7 100644 --- a/internal/service/ecs/flex.go +++ b/internal/service/ecs/flex.go @@ -43,11 +43,11 @@ func flattenECSLoadBalancers(list []*ecs.LoadBalancer) []map[string]interface{} } if loadBalancer.LoadBalancerName != nil { - l["elb_name"] = *loadBalancer.LoadBalancerName + l["elb_name"] = aws.StringValue(loadBalancer.LoadBalancerName) } if loadBalancer.TargetGroupArn != nil { - l["target_group_arn"] = *loadBalancer.TargetGroupArn + l["target_group_arn"] = aws.StringValue(loadBalancer.TargetGroupArn) } result = append(result, l) diff --git a/internal/service/ecs/task_definition.go b/internal/service/ecs/task_definition.go index ca634c7df69..2e0c96602a8 100644 --- a/internal/service/ecs/task_definition.go +++ b/internal/service/ecs/task_definition.go @@ -500,7 +500,7 @@ func resourceTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) erro return err } - taskDefinition := *out.TaskDefinition + taskDefinition := *out.TaskDefinition // nosemgrep: prefer-aws-go-sdk-pointer-conversion-assignment // false positive log.Printf("[DEBUG] ECS task definition registered: %q (rev. %d)", aws.StringValue(taskDefinition.TaskDefinitionArn), aws.Int64Value(taskDefinition.Revision)) diff --git a/internal/service/ecs/task_definition_test.go b/internal/service/ecs/task_definition_test.go index f5cb5f8b309..79ae3df0a4d 100644 --- a/internal/service/ecs/task_definition_test.go +++ b/internal/service/ecs/task_definition_test.go @@ -945,7 +945,7 @@ func testAccCheckTaskDefinitionProxyConfiguration(after *ecs.TaskDefinition, con propertyLookups := make(map[string]string) for _, property := range properties { - propertyLookups[*property.Name] = *property.Value + propertyLookups[aws.StringValue(property.Name)] = aws.StringValue(property.Value) } if propertyLookups["IgnoredUID"] != ignoredUid { diff --git a/internal/service/elasticache/replication_group.go b/internal/service/elasticache/replication_group.go index 1047fd6ce7a..1a0d3f8d9f5 100644 --- a/internal/service/elasticache/replication_group.go +++ b/internal/service/elasticache/replication_group.go @@ -538,7 +538,7 @@ func resourceReplicationGroupRead(d *schema.ResourceData, meta interface{}) erro return nil } - cacheCluster := *rgp.NodeGroups[0].NodeGroupMembers[0] + cacheCluster := *rgp.NodeGroups[0].NodeGroupMembers[0] // nosemgrep: prefer-aws-go-sdk-pointer-conversion-assignment // false positive res, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{ CacheClusterId: cacheCluster.CacheClusterId, diff --git a/internal/service/elasticache/subnet_group.go b/internal/service/elasticache/subnet_group.go index 3179a988067..5a80f683cbc 100644 --- a/internal/service/elasticache/subnet_group.go +++ b/internal/service/elasticache/subnet_group.go @@ -148,7 +148,7 @@ func resourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { ids := make([]string, len(group.Subnets)) for i, s := range group.Subnets { - ids[i] = *s.SubnetIdentifier + ids[i] = aws.StringValue(s.SubnetIdentifier) } d.Set("arn", group.ARN) diff --git a/internal/service/glue/resource_policy_test.go b/internal/service/glue/resource_policy_test.go index 36622cb98e9..d01a4ce5c85 100644 --- a/internal/service/glue/resource_policy_test.go +++ b/internal/service/glue/resource_policy_test.go @@ -4,6 +4,7 @@ import ( "fmt" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/glue" "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -209,7 +210,7 @@ func testAccResourcePolicy(n string, action string) resource.TestCheckFunc { return fmt.Errorf("Get resource policy error: %v", err) } - actualPolicyText := *policy.PolicyInJson + actualPolicyText := aws.StringValue(policy.PolicyInJson) expectedPolicy := CreateTablePolicy(action) equivalent, err := awspolicy.PoliciesAreEquivalent(actualPolicyText, expectedPolicy) diff --git a/internal/service/kms/key_test.go b/internal/service/kms/key_test.go index 2620adef92b..3522deb2bf4 100644 --- a/internal/service/kms/key_test.go +++ b/internal/service/kms/key_test.go @@ -384,7 +384,7 @@ func testAccCheckKeyHasPolicy(name string, expectedPolicyText string) resource.T return err } - actualPolicyText := *out.Policy + actualPolicyText := aws.StringValue(out.Policy) equivalent, err := awspolicy.PoliciesAreEquivalent(actualPolicyText, expectedPolicyText) if err != nil { diff --git a/internal/service/mq/broker.go b/internal/service/mq/broker.go index 91d44ef0e01..807b932d1f7 100644 --- a/internal/service/mq/broker.go +++ b/internal/service/mq/broker.go @@ -875,13 +875,13 @@ func flattenMqWeeklyStartTime(wst *mq.WeeklyStartTime) []interface{} { } m := make(map[string]interface{}) if wst.DayOfWeek != nil { - m["day_of_week"] = *wst.DayOfWeek + m["day_of_week"] = aws.StringValue(wst.DayOfWeek) } if wst.TimeOfDay != nil { - m["time_of_day"] = *wst.TimeOfDay + m["time_of_day"] = aws.StringValue(wst.TimeOfDay) } if wst.TimeZone != nil { - m["time_zone"] = *wst.TimeZone + m["time_zone"] = aws.StringValue(wst.TimeZone) } return []interface{}{m} } diff --git a/internal/service/organizations/account.go b/internal/service/organizations/account.go index 42f49c6460c..5b6aaf8e93e 100644 --- a/internal/service/organizations/account.go +++ b/internal/service/organizations/account.go @@ -136,7 +136,7 @@ func resourceAccountCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error creating account: %s", err) } - requestId := *resp.CreateAccountStatus.Id + requestId := aws.StringValue(resp.CreateAccountStatus.Id) // Wait for the account to become available log.Printf("[DEBUG] Waiting for account request (%s) to succeed", requestId) diff --git a/internal/service/s3control/sweep.go b/internal/service/s3control/sweep.go index c10f319fdf6..7572c24b134 100644 --- a/internal/service/s3control/sweep.go +++ b/internal/service/s3control/sweep.go @@ -10,6 +10,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/service/s3control" + "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/sweep" @@ -46,6 +47,7 @@ func sweepAccessPoints(region string) error { AccountId: aws.String(accountID), } sweepResources := make([]*sweep.SweepResource, 0) + var sweeperErrs *multierror.Error err = conn.ListAccessPointsPages(input, func(page *s3control.ListAccessPointsOutput, lastPage bool) bool { if page == nil { @@ -55,7 +57,13 @@ func sweepAccessPoints(region string) error { for _, accessPoint := range page.AccessPointList { r := ResourceAccessPoint() d := r.Data(nil) - d.SetId(AccessPointCreateResourceID(aws.StringValue(accessPoint.AccessPointArn), accountID, aws.StringValue(accessPoint.Name))) + id, err := AccessPointCreateResourceID(aws.StringValue(accessPoint.AccessPointArn)) + if err != nil { + sweeperErr := fmt.Errorf("error composing S3 Access Point ID (%s): %w", aws.StringValue(accessPoint.AccessPointArn), err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + } + d.SetId(id) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } @@ -65,20 +73,28 @@ func sweepAccessPoints(region string) error { if sweep.SkipSweepError(err) { log.Printf("[WARN] Skipping S3 Access Point sweep for %s: %s", region, err) - return nil + return sweeperErrs.ErrorOrNil() } if err != nil { - return fmt.Errorf("error listing SS3 Access Points (%s): %w", region, err) + sweeperErr := fmt.Errorf("error listing S3 Access Points (%s): %w", region, err) + if sweeperErrs.Len() > 0 { + return multierror.Append(sweeperErr, sweeperErrs) + } + return sweeperErr } err = sweep.SweepOrchestrator(sweepResources) if err != nil { - return fmt.Errorf("error sweeping S3 Access Points (%s): %w", region, err) + sweeperErr := fmt.Errorf("error sweeping S3 Access Points (%s): %w", region, err) + if sweeperErrs.Len() > 0 { + return multierror.Append(sweeperErr, sweeperErrs) + } + return sweeperErr } - return nil + return sweeperErrs.ErrorOrNil() } func sweepMultiRegionAccessPoints(region string) error { @@ -151,7 +167,7 @@ func sweepObjectLambdaAccessPoints(region string) error { for _, accessPoint := range page.ObjectLambdaAccessPointList { r := ResourceObjectLambdaAccessPoint() d := r.Data(nil) - d.SetId(AccessPointCreateResourceID(aws.StringValue(accessPoint.ObjectLambdaAccessPointArn), accountID, aws.StringValue(accessPoint.Name))) + d.SetId(ObjectLambdaAccessPointCreateResourceID(accountID, aws.StringValue(accessPoint.Name))) sweepResources = append(sweepResources, sweep.NewSweepResource(r, d, client)) } diff --git a/internal/service/serverlessrepo/cloudformation_stack.go b/internal/service/serverlessrepo/cloudformation_stack.go index 3f1544c049e..deededd3f37 100644 --- a/internal/service/serverlessrepo/cloudformation_stack.go +++ b/internal/service/serverlessrepo/cloudformation_stack.go @@ -352,7 +352,7 @@ func flattenServerlessRepositoryStackCapabilities(stackCapabilities []*string, a func flattenCloudFormationOutputs(cfOutputs []*cloudformation.Output) map[string]string { outputs := make(map[string]string, len(cfOutputs)) for _, o := range cfOutputs { - outputs[*o.OutputKey] = *o.OutputValue + outputs[aws.StringValue(o.OutputKey)] = aws.StringValue(o.OutputValue) } return outputs } diff --git a/internal/service/ses/identity_notification_topic_test.go b/internal/service/ses/identity_notification_topic_test.go index 4e77c30c361..0fd8938ec92 100644 --- a/internal/service/ses/identity_notification_topic_test.go +++ b/internal/service/ses/identity_notification_topic_test.go @@ -119,11 +119,11 @@ func testAccCheckIdentityNotificationTopicExists(n string) resource.TestCheckFun var headersIncluded bool switch notificationType { case ses.NotificationTypeBounce: - headersIncluded = *response.NotificationAttributes[identity].HeadersInBounceNotificationsEnabled + headersIncluded = aws.BoolValue(response.NotificationAttributes[identity].HeadersInBounceNotificationsEnabled) case ses.NotificationTypeComplaint: - headersIncluded = *response.NotificationAttributes[identity].HeadersInComplaintNotificationsEnabled + headersIncluded = aws.BoolValue(response.NotificationAttributes[identity].HeadersInComplaintNotificationsEnabled) case ses.NotificationTypeDelivery: - headersIncluded = *response.NotificationAttributes[identity].HeadersInDeliveryNotificationsEnabled + headersIncluded = aws.BoolValue(response.NotificationAttributes[identity].HeadersInDeliveryNotificationsEnabled) } if headersIncluded != headersExpected { diff --git a/internal/service/signer/signing_profile_permission.go b/internal/service/signer/signing_profile_permission.go index dfac82f5832..a87abecbeae 100644 --- a/internal/service/signer/signing_profile_permission.go +++ b/internal/service/signer/signing_profile_permission.go @@ -97,7 +97,7 @@ func resourceSigningProfilePermissionCreate(d *schema.ResourceData, meta interfa return err } } else { - revisionId = *getProfilePermissionsOutput.RevisionId + revisionId = aws.StringValue(getProfilePermissionsOutput.RevisionId) } statementId := create.Name(d.Get("statement_id").(string), d.Get("statement_id_prefix").(string)) diff --git a/internal/service/sns/topic_test.go b/internal/service/sns/topic_test.go index db2039168e8..773ec2df5dc 100644 --- a/internal/service/sns/topic_test.go +++ b/internal/service/sns/topic_test.go @@ -528,7 +528,7 @@ func testAccCheckNSTopicHasPolicy(n string, expectedPolicyText string) resource. var actualPolicyText string for k, v := range resp.Attributes { if k == "Policy" { - actualPolicyText = *v + actualPolicyText = aws.StringValue(v) break } } @@ -570,7 +570,7 @@ func testAccCheckNSTopicHasDeliveryPolicy(n string, expectedPolicyText string) r var actualPolicyText string for k, v := range resp.Attributes { if k == "DeliveryPolicy" { - actualPolicyText = *v + actualPolicyText = aws.StringValue(v) break } } @@ -634,7 +634,7 @@ func testAccCheckTopicExists(n string, attributes map[string]string) resource.Te } for k, v := range out.Attributes { - attributes[k] = *v + attributes[k] = aws.StringValue(v) } return nil diff --git a/internal/service/swf/domain.go b/internal/service/swf/domain.go index 0b09fe7b638..a9766d1aca1 100644 --- a/internal/service/swf/domain.go +++ b/internal/service/swf/domain.go @@ -129,7 +129,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { return nil } - arn := *resp.DomainInfo.Arn + arn := aws.StringValue(resp.DomainInfo.Arn) tags, err := ListTags(conn, arn) if err != nil { diff --git a/internal/service/waf/byte_match_set.go b/internal/service/waf/byte_match_set.go index 6147e168e5f..160ed207ff1 100644 --- a/internal/service/waf/byte_match_set.go +++ b/internal/service/waf/byte_match_set.go @@ -219,7 +219,7 @@ func diffWafByteMatchSetTuples(oldT, newT []interface{}) []*waf.ByteMatchSetUpda updates = append(updates, &waf.ByteMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), ByteMatchTuple: &waf.ByteMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), TargetString: []byte(tuple["target_string"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), @@ -233,7 +233,7 @@ func diffWafByteMatchSetTuples(oldT, newT []interface{}) []*waf.ByteMatchSetUpda updates = append(updates, &waf.ByteMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), ByteMatchTuple: &waf.ByteMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), TargetString: []byte(tuple["target_string"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), diff --git a/internal/service/waf/flex.go b/internal/service/waf/flex.go index b840c5144e6..a97d86b6bbf 100644 --- a/internal/service/waf/flex.go +++ b/internal/service/waf/flex.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/service/waf" ) -func expandAction(l []interface{}) *waf.WafAction { +func ExpandAction(l []interface{}) *waf.WafAction { if len(l) == 0 || l[0] == nil { return nil } @@ -29,7 +29,7 @@ func expandOverrideAction(l []interface{}) *waf.WafOverrideAction { } } -func expandWebACLUpdate(updateAction string, aclRule map[string]interface{}) *waf.WebACLUpdate { +func ExpandWebACLUpdate(updateAction string, aclRule map[string]interface{}) *waf.WebACLUpdate { var rule *waf.ActivatedRule switch aclRule["type"].(string) { @@ -42,7 +42,7 @@ func expandWebACLUpdate(updateAction string, aclRule map[string]interface{}) *wa } default: rule = &waf.ActivatedRule{ - Action: expandAction(aclRule["action"].([]interface{})), + Action: ExpandAction(aclRule["action"].([]interface{})), Priority: aws.Int64(int64(aclRule["priority"].(int))), RuleId: aws.String(aclRule["rule_id"].(string)), Type: aws.String(aclRule["type"].(string)), @@ -57,7 +57,7 @@ func expandWebACLUpdate(updateAction string, aclRule map[string]interface{}) *wa return update } -func flattenAction(n *waf.WafAction) []map[string]interface{} { +func FlattenAction(n *waf.WafAction) []map[string]interface{} { if n == nil { return nil } @@ -69,7 +69,7 @@ func flattenAction(n *waf.WafAction) []map[string]interface{} { return []map[string]interface{}{result} } -func flattenWebACLRules(ts []*waf.ActivatedRule) []map[string]interface{} { +func FlattenWebACLRules(ts []*waf.ActivatedRule) []map[string]interface{} { out := make([]map[string]interface{}, len(ts)) for i, r := range ts { m := make(map[string]interface{}) @@ -95,7 +95,7 @@ func flattenWebACLRules(ts []*waf.ActivatedRule) []map[string]interface{} { return out } -func expandFieldToMatch(d map[string]interface{}) *waf.FieldToMatch { +func ExpandFieldToMatch(d map[string]interface{}) *waf.FieldToMatch { ftm := &waf.FieldToMatch{ Type: aws.String(d["type"].(string)), } @@ -108,10 +108,10 @@ func expandFieldToMatch(d map[string]interface{}) *waf.FieldToMatch { func FlattenFieldToMatch(fm *waf.FieldToMatch) []interface{} { m := make(map[string]interface{}) if fm.Data != nil { - m["data"] = *fm.Data + m["data"] = aws.StringValue(fm.Data) } if fm.Type != nil { - m["type"] = *fm.Type + m["type"] = aws.StringValue(fm.Type) } return []interface{}{m} } diff --git a/internal/service/waf/geo_match_set.go b/internal/service/waf/geo_match_set.go index f3331556fee..814ebb2ed27 100644 --- a/internal/service/waf/geo_match_set.go +++ b/internal/service/waf/geo_match_set.go @@ -95,7 +95,7 @@ func resourceGeoMatchSetRead(d *schema.ResourceData, meta interface{}) error { } d.Set("name", resp.GeoMatchSet.Name) - d.Set("geo_match_constraint", flattenWafGeoMatchConstraint(resp.GeoMatchSet.GeoMatchConstraints)) + d.Set("geo_match_constraint", FlattenGeoMatchConstraint(resp.GeoMatchSet.GeoMatchConstraints)) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, @@ -158,7 +158,7 @@ func updateGeoMatchSetResource(id string, oldT, newT []interface{}, conn *waf.WA req := &waf.UpdateGeoMatchSetInput{ ChangeToken: token, GeoMatchSetId: aws.String(id), - Updates: diffWafGeoMatchSetConstraints(oldT, newT), + Updates: DiffGeoMatchSetConstraints(oldT, newT), } log.Printf("[INFO] Updating GeoMatchSet constraints: %s", req) diff --git a/internal/service/waf/helpers.go b/internal/service/waf/helpers.go index f44272042ee..f8a7721870a 100644 --- a/internal/service/waf/helpers.go +++ b/internal/service/waf/helpers.go @@ -12,7 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) -func wafSizeConstraintSetSchema() map[string]*schema.Schema { +func SizeConstraintSetSchema() map[string]*schema.Schema { return map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -63,7 +63,7 @@ func wafSizeConstraintSetSchema() map[string]*schema.Schema { } } -func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUpdate { +func DiffSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUpdate { updates := make([]*waf.SizeConstraintSetUpdate, 0) for _, os := range oldS { @@ -77,7 +77,7 @@ func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUp updates = append(updates, &waf.SizeConstraintSetUpdate{ Action: aws.String(waf.ChangeActionDelete), SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), ComparisonOperator: aws.String(constraint["comparison_operator"].(string)), Size: aws.Int64(int64(constraint["size"].(int))), TextTransformation: aws.String(constraint["text_transformation"].(string)), @@ -91,7 +91,7 @@ func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUp updates = append(updates, &waf.SizeConstraintSetUpdate{ Action: aws.String(waf.ChangeActionInsert), SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), ComparisonOperator: aws.String(constraint["comparison_operator"].(string)), Size: aws.Int64(int64(constraint["size"].(int))), TextTransformation: aws.String(constraint["text_transformation"].(string)), @@ -101,33 +101,33 @@ func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUp return updates } -func flattenWafSizeConstraints(sc []*waf.SizeConstraint) []interface{} { +func FlattenSizeConstraints(sc []*waf.SizeConstraint) []interface{} { out := make([]interface{}, len(sc)) for i, c := range sc { m := make(map[string]interface{}) - m["comparison_operator"] = *c.ComparisonOperator + m["comparison_operator"] = aws.StringValue(c.ComparisonOperator) if c.FieldToMatch != nil { m["field_to_match"] = FlattenFieldToMatch(c.FieldToMatch) } - m["size"] = *c.Size - m["text_transformation"] = *c.TextTransformation + m["size"] = aws.Int64Value(c.Size) + m["text_transformation"] = aws.StringValue(c.TextTransformation) out[i] = m } return out } -func flattenWafGeoMatchConstraint(ts []*waf.GeoMatchConstraint) []interface{} { +func FlattenGeoMatchConstraint(ts []*waf.GeoMatchConstraint) []interface{} { out := make([]interface{}, len(ts)) for i, t := range ts { m := make(map[string]interface{}) - m["type"] = *t.Type - m["value"] = *t.Value + m["type"] = aws.StringValue(t.Type) + m["value"] = aws.StringValue(t.Value) out[i] = m } return out } -func diffWafGeoMatchSetConstraints(oldT, newT []interface{}) []*waf.GeoMatchSetUpdate { +func DiffGeoMatchSetConstraints(oldT, newT []interface{}) []*waf.GeoMatchSetUpdate { updates := make([]*waf.GeoMatchSetUpdate, 0) for _, od := range oldT { @@ -161,7 +161,7 @@ func diffWafGeoMatchSetConstraints(oldT, newT []interface{}) []*waf.GeoMatchSetU return updates } -func diffWafRegexPatternSetPatternStrings(oldPatterns, newPatterns []interface{}) []*waf.RegexPatternSetUpdate { +func DiffRegexPatternSetPatternStrings(oldPatterns, newPatterns []interface{}) []*waf.RegexPatternSetUpdate { updates := make([]*waf.RegexPatternSetUpdate, 0) for _, op := range oldPatterns { @@ -185,7 +185,7 @@ func diffWafRegexPatternSetPatternStrings(oldPatterns, newPatterns []interface{} return updates } -func diffWafRulePredicates(oldP, newP []interface{}) []*waf.RuleUpdate { +func DiffRulePredicates(oldP, newP []interface{}) []*waf.RuleUpdate { updates := make([]*waf.RuleUpdate, 0) for _, op := range oldP { @@ -221,7 +221,7 @@ func diffWafRulePredicates(oldP, newP []interface{}) []*waf.RuleUpdate { return updates } -func diffWafRuleGroupActivatedRules(oldRules, newRules []interface{}) []*waf.RuleGroupUpdate { +func DiffRuleGroupActivatedRules(oldRules, newRules []interface{}) []*waf.RuleGroupUpdate { updates := make([]*waf.RuleGroupUpdate, 0) for _, op := range oldRules { @@ -234,7 +234,7 @@ func diffWafRuleGroupActivatedRules(oldRules, newRules []interface{}) []*waf.Rul updates = append(updates, &waf.RuleGroupUpdate{ Action: aws.String(waf.ChangeActionDelete), - ActivatedRule: expandWafActivatedRule(rule), + ActivatedRule: ExpandActivatedRule(rule), }) } @@ -243,24 +243,24 @@ func diffWafRuleGroupActivatedRules(oldRules, newRules []interface{}) []*waf.Rul updates = append(updates, &waf.RuleGroupUpdate{ Action: aws.String(waf.ChangeActionInsert), - ActivatedRule: expandWafActivatedRule(rule), + ActivatedRule: ExpandActivatedRule(rule), }) } return updates } -func flattenWafActivatedRules(activatedRules []*waf.ActivatedRule) []interface{} { +func FlattenActivatedRules(activatedRules []*waf.ActivatedRule) []interface{} { out := make([]interface{}, len(activatedRules)) for i, ar := range activatedRules { rule := map[string]interface{}{ - "priority": int(*ar.Priority), - "rule_id": *ar.RuleId, - "type": *ar.Type, + "priority": aws.Int64Value(ar.Priority), + "rule_id": aws.StringValue(ar.RuleId), + "type": aws.StringValue(ar.Type), } if ar.Action != nil { rule["action"] = []interface{}{ map[string]interface{}{ - "type": *ar.Action.Type, + "type": aws.StringValue(ar.Action.Type), }, } } @@ -269,9 +269,9 @@ func flattenWafActivatedRules(activatedRules []*waf.ActivatedRule) []interface{} return out } -func expandWafActivatedRule(rule map[string]interface{}) *waf.ActivatedRule { +func ExpandActivatedRule(rule map[string]interface{}) *waf.ActivatedRule { r := &waf.ActivatedRule{ - Priority: aws.Int64(int64(rule["priority"].(int))), + Priority: aws.Int64(rule["priority"].(int64)), RuleId: aws.String(rule["rule_id"].(string)), Type: aws.String(rule["type"].(string)), } @@ -285,7 +285,7 @@ func expandWafActivatedRule(rule map[string]interface{}) *waf.ActivatedRule { return r } -func flattenWafRegexMatchTuples(tuples []*waf.RegexMatchTuple) []interface{} { +func FlattenRegexMatchTuples(tuples []*waf.RegexMatchTuple) []interface{} { out := make([]interface{}, len(tuples)) for i, t := range tuples { m := make(map[string]interface{}) @@ -293,24 +293,24 @@ func flattenWafRegexMatchTuples(tuples []*waf.RegexMatchTuple) []interface{} { if t.FieldToMatch != nil { m["field_to_match"] = FlattenFieldToMatch(t.FieldToMatch) } - m["regex_pattern_set_id"] = *t.RegexPatternSetId - m["text_transformation"] = *t.TextTransformation + m["regex_pattern_set_id"] = aws.StringValue(t.RegexPatternSetId) + m["text_transformation"] = aws.StringValue(t.TextTransformation) out[i] = m } return out } -func expandWafRegexMatchTuple(tuple map[string]interface{}) *waf.RegexMatchTuple { +func ExpandRegexMatchTuple(tuple map[string]interface{}) *waf.RegexMatchTuple { ftm := tuple["field_to_match"].([]interface{}) return &waf.RegexMatchTuple{ - FieldToMatch: expandFieldToMatch(ftm[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(ftm[0].(map[string]interface{})), RegexPatternSetId: aws.String(tuple["regex_pattern_set_id"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), } } -func diffWafRegexMatchSetTuples(oldT, newT []interface{}) []*waf.RegexMatchSetUpdate { +func DiffRegexMatchSetTuples(oldT, newT []interface{}) []*waf.RegexMatchSetUpdate { updates := make([]*waf.RegexMatchSetUpdate, 0) for _, ot := range oldT { @@ -323,7 +323,7 @@ func diffWafRegexMatchSetTuples(oldT, newT []interface{}) []*waf.RegexMatchSetUp updates = append(updates, &waf.RegexMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), - RegexMatchTuple: expandWafRegexMatchTuple(tuple), + RegexMatchTuple: ExpandRegexMatchTuple(tuple), }) } @@ -332,7 +332,7 @@ func diffWafRegexMatchSetTuples(oldT, newT []interface{}) []*waf.RegexMatchSetUp updates = append(updates, &waf.RegexMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), - RegexMatchTuple: expandWafRegexMatchTuple(tuple), + RegexMatchTuple: ExpandRegexMatchTuple(tuple), }) } return updates diff --git a/internal/service/waf/rate_based_rule.go b/internal/service/waf/rate_based_rule.go index 63d35bd4910..aed3c87b897 100644 --- a/internal/service/waf/rate_based_rule.go +++ b/internal/service/waf/rate_based_rule.go @@ -244,7 +244,7 @@ func updateWafRateBasedRuleResource(id string, oldP, newP []interface{}, rateLim req := &waf.UpdateRateBasedRuleInput{ ChangeToken: token, RuleId: aws.String(id), - Updates: diffWafRulePredicates(oldP, newP), + Updates: DiffRulePredicates(oldP, newP), RateLimit: aws.Int64(int64(rateLimit.(int))), } diff --git a/internal/service/waf/regex_match_set.go b/internal/service/waf/regex_match_set.go index b3694759f75..0af085a9313 100644 --- a/internal/service/waf/regex_match_set.go +++ b/internal/service/waf/regex_match_set.go @@ -116,7 +116,7 @@ func resourceRegexMatchSetRead(d *schema.ResourceData, meta interface{}) error { } d.Set("name", resp.RegexMatchSet.Name) - d.Set("regex_match_tuple", flattenWafRegexMatchTuples(resp.RegexMatchSet.RegexMatchTuples)) + d.Set("regex_match_tuple", FlattenRegexMatchTuples(resp.RegexMatchSet.RegexMatchTuples)) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, @@ -180,7 +180,7 @@ func updateRegexMatchSetResource(id string, oldT, newT []interface{}, conn *waf. req := &waf.UpdateRegexMatchSetInput{ ChangeToken: token, RegexMatchSetId: aws.String(id), - Updates: diffWafRegexMatchSetTuples(oldT, newT), + Updates: DiffRegexMatchSetTuples(oldT, newT), } return conn.UpdateRegexMatchSet(req) diff --git a/internal/service/waf/regex_pattern_set.go b/internal/service/waf/regex_pattern_set.go index 23892eaec64..61d18365581 100644 --- a/internal/service/waf/regex_pattern_set.go +++ b/internal/service/waf/regex_pattern_set.go @@ -147,7 +147,7 @@ func updateWafRegexPatternSetPatternStrings(id string, oldPatterns, newPatterns req := &waf.UpdateRegexPatternSetInput{ ChangeToken: token, RegexPatternSetId: aws.String(id), - Updates: diffWafRegexPatternSetPatternStrings(oldPatterns, newPatterns), + Updates: DiffRegexPatternSetPatternStrings(oldPatterns, newPatterns), } return conn.UpdateRegexPatternSet(req) diff --git a/internal/service/waf/rule.go b/internal/service/waf/rule.go index 71aa06e49fb..75fda110b1f 100644 --- a/internal/service/waf/rule.go +++ b/internal/service/waf/rule.go @@ -275,7 +275,7 @@ func updateWafRuleResource(id string, oldP, newP []interface{}, conn *waf.WAF) e req := &waf.UpdateRuleInput{ ChangeToken: token, RuleId: aws.String(id), - Updates: diffWafRulePredicates(oldP, newP), + Updates: DiffRulePredicates(oldP, newP), } return conn.UpdateRule(req) diff --git a/internal/service/waf/rule_group.go b/internal/service/waf/rule_group.go index 767282977b8..60ac63c349a 100644 --- a/internal/service/waf/rule_group.go +++ b/internal/service/waf/rule_group.go @@ -171,7 +171,7 @@ func resourceRuleGroupRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags_all: %w", err) } - d.Set("activated_rule", flattenWafActivatedRules(rResp.ActivatedRules)) + d.Set("activated_rule", FlattenActivatedRules(rResp.ActivatedRules)) d.Set("name", resp.RuleGroup.Name) d.Set("metric_name", resp.RuleGroup.MetricName) @@ -241,7 +241,7 @@ func updateWafRuleGroupResource(id string, oldRules, newRules []interface{}, con req := &waf.UpdateRuleGroupInput{ ChangeToken: token, RuleGroupId: aws.String(id), - Updates: diffWafRuleGroupActivatedRules(oldRules, newRules), + Updates: DiffRuleGroupActivatedRules(oldRules, newRules), } return conn.UpdateRuleGroup(req) diff --git a/internal/service/waf/size_constraint_set.go b/internal/service/waf/size_constraint_set.go index 56105be4bb1..1aeb4d43156 100644 --- a/internal/service/waf/size_constraint_set.go +++ b/internal/service/waf/size_constraint_set.go @@ -22,7 +22,7 @@ func ResourceSizeConstraintSet() *schema.Resource { State: schema.ImportStatePassthrough, }, - Schema: wafSizeConstraintSetSchema(), + Schema: SizeConstraintSetSchema(), } } @@ -69,7 +69,7 @@ func resourceSizeConstraintSetRead(d *schema.ResourceData, meta interface{}) err } d.Set("name", resp.SizeConstraintSet.Name) - d.Set("size_constraints", flattenWafSizeConstraints(resp.SizeConstraintSet.SizeConstraints)) + d.Set("size_constraints", FlattenSizeConstraints(resp.SizeConstraintSet.SizeConstraints)) arn := arn.ARN{ Partition: meta.(*conns.AWSClient).Partition, @@ -132,7 +132,7 @@ func updateSizeConstraintSetResource(id string, oldS, newS []interface{}, conn * req := &waf.UpdateSizeConstraintSetInput{ ChangeToken: token, SizeConstraintSetId: aws.String(id), - Updates: diffWafSizeConstraints(oldS, newS), + Updates: DiffSizeConstraints(oldS, newS), } log.Printf("[INFO] Updating WAF Size Constraint constraints: %s", req) diff --git a/internal/service/waf/sql_injection_match_set.go b/internal/service/waf/sql_injection_match_set.go index e9c0f43a8c0..d7d4dac2a38 100644 --- a/internal/service/waf/sql_injection_match_set.go +++ b/internal/service/waf/sql_injection_match_set.go @@ -200,7 +200,7 @@ func diffWafSqlInjectionMatchTuples(oldT, newT []interface{}) []*waf.SqlInjectio updates = append(updates, &waf.SqlInjectionMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) @@ -212,7 +212,7 @@ func diffWafSqlInjectionMatchTuples(oldT, newT []interface{}) []*waf.SqlInjectio updates = append(updates, &waf.SqlInjectionMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) diff --git a/internal/service/waf/web_acl.go b/internal/service/waf/web_acl.go index f7e30105365..2889f416cf7 100644 --- a/internal/service/waf/web_acl.go +++ b/internal/service/waf/web_acl.go @@ -158,7 +158,7 @@ func resourceWebACLCreate(d *schema.ResourceData, meta interface{}) error { out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { params := &waf.CreateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: ExpandAction(d.Get("default_action").([]interface{})), MetricName: aws.String(d.Get("metric_name").(string)), Name: aws.String(d.Get("name").(string)), } @@ -201,7 +201,7 @@ func resourceWebACLCreate(d *schema.ResourceData, meta interface{}) error { _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: ExpandAction(d.Get("default_action").([]interface{})), Updates: diffWebACLRules([]interface{}{}, rules), WebACLId: aws.String(d.Id()), } @@ -249,7 +249,7 @@ func resourceWebACLRead(d *schema.ResourceData, meta interface{}) error { d.Set("arn", resp.WebACL.WebACLArn) arn := aws.StringValue(resp.WebACL.WebACLArn) - if err := d.Set("default_action", flattenAction(resp.WebACL.DefaultAction)); err != nil { + if err := d.Set("default_action", FlattenAction(resp.WebACL.DefaultAction)); err != nil { return fmt.Errorf("error setting default_action: %w", err) } d.Set("name", resp.WebACL.Name) @@ -271,7 +271,7 @@ func resourceWebACLRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags_all: %w", err) } - if err := d.Set("rules", flattenWebACLRules(resp.WebACL.Rules)); err != nil { + if err := d.Set("rules", FlattenWebACLRules(resp.WebACL.Rules)); err != nil { return fmt.Errorf("error setting rules: %w", err) } @@ -308,7 +308,7 @@ func resourceWebACLUpdate(d *schema.ResourceData, meta interface{}) error { _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: ExpandAction(d.Get("default_action").([]interface{})), Updates: diffWebACLRules(oldR, newR), WebACLId: aws.String(d.Id()), } @@ -363,7 +363,7 @@ func resourceWebACLDelete(d *schema.ResourceData, meta interface{}) error { _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: ExpandAction(d.Get("default_action").([]interface{})), Updates: diffWebACLRules(rules, []interface{}{}), WebACLId: aws.String(d.Id()), } @@ -430,7 +430,7 @@ func expandWAFRedactedFields(l []interface{}) []*waf.FieldToMatch { continue } - redactedFields = append(redactedFields, expandFieldToMatch(fieldToMatch.(map[string]interface{}))) + redactedFields = append(redactedFields, ExpandFieldToMatch(fieldToMatch.(map[string]interface{}))) } return redactedFields @@ -493,12 +493,12 @@ func diffWebACLRules(oldR, newR []interface{}) []*waf.WebACLUpdate { newR = append(newR[:idx], newR[idx+1:]...) continue } - updates = append(updates, expandWebACLUpdate(waf.ChangeActionDelete, aclRule)) + updates = append(updates, ExpandWebACLUpdate(waf.ChangeActionDelete, aclRule)) } for _, nr := range newR { aclRule := nr.(map[string]interface{}) - updates = append(updates, expandWebACLUpdate(waf.ChangeActionInsert, aclRule)) + updates = append(updates, ExpandWebACLUpdate(waf.ChangeActionInsert, aclRule)) } return updates } diff --git a/internal/service/waf/xss_match_set.go b/internal/service/waf/xss_match_set.go index a167e4d608b..ca64347e6ab 100644 --- a/internal/service/waf/xss_match_set.go +++ b/internal/service/waf/xss_match_set.go @@ -219,7 +219,7 @@ func diffXSSMatchSetTuples(oldT, newT []interface{}) []*waf.XssMatchSetUpdate { updates = append(updates, &waf.XssMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), XssMatchTuple: &waf.XssMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) @@ -231,7 +231,7 @@ func diffXSSMatchSetTuples(oldT, newT []interface{}) []*waf.XssMatchSetUpdate { updates = append(updates, &waf.XssMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), XssMatchTuple: &waf.XssMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) diff --git a/internal/service/wafregional/byte_match_set.go b/internal/service/wafregional/byte_match_set.go index 06a2c45334c..a45774a00e3 100644 --- a/internal/service/wafregional/byte_match_set.go +++ b/internal/service/wafregional/byte_match_set.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceByteMatchSet() *schema.Resource { @@ -232,7 +233,7 @@ func diffByteMatchSetTuple(oldT, newT []interface{}) []*waf.ByteMatchSetUpdate { updates = append(updates, &waf.ByteMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), ByteMatchTuple: &waf.ByteMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: tfwaf.ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), TargetString: []byte(tuple["target_string"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), @@ -246,7 +247,7 @@ func diffByteMatchSetTuple(oldT, newT []interface{}) []*waf.ByteMatchSetUpdate { updates = append(updates, &waf.ByteMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), ByteMatchTuple: &waf.ByteMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: tfwaf.ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), TargetString: []byte(tuple["target_string"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), diff --git a/internal/service/wafregional/flex.go b/internal/service/wafregional/flex.go deleted file mode 100644 index 55cbe005026..00000000000 --- a/internal/service/wafregional/flex.go +++ /dev/null @@ -1,117 +0,0 @@ -package wafregional - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/waf" -) - -func expandAction(l []interface{}) *waf.WafAction { - if len(l) == 0 || l[0] == nil { - return nil - } - - m := l[0].(map[string]interface{}) - - return &waf.WafAction{ - Type: aws.String(m["type"].(string)), - } -} - -func expandOverrideAction(l []interface{}) *waf.WafOverrideAction { - if len(l) == 0 || l[0] == nil { - return nil - } - - m := l[0].(map[string]interface{}) - - return &waf.WafOverrideAction{ - Type: aws.String(m["type"].(string)), - } -} - -func expandWebACLUpdate(updateAction string, aclRule map[string]interface{}) *waf.WebACLUpdate { - var rule *waf.ActivatedRule - - switch aclRule["type"].(string) { - case waf.WafRuleTypeGroup: - rule = &waf.ActivatedRule{ - OverrideAction: expandOverrideAction(aclRule["override_action"].([]interface{})), - Priority: aws.Int64(int64(aclRule["priority"].(int))), - RuleId: aws.String(aclRule["rule_id"].(string)), - Type: aws.String(aclRule["type"].(string)), - } - default: - rule = &waf.ActivatedRule{ - Action: expandAction(aclRule["action"].([]interface{})), - Priority: aws.Int64(int64(aclRule["priority"].(int))), - RuleId: aws.String(aclRule["rule_id"].(string)), - Type: aws.String(aclRule["type"].(string)), - } - } - - update := &waf.WebACLUpdate{ - Action: aws.String(updateAction), - ActivatedRule: rule, - } - - return update -} - -func flattenAction(n *waf.WafAction) []map[string]interface{} { - if n == nil { - return nil - } - - result := map[string]interface{}{ - "type": aws.StringValue(n.Type), - } - - return []map[string]interface{}{result} -} - -func flattenWebACLRules(ts []*waf.ActivatedRule) []map[string]interface{} { - out := make([]map[string]interface{}, len(ts)) - for i, r := range ts { - m := make(map[string]interface{}) - - switch aws.StringValue(r.Type) { - case waf.WafRuleTypeGroup: - actionMap := map[string]interface{}{ - "type": aws.StringValue(r.OverrideAction.Type), - } - m["override_action"] = []map[string]interface{}{actionMap} - default: - actionMap := map[string]interface{}{ - "type": aws.StringValue(r.Action.Type), - } - m["action"] = []map[string]interface{}{actionMap} - } - - m["priority"] = int(aws.Int64Value(r.Priority)) - m["rule_id"] = aws.StringValue(r.RuleId) - m["type"] = aws.StringValue(r.Type) - out[i] = m - } - return out -} - -func expandFieldToMatch(d map[string]interface{}) *waf.FieldToMatch { - ftm := &waf.FieldToMatch{ - Type: aws.String(d["type"].(string)), - } - if data, ok := d["data"].(string); ok && data != "" { - ftm.Data = aws.String(data) - } - return ftm -} - -func FlattenFieldToMatch(fm *waf.FieldToMatch) []interface{} { - m := make(map[string]interface{}) - if fm.Data != nil { - m["data"] = *fm.Data - } - if fm.Type != nil { - m["type"] = *fm.Type - } - return []interface{}{m} -} diff --git a/internal/service/wafregional/geo_match_set.go b/internal/service/wafregional/geo_match_set.go index 673ab9db865..11e510d8923 100644 --- a/internal/service/wafregional/geo_match_set.go +++ b/internal/service/wafregional/geo_match_set.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceGeoMatchSet() *schema.Resource { @@ -92,7 +93,7 @@ func resourceGeoMatchSetRead(d *schema.ResourceData, meta interface{}) error { } d.Set("name", resp.GeoMatchSet.Name) - d.Set("geo_match_constraint", flattenWafGeoMatchConstraint(resp.GeoMatchSet.GeoMatchConstraints)) + d.Set("geo_match_constraint", tfwaf.FlattenGeoMatchConstraint(resp.GeoMatchSet.GeoMatchConstraints)) return nil } @@ -157,7 +158,7 @@ func updateGeoMatchSetResourceWR(id string, oldConstraints, newConstraints []int req := &waf.UpdateGeoMatchSetInput{ ChangeToken: token, GeoMatchSetId: aws.String(id), - Updates: diffWafGeoMatchSetConstraints(oldConstraints, newConstraints), + Updates: tfwaf.DiffGeoMatchSetConstraints(oldConstraints, newConstraints), } log.Printf("[INFO] Updating WAF Regional Geo Match Set constraints: %s", req) diff --git a/internal/service/wafregional/rate_based_rule.go b/internal/service/wafregional/rate_based_rule.go index 7bb2c6eaa08..8f0739130f2 100644 --- a/internal/service/wafregional/rate_based_rule.go +++ b/internal/service/wafregional/rate_based_rule.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -258,7 +259,7 @@ func updateWafRateBasedRuleResourceWR(id string, oldP, newP []interface{}, rateL req := &waf.UpdateRateBasedRuleInput{ ChangeToken: token, RuleId: aws.String(id), - Updates: diffWafRulePredicates(oldP, newP), + Updates: tfwaf.DiffRulePredicates(oldP, newP), RateLimit: aws.Int64(int64(rateLimit.(int))), } diff --git a/internal/service/wafregional/regex_match_set.go b/internal/service/wafregional/regex_match_set.go index b5b1f21c9e1..9ecdf03dac9 100644 --- a/internal/service/wafregional/regex_match_set.go +++ b/internal/service/wafregional/regex_match_set.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceRegexMatchSet() *schema.Resource { @@ -32,7 +33,7 @@ func ResourceRegexMatchSet() *schema.Resource { "regex_match_tuple": { Type: schema.TypeSet, Optional: true, - Set: WAFRegexMatchSetTupleHash, + Set: tfwaf.RegexMatchSetTupleHash, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "field_to_match": { @@ -109,7 +110,7 @@ func resourceRegexMatchSetRead(d *schema.ResourceData, meta interface{}) error { } d.Set("name", set.Name) - d.Set("regex_match_tuple", flattenWafRegexMatchTuples(set.RegexMatchTuples)) + d.Set("regex_match_tuple", tfwaf.FlattenRegexMatchTuples(set.RegexMatchTuples)) return nil } @@ -158,7 +159,7 @@ func getRegexMatchTuplesFromResourceData(d *schema.ResourceData) []*waf.RegexMat result := []*waf.RegexMatchTuple{} for _, t := range d.Get("regex_match_tuple").(*schema.Set).List() { - result = append(result, expandWafRegexMatchTuple(t.(map[string]interface{}))) + result = append(result, tfwaf.ExpandRegexMatchTuple(t.(map[string]interface{}))) } return result @@ -224,7 +225,7 @@ func updateRegexMatchSetResourceWR(id string, oldT, newT []interface{}, conn *wa req := &waf.UpdateRegexMatchSetInput{ ChangeToken: token, RegexMatchSetId: aws.String(id), - Updates: diffWafRegexMatchSetTuples(oldT, newT), + Updates: tfwaf.DiffRegexMatchSetTuples(oldT, newT), } return conn.UpdateRegexMatchSet(req) diff --git a/internal/service/wafregional/regex_match_set_test.go b/internal/service/wafregional/regex_match_set_test.go index d5283ae2dc6..0e0df7b71f1 100644 --- a/internal/service/wafregional/regex_match_set_test.go +++ b/internal/service/wafregional/regex_match_set_test.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/hashicorp/terraform-provider-aws/internal/acctest" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" tfwafregional "github.com/hashicorp/terraform-provider-aws/internal/service/wafregional" ) @@ -301,12 +302,12 @@ resource "aws_wafregional_regex_match_set" "test" { func computeWafRegexMatchSetTuple(patternSet *waf.RegexPatternSet, fieldToMatch *waf.FieldToMatch, textTransformation string, idx *int) resource.TestCheckFunc { return func(s *terraform.State) error { m := map[string]interface{}{ - "field_to_match": tfwafregional.FlattenFieldToMatch(fieldToMatch), + "field_to_match": tfwaf.FlattenFieldToMatch(fieldToMatch), "regex_pattern_set_id": *patternSet.RegexPatternSetId, "text_transformation": textTransformation, } - *idx = tfwafregional.WAFRegexMatchSetTupleHash(m) + *idx = tfwaf.RegexMatchSetTupleHash(m) return nil } diff --git a/internal/service/wafregional/regex_pattern_set.go b/internal/service/wafregional/regex_pattern_set.go index 9d0d1368086..a7ebdf9508a 100644 --- a/internal/service/wafregional/regex_pattern_set.go +++ b/internal/service/wafregional/regex_pattern_set.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceRegexPatternSet() *schema.Resource { @@ -147,7 +148,7 @@ func updateWafRegionalRegexPatternSetPatternStringsWR(id string, oldPatterns, ne req := &waf.UpdateRegexPatternSetInput{ ChangeToken: token, RegexPatternSetId: aws.String(id), - Updates: diffWafRegexPatternSetPatternStrings(oldPatterns, newPatterns), + Updates: tfwaf.DiffRegexPatternSetPatternStrings(oldPatterns, newPatterns), } return conn.UpdateRegexPatternSet(req) diff --git a/internal/service/wafregional/rule.go b/internal/service/wafregional/rule.go index 9b56c558321..24cd78ee26d 100644 --- a/internal/service/wafregional/rule.go +++ b/internal/service/wafregional/rule.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -223,7 +224,7 @@ func updateWafRegionalRuleResource(id string, oldP, newP []interface{}, meta int req := &waf.UpdateRuleInput{ ChangeToken: token, RuleId: aws.String(id), - Updates: diffWafRulePredicates(oldP, newP), + Updates: tfwaf.DiffRulePredicates(oldP, newP), } return conn.UpdateRule(req) diff --git a/internal/service/wafregional/rule_group.go b/internal/service/wafregional/rule_group.go index 5c3bc82b19f..e597e9d051e 100644 --- a/internal/service/wafregional/rule_group.go +++ b/internal/service/wafregional/rule_group.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -173,7 +174,7 @@ func resourceRuleGroupRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags_all: %w", err) } - d.Set("activated_rule", FlattenWAFActivatedRules(rResp.ActivatedRules)) + d.Set("activated_rule", tfwaf.FlattenActivatedRules(rResp.ActivatedRules)) d.Set("name", resp.RuleGroup.Name) d.Set("metric_name", resp.RuleGroup.MetricName) @@ -245,7 +246,7 @@ func updateWafRuleGroupResourceWR(id string, oldRules, newRules []interface{}, c req := &waf.UpdateRuleGroupInput{ ChangeToken: token, RuleGroupId: aws.String(id), - Updates: diffWafRuleGroupActivatedRules(oldRules, newRules), + Updates: tfwaf.DiffRuleGroupActivatedRules(oldRules, newRules), } return conn.UpdateRuleGroup(req) diff --git a/internal/service/wafregional/size_constraint_set.go b/internal/service/wafregional/size_constraint_set.go index 3e82ef69663..b74ca02124d 100644 --- a/internal/service/wafregional/size_constraint_set.go +++ b/internal/service/wafregional/size_constraint_set.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceSizeConstraintSet() *schema.Resource { @@ -22,7 +23,7 @@ func ResourceSizeConstraintSet() *schema.Resource { State: schema.ImportStatePassthrough, }, - Schema: wafSizeConstraintSetSchema(), + Schema: tfwaf.SizeConstraintSetSchema(), } } @@ -72,7 +73,7 @@ func resourceSizeConstraintSetRead(d *schema.ResourceData, meta interface{}) err } d.Set("name", resp.SizeConstraintSet.Name) - d.Set("size_constraints", flattenWafSizeConstraints(resp.SizeConstraintSet.SizeConstraints)) + d.Set("size_constraints", tfwaf.FlattenSizeConstraints(resp.SizeConstraintSet.SizeConstraints)) return nil } @@ -139,7 +140,7 @@ func updateRegionalSizeConstraintSetResource(id string, oldConstraints, newConst req := &waf.UpdateSizeConstraintSetInput{ ChangeToken: token, SizeConstraintSetId: aws.String(id), - Updates: diffWafSizeConstraints(oldConstraints, newConstraints), + Updates: tfwaf.DiffSizeConstraints(oldConstraints, newConstraints), } log.Printf("[INFO] Updating WAF Regional SizeConstraintSet: %s", req) diff --git a/internal/service/wafregional/sql_injection_match_set.go b/internal/service/wafregional/sql_injection_match_set.go index 36d80c4f696..29be05cde76 100644 --- a/internal/service/wafregional/sql_injection_match_set.go +++ b/internal/service/wafregional/sql_injection_match_set.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceSQLInjectionMatchSet() *schema.Resource { @@ -206,7 +207,7 @@ func diffWafSqlInjectionMatchTuplesWR(oldT, newT []interface{}) []*waf.SqlInject updates = append(updates, &waf.SqlInjectionMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(ftm[0].(map[string]interface{})), + FieldToMatch: tfwaf.ExpandFieldToMatch(ftm[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) @@ -219,7 +220,7 @@ func diffWafSqlInjectionMatchTuplesWR(oldT, newT []interface{}) []*waf.SqlInject updates = append(updates, &waf.SqlInjectionMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(ftm[0].(map[string]interface{})), + FieldToMatch: tfwaf.ExpandFieldToMatch(ftm[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) @@ -249,7 +250,7 @@ func flattenSQLInjectionMatchTuples(ts []*waf.SqlInjectionMatchTuple) []interfac for i, t := range ts { m := make(map[string]interface{}) m["text_transformation"] = aws.StringValue(t.TextTransformation) - m["field_to_match"] = FlattenFieldToMatch(t.FieldToMatch) + m["field_to_match"] = tfwaf.FlattenFieldToMatch(t.FieldToMatch) out[i] = m } diff --git a/internal/service/wafregional/sweep.go b/internal/service/wafregional/sweep.go index bf7ce278449..cd10011f043 100644 --- a/internal/service/wafregional/sweep.go +++ b/internal/service/wafregional/sweep.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" "github.com/hashicorp/terraform-provider-aws/internal/sweep" ) @@ -218,7 +219,7 @@ func sweepRuleGroups(region string) error { if err != nil { return err } - oldRules := FlattenWAFActivatedRules(rResp.ActivatedRules) + oldRules := tfwaf.FlattenActivatedRules(rResp.ActivatedRules) err = DeleteRuleGroup(*group.RuleGroupId, oldRules, conn, region) if err != nil { return err diff --git a/internal/service/wafregional/waf_helpers.go b/internal/service/wafregional/waf_helpers.go deleted file mode 100644 index 81fa9a7a57d..00000000000 --- a/internal/service/wafregional/waf_helpers.go +++ /dev/null @@ -1,357 +0,0 @@ -package wafregional - -import ( - "bytes" - "fmt" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-provider-aws/internal/create" - "github.com/hashicorp/terraform-provider-aws/internal/verify" -) - -func wafSizeConstraintSetSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "arn": { - Type: schema.TypeString, - Computed: true, - }, - "size_constraints": { - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "field_to_match": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "data": { - Type: schema.TypeString, - Optional: true, - }, - "type": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, - "comparison_operator": { - Type: schema.TypeString, - Required: true, - }, - "size": { - Type: schema.TypeInt, - Required: true, - }, - "text_transformation": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, - } -} - -func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUpdate { - updates := make([]*waf.SizeConstraintSetUpdate, 0) - - for _, os := range oldS { - constraint := os.(map[string]interface{}) - - if idx, contains := sliceContainsMap(newS, constraint); contains { - newS = append(newS[:idx], newS[idx+1:]...) - continue - } - - updates = append(updates, &waf.SizeConstraintSetUpdate{ - Action: aws.String(waf.ChangeActionDelete), - SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), - ComparisonOperator: aws.String(constraint["comparison_operator"].(string)), - Size: aws.Int64(int64(constraint["size"].(int))), - TextTransformation: aws.String(constraint["text_transformation"].(string)), - }, - }) - } - - for _, ns := range newS { - constraint := ns.(map[string]interface{}) - - updates = append(updates, &waf.SizeConstraintSetUpdate{ - Action: aws.String(waf.ChangeActionInsert), - SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), - ComparisonOperator: aws.String(constraint["comparison_operator"].(string)), - Size: aws.Int64(int64(constraint["size"].(int))), - TextTransformation: aws.String(constraint["text_transformation"].(string)), - }, - }) - } - return updates -} - -func flattenWafSizeConstraints(sc []*waf.SizeConstraint) []interface{} { - out := make([]interface{}, len(sc)) - for i, c := range sc { - m := make(map[string]interface{}) - m["comparison_operator"] = *c.ComparisonOperator - if c.FieldToMatch != nil { - m["field_to_match"] = FlattenFieldToMatch(c.FieldToMatch) - } - m["size"] = *c.Size - m["text_transformation"] = *c.TextTransformation - out[i] = m - } - return out -} - -func flattenWafGeoMatchConstraint(ts []*waf.GeoMatchConstraint) []interface{} { - out := make([]interface{}, len(ts)) - for i, t := range ts { - m := make(map[string]interface{}) - m["type"] = *t.Type - m["value"] = *t.Value - out[i] = m - } - return out -} - -func diffWafGeoMatchSetConstraints(oldT, newT []interface{}) []*waf.GeoMatchSetUpdate { - updates := make([]*waf.GeoMatchSetUpdate, 0) - - for _, od := range oldT { - constraint := od.(map[string]interface{}) - - if idx, contains := sliceContainsMap(newT, constraint); contains { - newT = append(newT[:idx], newT[idx+1:]...) - continue - } - - updates = append(updates, &waf.GeoMatchSetUpdate{ - Action: aws.String(waf.ChangeActionDelete), - GeoMatchConstraint: &waf.GeoMatchConstraint{ - Type: aws.String(constraint["type"].(string)), - Value: aws.String(constraint["value"].(string)), - }, - }) - } - - for _, nd := range newT { - constraint := nd.(map[string]interface{}) - - updates = append(updates, &waf.GeoMatchSetUpdate{ - Action: aws.String(waf.ChangeActionInsert), - GeoMatchConstraint: &waf.GeoMatchConstraint{ - Type: aws.String(constraint["type"].(string)), - Value: aws.String(constraint["value"].(string)), - }, - }) - } - return updates -} - -func diffWafRegexPatternSetPatternStrings(oldPatterns, newPatterns []interface{}) []*waf.RegexPatternSetUpdate { - updates := make([]*waf.RegexPatternSetUpdate, 0) - - for _, op := range oldPatterns { - if idx, contains := verify.SliceContainsString(newPatterns, op.(string)); contains { - newPatterns = append(newPatterns[:idx], newPatterns[idx+1:]...) - continue - } - - updates = append(updates, &waf.RegexPatternSetUpdate{ - Action: aws.String(waf.ChangeActionDelete), - RegexPatternString: aws.String(op.(string)), - }) - } - - for _, np := range newPatterns { - updates = append(updates, &waf.RegexPatternSetUpdate{ - Action: aws.String(waf.ChangeActionInsert), - RegexPatternString: aws.String(np.(string)), - }) - } - return updates -} - -func diffWafRulePredicates(oldP, newP []interface{}) []*waf.RuleUpdate { - updates := make([]*waf.RuleUpdate, 0) - - for _, op := range oldP { - predicate := op.(map[string]interface{}) - - if idx, contains := sliceContainsMap(newP, predicate); contains { - newP = append(newP[:idx], newP[idx+1:]...) - continue - } - - updates = append(updates, &waf.RuleUpdate{ - Action: aws.String(waf.ChangeActionDelete), - Predicate: &waf.Predicate{ - Negated: aws.Bool(predicate["negated"].(bool)), - Type: aws.String(predicate["type"].(string)), - DataId: aws.String(predicate["data_id"].(string)), - }, - }) - } - - for _, np := range newP { - predicate := np.(map[string]interface{}) - - updates = append(updates, &waf.RuleUpdate{ - Action: aws.String(waf.ChangeActionInsert), - Predicate: &waf.Predicate{ - Negated: aws.Bool(predicate["negated"].(bool)), - Type: aws.String(predicate["type"].(string)), - DataId: aws.String(predicate["data_id"].(string)), - }, - }) - } - return updates -} - -func diffWafRuleGroupActivatedRules(oldRules, newRules []interface{}) []*waf.RuleGroupUpdate { - updates := make([]*waf.RuleGroupUpdate, 0) - - for _, op := range oldRules { - rule := op.(map[string]interface{}) - - if idx, contains := sliceContainsMap(newRules, rule); contains { - newRules = append(newRules[:idx], newRules[idx+1:]...) - continue - } - - updates = append(updates, &waf.RuleGroupUpdate{ - Action: aws.String(waf.ChangeActionDelete), - ActivatedRule: expandWafActivatedRule(rule), - }) - } - - for _, np := range newRules { - rule := np.(map[string]interface{}) - - updates = append(updates, &waf.RuleGroupUpdate{ - Action: aws.String(waf.ChangeActionInsert), - ActivatedRule: expandWafActivatedRule(rule), - }) - } - return updates -} - -func FlattenWAFActivatedRules(activatedRules []*waf.ActivatedRule) []interface{} { - out := make([]interface{}, len(activatedRules)) - for i, ar := range activatedRules { - rule := map[string]interface{}{ - "priority": int(*ar.Priority), - "rule_id": *ar.RuleId, - "type": *ar.Type, - } - if ar.Action != nil { - rule["action"] = []interface{}{ - map[string]interface{}{ - "type": *ar.Action.Type, - }, - } - } - out[i] = rule - } - return out -} - -func expandWafActivatedRule(rule map[string]interface{}) *waf.ActivatedRule { - r := &waf.ActivatedRule{ - Priority: aws.Int64(int64(rule["priority"].(int))), - RuleId: aws.String(rule["rule_id"].(string)), - Type: aws.String(rule["type"].(string)), - } - - if a, ok := rule["action"].([]interface{}); ok && len(a) > 0 { - m := a[0].(map[string]interface{}) - r.Action = &waf.WafAction{ - Type: aws.String(m["type"].(string)), - } - } - return r -} - -func flattenWafRegexMatchTuples(tuples []*waf.RegexMatchTuple) []interface{} { - out := make([]interface{}, len(tuples)) - for i, t := range tuples { - m := make(map[string]interface{}) - - if t.FieldToMatch != nil { - m["field_to_match"] = FlattenFieldToMatch(t.FieldToMatch) - } - m["regex_pattern_set_id"] = *t.RegexPatternSetId - m["text_transformation"] = *t.TextTransformation - - out[i] = m - } - return out -} - -func expandWafRegexMatchTuple(tuple map[string]interface{}) *waf.RegexMatchTuple { - ftm := tuple["field_to_match"].([]interface{}) - return &waf.RegexMatchTuple{ - FieldToMatch: expandFieldToMatch(ftm[0].(map[string]interface{})), - RegexPatternSetId: aws.String(tuple["regex_pattern_set_id"].(string)), - TextTransformation: aws.String(tuple["text_transformation"].(string)), - } -} - -func diffWafRegexMatchSetTuples(oldT, newT []interface{}) []*waf.RegexMatchSetUpdate { - updates := make([]*waf.RegexMatchSetUpdate, 0) - - for _, ot := range oldT { - tuple := ot.(map[string]interface{}) - - if idx, contains := sliceContainsMap(newT, tuple); contains { - newT = append(newT[:idx], newT[idx+1:]...) - continue - } - - updates = append(updates, &waf.RegexMatchSetUpdate{ - Action: aws.String(waf.ChangeActionDelete), - RegexMatchTuple: expandWafRegexMatchTuple(tuple), - }) - } - - for _, nt := range newT { - tuple := nt.(map[string]interface{}) - - updates = append(updates, &waf.RegexMatchSetUpdate{ - Action: aws.String(waf.ChangeActionInsert), - RegexMatchTuple: expandWafRegexMatchTuple(tuple), - }) - } - return updates -} - -func WAFRegexMatchSetTupleHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - if v, ok := m["field_to_match"]; ok { - ftms := v.([]interface{}) - ftm := ftms[0].(map[string]interface{}) - - if v, ok := ftm["data"]; ok { - buf.WriteString(fmt.Sprintf("%s-", strings.ToLower(v.(string)))) - } - buf.WriteString(fmt.Sprintf("%s-", ftm["type"].(string))) - } - buf.WriteString(fmt.Sprintf("%s-", m["regex_pattern_set_id"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["text_transformation"].(string))) - - return create.StringHashcode(buf.String()) -} diff --git a/internal/service/wafregional/web_acl.go b/internal/service/wafregional/web_acl.go index 0b9a0762897..54a13e92d3d 100644 --- a/internal/service/wafregional/web_acl.go +++ b/internal/service/wafregional/web_acl.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -186,7 +187,7 @@ func resourceWebACLCreate(d *schema.ResourceData, meta interface{}) error { out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { params := &waf.CreateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: tfwaf.ExpandAction(d.Get("default_action").([]interface{})), MetricName: aws.String(d.Get("metric_name").(string)), Name: aws.String(d.Get("name").(string)), } @@ -234,7 +235,7 @@ func resourceWebACLCreate(d *schema.ResourceData, meta interface{}) error { _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: tfwaf.ExpandAction(d.Get("default_action").([]interface{})), Updates: diffWebACLRules([]interface{}{}, rules), WebACLId: aws.String(d.Id()), } @@ -287,12 +288,12 @@ func resourceWebACLRead(d *schema.ResourceData, meta interface{}) error { } d.Set("arn", webACLARN) - if err := d.Set("default_action", flattenAction(resp.WebACL.DefaultAction)); err != nil { + if err := d.Set("default_action", tfwaf.FlattenAction(resp.WebACL.DefaultAction)); err != nil { return fmt.Errorf("error setting default_action: %s", err) } d.Set("name", resp.WebACL.Name) d.Set("metric_name", resp.WebACL.MetricName) - if err := d.Set("rule", flattenWebACLRules(resp.WebACL.Rules)); err != nil { + if err := d.Set("rule", tfwaf.FlattenWebACLRules(resp.WebACL.Rules)); err != nil { return fmt.Errorf("error setting rule: %s", err) } @@ -347,7 +348,7 @@ func resourceWebACLUpdate(d *schema.ResourceData, meta interface{}) error { _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: tfwaf.ExpandAction(d.Get("default_action").([]interface{})), Updates: diffWebACLRules(oldR, newR), WebACLId: aws.String(d.Id()), } @@ -404,7 +405,7 @@ func resourceWebACLDelete(d *schema.ResourceData, meta interface{}) error { _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandAction(d.Get("default_action").([]interface{})), + DefaultAction: tfwaf.ExpandAction(d.Get("default_action").([]interface{})), Updates: diffWebACLRules(rules, []interface{}{}), WebACLId: aws.String(d.Id()), } @@ -467,7 +468,7 @@ func expandWAFRegionalRedactedFields(l []interface{}) []*waf.FieldToMatch { continue } - redactedFields = append(redactedFields, expandFieldToMatch(fieldToMatch.(map[string]interface{}))) + redactedFields = append(redactedFields, tfwaf.ExpandFieldToMatch(fieldToMatch.(map[string]interface{}))) } return redactedFields @@ -510,7 +511,7 @@ func flattenWAFRegionalRedactedFields(fieldToMatches []*waf.FieldToMatch) []inte l := make([]interface{}, len(fieldToMatches)) for i, fieldToMatch := range fieldToMatches { - l[i] = FlattenFieldToMatch(fieldToMatch)[0] + l[i] = tfwaf.FlattenFieldToMatch(fieldToMatch)[0] } m := map[string]interface{}{ @@ -530,12 +531,12 @@ func diffWebACLRules(oldR, newR []interface{}) []*waf.WebACLUpdate { newR = append(newR[:idx], newR[idx+1:]...) continue } - updates = append(updates, expandWebACLUpdate(waf.ChangeActionDelete, aclRule)) + updates = append(updates, tfwaf.ExpandWebACLUpdate(waf.ChangeActionDelete, aclRule)) } for _, nr := range newR { aclRule := nr.(map[string]interface{}) - updates = append(updates, expandWebACLUpdate(waf.ChangeActionInsert, aclRule)) + updates = append(updates, tfwaf.ExpandWebACLUpdate(waf.ChangeActionInsert, aclRule)) } return updates } diff --git a/internal/service/wafregional/xss_match_set.go b/internal/service/wafregional/xss_match_set.go index 6d237771952..8ef835e9cb1 100644 --- a/internal/service/wafregional/xss_match_set.go +++ b/internal/service/wafregional/xss_match_set.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" + tfwaf "github.com/hashicorp/terraform-provider-aws/internal/service/waf" ) func ResourceXSSMatchSet() *schema.Resource { @@ -195,7 +196,7 @@ func flattenXSSMatchTuples(ts []*waf.XssMatchTuple) []interface{} { out := make([]interface{}, len(ts)) for i, t := range ts { m := make(map[string]interface{}) - m["field_to_match"] = FlattenFieldToMatch(t.FieldToMatch) + m["field_to_match"] = tfwaf.FlattenFieldToMatch(t.FieldToMatch) m["text_transformation"] = aws.StringValue(t.TextTransformation) out[i] = m } @@ -216,7 +217,7 @@ func diffXSSMatchSetTuples(oldT, newT []interface{}) []*waf.XssMatchSetUpdate { updates = append(updates, &waf.XssMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), XssMatchTuple: &waf.XssMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: tfwaf.ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) @@ -228,7 +229,7 @@ func diffXSSMatchSetTuples(oldT, newT []interface{}) []*waf.XssMatchSetUpdate { updates = append(updates, &waf.XssMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), XssMatchTuple: &waf.XssMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), + FieldToMatch: tfwaf.ExpandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) diff --git a/internal/tfresource/retry.go b/internal/tfresource/retry.go index 1fc7e9990e6..5b3e8f2a469 100644 --- a/internal/tfresource/retry.go +++ b/internal/tfresource/retry.go @@ -21,7 +21,7 @@ type Retryable func(error) (bool, error) func RetryWhenContext(ctx context.Context, timeout time.Duration, f func() (interface{}, error), retryable Retryable) (interface{}, error) { var output interface{} - err := resource.Retry(timeout, func() *resource.RetryError { + err := resource.Retry(timeout, func() *resource.RetryError { // nosemgrep: helper-schema-resource-Retry-without-TimeoutError-check var err error output, err = f()